Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objective C cosine

Tags:

objective-c

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?

like image 777
Hashmat Khalil Avatar asked Dec 28 '22 16:12

Hashmat Khalil


1 Answers

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.

like image 53
Marcelo Cantos Avatar answered Jan 25 '23 02:01

Marcelo Cantos