note 109664 added to function.fmod

From: Date: Tue, 07 Aug 2012 09:06:39 +0000
Subject: note 109664 added to function.fmod
Groups: php.notes 
Request: Send a blank email to php-notes+get-189942@lists.php.net to get a copy of this message
The fmod() function is useful as the integer modulus operator (%) is limited in its range of precision. Making the assumption that any operator has arbitrary precision is not portable. I created a sample code here and ran it off a random virtual server. Do note the output may vary according to your environment but it is sufficient to illustrate the possible gotchas. <?php $checksum = crc32("The quick brown fox jumped over the lazy dog."); $divisor = 256; $a = sprintf("%u", $checksum); echo "sprintf crc32 output a = $a, to divide by $divisor\n"; $r = $a % $divisor; echo "% operator: r = $r \n"; $r = intval(fmod($a, $divisor)); echo "fmod function: r = $r \n"; $r = bcmod($a, $divisor); echo "bcmod function: r = $r \n"; ?> Output: sprintf crc32 output a = 2191738434, to divide by 256 % operator: r = 255 fmod function: r = 66 bcmod function: r = 66 Conclusion: Integer arithmetic operators do not have the precision to work correctly in some applications. In such situations, fmod() can be used in place of the modulus (%) operator. ---- Server IP: 69.147.83.197 Probable Submitter: 220.255.2.129 ---- Manual Page -- http://www.php.net/manual/en/function.fmod.php Edit -- https://master.php.net/note/edit/109664 Del: integrated -- https://master.php.net/note/delete/109664/integrated Del: useless -- https://master.php.net/note/delete/109664/useless Del: bad code -- https://master.php.net/note/delete/109664/bad+code Del: spam -- https://master.php.net/note/delete/109664/spam Del: non-english -- https://master.php.net/note/delete/109664/non-english Del: in docs -- https://master.php.net/note/delete/109664/in+docs Del: other reasons-- https://master.php.net/note/delete/109664 Reject -- https://master.php.net/note/reject/109664 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#189942) next »