#35319 [Opn->Bgs]: modulo operator is not coherent with mathematical definition

From: Date: Mon, 21 Nov 2005 22:48:05 +0000
Subject: #35319 [Opn->Bgs]: modulo operator is not coherent with mathematical definition
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-88648@lists.php.net to get a copy of this message
ID: 35319 Updated by: sniper@php.net Reported By: ian at euona dot com -Status: Open +Status: Bogus Bug Type: Math related Operating System: Win XP PHP Version: 5.0.5 New Comment: This is still bogus just for the same reasons as before. Also, RTFM. Previous Comments: ------------------------------------------------------------------------ [2005-11-21 22:12:19] ian at euona dot com Description: ------------ This is the same problem as stated in reports 20365 and 29822. This is indeed not bogus, PHP, C and Javascript are NOT producing the mathematical correct result. Per definition modulus arithmetics create a ring structure containing the values [0,1,...,(n-1)]. THERE ARE NO NEGATIVE NUMBERS! The current behavior is not intuitive and basically incorrect. An integer typecast is not the same as floor. This is a big problem when shifting table fields (e.g. weekdays). Take a look at spreadsheet software. //This is the way % should behave function math_mod($a,$n){$n=abs($n);if($n===0){return NULL;}return $a-$n*floor($a/$n);} //this function emulates ($a%$n) function php_mod($a,$n){return $a-$n*(int)($a/$n);} Reproduce code: --------------- echo -5%7 , ' ', fmod(-5,7),' ', 1%0,' ', 3%-2; Expected result: ---------------- 2 2 NULL 1 Actual result: -------------- -5 -5 NULL 1 ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=35319&edit=1

« previous php.bugs (#88648) next »