Issue with fmodf for getting the Modulo

145 Views Asked by At

I need to find the modulo for float numbers.

For that, I am using

NSLog(@"value >> %f",fmodf(2.0f, 0.1f));

The output for this should be 0.0f

But I am getting the output value >> 0.1

How?

1

There are 1 best solutions below

2
On

The compiler converts the source text 0.1f to the nearest representable value. The IEEE-754 32-bit floating-point value (which iOS uses) nearest .1 is 0.100000001490116119384765625.

The you evaluate fmodf with the arguments 2 and 0.100000001490116119384765625. After subtracting 19 times the latter value from 2, the residue is 0.099999971687793731689453125, so that is the returned value. When it is rounded to a few digits for display, the result is “0.1”.