Error adding CGFloat?

I tried to add CGFloat values ​​recursively to my program. And I just realized that in one particular scenario, the total generation was wrong. So that I would not be mistaken in my program logic, I created a simple example of this script (see below), and it 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 ... with the correct result 689580720. However, the second NSLog prints the correct result. I am not sure if this is a mistake, or if I am doing something wrong.

Thanks Murali

+4
source share
1 answer

CGFloat is a single precision float for 32-bit targets such as iOS - it only has a 23-bit mantissa, i.e. about 6-7 significant digits. Use the double type of precision if you need more precision.

You should probably read David Goldberg What Every Computer Scientist Should Know About Floating-Point Arithmetic Before Continuing Training With The Program.

+11
source

All Articles