php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #35319 modulo operator is not coherent with mathematical definition
Submitted: 2005-11-21 22:12 UTC Modified: 2005-11-21 23:56 UTC
From: ian at euona dot com Assigned:
Status: Not a bug Package: Math related
PHP Version: 5.0.5 OS: Win XP
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
MUST BE VALID
Solve the problem:
30 + 33 = ?
Subscribe to this entry?

 
 [2005-11-21 22:12 UTC] 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

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2005-11-21 23:48 UTC] sniper@php.net
This is still bogus just for the same reasons as before.
Also, RTFM.

 [2005-11-21 23:56 UTC] ian at euona dot com
Just because TFM says it is used that way it does not make it less unintuitive. Math should be the basis of programming languages and if PHP wants to be taken seriously this issue should be addressed.
STFW
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon May 13 17:01:58 2024 UTC