CGFloat addition bug?

2019-01-20 11:41发布

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

1条回答
forever°为你锁心
2楼-- · 2019-01-20 12:26

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.

查看更多
登录 后发表回答