Forum Moderators: coopster

Message Too Old, No Replies

Interval of Doom!

...I wouldn't want to travel into this interval :)

         

eelixduppy

10:39 pm on Feb 22, 2007 (gmt 0)



Ok...in search of a solution to trillianjedi's question earlier this morning, I've discovered that PHP's modulus operator does not work as it should for a specific range of numbers.

As of right now, the interval:

[2147483649,4294967295]
produces negative remainders. Anything less than the first number (2147483649) and greater than the larger number (4294967295) all have positive moduli. For example:

echo (2147483649 % 2); #echos -1
#
echo (2147483647 % 2); #echos 1

From tests this seems to only happen within this interval. I've checked the documentation and it seems that one of the user-contributed notes addresses the issue somewhat:


Note that operator % (modulus) works just with integers (between -214748348 and 2147483647) while fmod() works with short and large numbers.

Now, this is the best explanation that I can think of that can possibly be correct:

Integers greater than 2147483647 are considered as type float in PHP. Apparently the modulus operator has problems with dealing with floats? So now the problem I have with this explanation is that there is an upper limit to this behavior, 4294967295. Integers greater than this work normally which doesn't work with my reasoning. Does anyone have a reasonable explanation for this?

It kind of bugs me ;)

Thanks!

sned

12:24 am on Feb 23, 2007 (gmt 0)

10+ Year Member



Hmm .. interesting.

2147483647 = 01111111111111111111111111111111

2147483649 = 10000000000000000000000000000001

4294967295 = 11111111111111111111111111111111

4294967295 looks like the max for an unsigned 32 bit integer, I wonder if php assumes that any 32 bit integer with a 1 in the first column is a signed int, therefore a negative number?

-sned

coopster

3:56 am on Feb 23, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Yes, you have to be careful with integers and going beyond the OS capabilities. And there is a difference between 32 bit and 64 bit systems. I recall a thread once where precision was discussed, but can't find the one I am thinking of. Found these though ...

Is a whole number [webmasterworld.com]
testing post variables to be an integer [webmasterworld.com]
getenv("REMOTE_ADDR") [webmasterworld.com]

eelixduppy

1:48 pm on Feb 23, 2007 (gmt 0)



Thanks for the links, coop. I guess the lesson here is that if you are going to be needing the modulus of a larger number, but you don't actually know what the number will be, cast it to float and use fmod [us2.php.net].

Thanks again :)