简体   繁体   中英

Performing Javascript floating point arithmetic in Python

I am writing a Python program which interacts with a webapp which I did not write. There is some state that I need to represent in my program which is not sent to the (javascript) client by the server, but is instead computed separately on both the client and the server with shared information.

For example, the exchange might go something like:

var x = getValueFromServer(); //client gets 0.73346
x *= 1 << 30;
result = x & 1023

My Python code successfully receives 0.73346, but I need the value of result . The result of the multiplication by 2^30 seems to be the same in javascript and Python, but I cannot directly mask the float value inside Python.

I have tried (for the above example value)

from struct import pack, unpack
unpack('q', pack('d', 0.73346))[0] & 1023

but this gives a value of 696 in Python, while when I run the above javascript in node I get a value of 566. I've also tried a few other combinations of packing and unpacking formats, with no success.

My last resort would be executing javascript from inside Python with a node subprocess, but I'd prefer to avoid that. How can I solve this?

x = 0.73346
x = x * (1 << 30)
x = int(x) & 1023

gives 566 in python

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