简体   繁体   中英

Javascript to python math translation

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM