Note that fmod is NOT equivalent to this basic function:
<?php
function modulo($a, $b) {
return $a - $b * floor($a / $b);
}
?>
because fmod() will return a value with the same sign as $a. In other words the floor() function is not correct as it rounds towards -INF instead of towards zero.
To emulate fmod($a, $b) the correct way is:
<?php
function fmod($a, $b) {
return $a - $b * (($b < 0) ? ceil($a / $b) : floor($a / $b)));
}
?>
Note that both functions will throw a DIVISION BY ZERO if $b is null.
The first function modulo() above is the mathematical function which is useful for working on cyclic structures (such as calender computions or trignonometric functions :
- fmod($a, 2*PI) returns a value in [0..2*PI) if $a is positive
- fmod($a, 2*PI) returns a value in [-2*PI..0] if $a is negative
- modulo($a, 2*PI) returns a value always in [0..2*PI) independantly of the sign of $a