Search code examples
phpfloating-pointfmod

fmod returning incorrect result


Why does PHP's fmod function not work as intended. Am I missing something?

fmod(2.0, 0.1); // outputs 0.1

The following should output 0 since 2.0/0.1 = 20 and therefore has no remainder. I'm aware of floating point math errors, but this function is specifically made for floating point numbers, so I'm not sure why it would return an incorrect result.


Solution

  • The closest IEEE 754 64-bit binary number to 0.1 is 0.1000000000000000055511151231257827021181583404541015625. 20 times that is bigger than 2.0. 19 times it is less, with remainder 0.0999999999999998667732370449812151491641998291015625. Depending on how you are printing that remainder it could come out as "0.1".

    The key here is that fmod did exactly what it was supposed to do, given the actual inputs 2.0 and 0.1000000000000000055511151231257827021181583404541015625. The inability to exactly represent 0.1 is a well known consequence of binary floating point.