0

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?

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
mayuur
  • 4,736
  • 4
  • 30
  • 65

1 Answers1

4

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”.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • But this is wrong according to common sense. :) Any solutions about how we could achieve the right result?? – mayuur Mar 16 '13 at 12:43
  • 2
    @mayuur: You need to supply context for the problem you are trying to solve. Why do you want to find a residue? Note that `fmodf` has returned the correct result; it returns the exact mathematical operands for the arguments it is given. You gave it inaccurate arguments. In some situations, you might be able to give it accurate arguments by scaling your values (e.g., to integers) so there is no rounding error. In others, you design to accept rounding errors. – Eric Postpischil Mar 16 '13 at 12:55