Page 1 of 1
PHP modulus not seeing that there is a remainder
Posted: Fri Apr 20, 2012 10:47 pm
by Joncom
Why is it that when I run this script
Code: Select all
<?php
die("600851475143 mod 3 = " . 600851475143 % 3);
?>
it returns this output
600851475143 mod 3 = 0
but when I perform the math operator 600851475143 / 3 on my Windows calculator I'm given the answer
200283825047.66666666666666666667
Obviously there IS a remainder. So why does PHP not see it?
PS - Is it just me?
Re: PHP modulus not seeing that there is a remainder
Posted: Sat Apr 21, 2012 8:05 am
by Chris
Re: PHP modulus not seeing that there is a remainder
Posted: Sat Apr 21, 2012 12:24 pm
by MikeD
Joncom wrote:Why is it that when I run this script
Code: Select all
<?php
die("600851475143 mod 3 = " . 600851475143 % 3);
?>
it returns this output
600851475143 mod 3 = 0
but when I perform the math operator 600851475143 / 3 on my Windows calculator I'm given the answer
200283825047.66666666666666666667
Obviously there IS a remainder. So why does PHP not see it?
PS - Is it just me?
Unless i'm missing something, to divide you use / in PHP
Re: PHP modulus not seeing that there is a remainder
Posted: Sat Apr 21, 2012 2:17 pm
by Xaleph
The thing is, PHP doesn`t handle large numbers well. If the number is too big, an overlfow occurs and I think ( not sure!) that the overflow returns -1.
You could look into a bigint implementation in PHP that should solve the issue.
Re: PHP modulus not seeing that there is a remainder
Posted: Sat Apr 21, 2012 7:00 pm
by Jackolantern
MikeD wrote:Unless i'm missing something, to divide you use / in PHP
Modulus is different than simple division. Division with / returns how many groups of x you can put y into, including the left-overs (remainder) as a decimal. Modulus or "mod" with %
only returns the remainder as an integer. Kind of like elementary school division where instead of figuring out the decimal, you just put an "R" and some number with what was left after you divided out the whole numbers.
Modulus is useful for a host of calculations, one of which is figuring when to move to the next row in an animation sheet calculation in traditional game development

Re: PHP modulus not seeing that there is a remainder
Posted: Sat Apr 21, 2012 9:02 pm
by Joncom
Xaleph wrote:The thing is, PHP doesn`t handle large numbers well.
Yes. So, apparently my number was too large:
Code: Select all
2^32 -> 4,294,967,296
My number -> 600,851,475,143
The solution I ended up using was to use
bcmod(), a modulus function which handles arbitrarily long integers.
Cheers.
Re: PHP modulus not seeing that there is a remainder
Posted: Sat Apr 21, 2012 9:20 pm
by Jackolantern
Good to know! Thanks
