I'm just facing weird problem with cos function in objective c. I have the xcode 4.1.1 with iOS 4.3 SDK installed.
I'm calculating the cos of a number:
y= cos(x*M_PI/180)
this returns correct answer for almost all numbers except for 90 degree.
y=cos(90*M_PI/180)
y is 6.12323e-17! which is not correct. it should be 0.
the NSLog shows something different:
operand=cos(operand * M_PI / 180);
NSLog(@"cos: %d", operand);
result: cos: -832086752
I don't get. Can someone explain it please?
Floating point arithmetic isn't precise. 90*M_PI/180
is not exactly π/2 because floating-point hardware can't represent transcendental numbers exactly.
The result in NSLog
is because operand
is (I presume) a float
or double
, and you've told NSLog
to interpret it as an int
(%d
). Use %f
or %g
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With