开发者

objective C cosine

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 N开发者_开发问答SLog 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜