开发者

CGFloat addition bug?

I was trying to add some CGFloat values recursively in my program. And I just realized in one particular scenario the total generated was incorrect. To ensure I had nothing wrong开发者_如何学运维 in my program logic, I created a simple example of that scenario (see below) and this printed the same wrong value.

CGFloat arr[3] = {34484000,512085280,143011440};
CGFloat sum = 0.0;
sum = arr[0] + arr[1] + arr[2];

NSLog(@"%f",sum);

int arr1[3] = {34484000,512085280,143011440};
int sum1 = 0.0;
sum1 =  arr1[0] + arr1[1] + arr1[2];

NSLog(@"%d",sum1);

The first NSLog prints 689580736.000000...while the correct result 689580720. However the second NSLog prints the correct result. I am not sure if this is a bug or if I am doing something wrong.

Thanks, Murali


CGFloat is a single precision float on 32 bit targets such as iOS - it only has a 23 bit mantissa, i.e. around 6 - 7 significant digits. Use a double precision type if you need greater accuracy.

You should probably read David Goldberg's What Every Computer Scientist Should Know About Floating-Point Arithmetic before proceeding much further with learning to program.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜