Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 871
greatwitenorth Avatar asked Feb 18 '26 09:02

greatwitenorth


1 Answers

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.

like image 115
Patricia Shanahan Avatar answered Feb 20 '26 23:02

Patricia Shanahan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!