Pyh.conf’25: a new PHP conference for the Russian-speaking community

Voting

: two plus two?
(Example: nine)

The Note You're Voting On

nospam at neonit dot de
8 years ago
Note that fmod does not behave like a similar function written in PHP itself does due to the lack of fixing floating point representation errors.

Have a look at this:
<?php
var_dump
(10 / (10 / 3) === 3.0); // bool(true)
var_dump(fmod(10, 10 / 3)); // float(3.3333333333333)
var_dump(fmod(10, 10 / 3) < 10 / 3); // bool(true)
?>

Internally there is no way of exactly representing the result of 10 / 3, so it will always be a bit above or below the actual result. In this case, the example proves it being a bit above the actual result.

PHP seems quite good at auto-fixing floating point representation errors so they behave like the user would expect it. That's why the first line yields true, although the result is slightly below 3 (like 2.9999999999[something]). I failed to trick PHP into rounding or cropping the result to 2.

However, fmod seems to not apply these fixes during calculations. From 10 / 3 it gets a value slightly below 3, floors it to 2 and returns 10 - 2 * 10 / 3, which is slightly less than the actual result of 10 / 3, but looks like 10 / 3 (third line).

Unfortunately, this is not the expected result. See other notes for high quality fixes.

<< Back to user notes page

To Top