Search code examples
javascriptpythongoogle-chromefirefoxlargenumber

different answer in javascript and python with large number- Division or mod operator


when i was dealing with some large numbers like,
take any random number 3289568273632879456235 .

I found that in Chrome or Firefox console
3289568273632879456235 % 6 = 0
but in Python shell
3289568273632879456235 % 6 = 5.

after that i found that answer from Python is correct.

so i don't understand why there is different answers.
can anybody explain to me.


Solution

  • This is because javascript has no concept of an integer -- only numbers (which are stored as IEEE floats). Floats have a finite precision, if you try to make a number more precise than the float can represent, it will be "truncated" -- Which is exactly what is happening with your big numbers. Consider the python "equivalent":

    >>> int(float(3289568273632879456235)) % 6
    0L
    

    Here's a few more interesting tidbits to hopefully make the point a little more clear:

    >>> int(float(3289568273632879456235))  # Notice, the different result due to loss of precision.
    3289568273632879706112L
    >>> int(float(3289568273632879456235)) == int(float(3289568273632879456236))  # different numbers, same result due to "truncation"
    True