davedelong / DDMathParser

String → Number
MIT License
854 stars 153 forks source link

sin(π()) != 0 #148

Closed baryon closed 6 years ago

baryon commented 6 years ago

the result of sin(π) is not zero. sin(π()) = 1.22464679914735e-16

davedelong commented 6 years ago

Sadly, this is a duplicate of issue #99. There’s not much I can do about it without a whole new math library (see issue #111).

Roman-Kerimov commented 5 years ago

This can be fixed so:

extension Double {
    func isDivisible(by value: Double) -> Bool {
        let decimalNumberFormatter = NumberFormatter.init()
        decimalNumberFormatter.numberStyle = .decimal
        return decimalNumberFormatter.string(from: .init(value: self/value))?.contains(decimalNumberFormatter.decimalSeparator) == false
    }
}

func sin(_ value: Double) -> Double {
    return value.isDivisible(by: .pi) ? 0 : Foundation.sin(value)
}

func cos(_ value: Double) -> Double {
    return (.pi/2+value).isDivisible(by: .pi) ? 0 : Foundation.cos(value)
}

func tan(_ value: Double) -> Double {
    return value.isDivisible(by: .pi) ? 0 : (.pi/2+value).isDivisible(by: .pi) ? .infinity : Foundation.tan(value)
}