0

I am building a calculator and I need to use cosinus. It works fine if I try cos(0), cos(30), but I get an odd output for cos(90) - 6.12323399573677e-17.
I checked the output for my radiansToDegrees and it looks ok.
Sinus works fine, for all the codes.
The numbers are in degrees not radians.
I use the latest xCode.

My code:

import Foundation
...
func radiansToDegrees (radians: Double)->Double {
    return radians * 180 / M_PI
}
...
let number = degreesToRadians(Double(digitsLabel.text!)!)
digitsLabel.text = "\(cos(number))"

Does anyone have an idea what is wrong?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Rado
  • 155
  • 12
  • What happens if you do `print(number)`. It's difficult to debug this and you haven't shown what digitsLabel.text is. – Fogmeister Feb 08 '16 at 15:24
  • 7
    cos(90) is 0, 6.12323399573677e-17 is very very close to 0. Its probably just a double accuracy issue. http://stackoverflow.com/questions/28947289/swift-double-conversion-inconsistency-how-to-correctly-compare-doubles – Will M. Feb 08 '16 at 15:24
  • digitsLabel is an UILabel for inputing a number. Treat the variable number as a Double. – Rado Feb 08 '16 at 15:26
  • 2
    If you have to deal with input in *degrees* then __sinpi/__cospi offer more accuracy, compare http://stackoverflow.com/a/6575277/1187415 and (for Swift) http://stackoverflow.com/a/28600210/1187415. – Martin R Feb 08 '16 at 15:36
  • @MartinR: the degrees are a red herring. In playground `cos(M_PI_2)` is 6.123233995736766e-17. – Grimxn Feb 08 '16 at 15:41
  • @Grimxn: Yes, but `print(__cospi(90.0/180.0))` prints `0.0`. The advantage of that (non-standard) functions can be that you *don't* have to multiply with π. – Martin R Feb 08 '16 at 15:44

0 Answers0