note 110824 modified in function.fmod by danbrown

From: Date: Wed, 12 Dec 2012 16:11:31 +0000
Subject: note 110824 modified in function.fmod by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-192495@lists.php.net to get a copy of this message
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 --was-- Note that fmod is NOT equivalent to this basic function: 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: 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 http://php.net/manual/en/function.fmod.php

« previous php.notes (#192495) next »