0

I have a java script function that I'm trying to replicate in python 2, and the java script is doing some kind of precision error wrap around (or something) which I'm having trouble understanding. These are large numbers, but here's the example:

In javascript:

a = 3141592751
b = 1234567890
result = (a*31) ^ b
window.alert(result)

Here, result = -447877661. I'm assuming it's because of a bit limitation on storing large numbers and the related wrap around to a large negative number.

Using python 2:

a = 3141592751
b = 1234567890
result = (a*31) ^ b
print result

Here, result = 98336370147, which is correct mathematically.

How can I replicate the functionality of the javascript code using python? What is the wrap around point? Thanks!

shutch
  • 197
  • 1
  • 1
  • 10
  • Possible duplicate of [How to get the signed integer value of a long in python?](http://stackoverflow.com/questions/1375897/how-to-get-the-signed-integer-value-of-a-long-in-python) – awesoon Dec 18 '15 at 13:00

1 Answers1

1

The limit of a variable in javascript is-

+/- 9007199254740991
i.e., 2^53 -1

One more thing to consider is that if you are dealing with bitwise operators and shift operators to get your job done, they operate on 32-bit ints, so in that case, the max safe integer is-

2^31-1, or 2147483647

Hope it helps!

More reference - MDN and StackOverflow

So, you may have to use this value to wrap your python code.

Note : ^ symbol above represents power of.

Community
  • 1
  • 1
bozzmob
  • 12,364
  • 16
  • 50
  • 73