简体   繁体   English

在Python中执行Javascript浮点运算

[英]Performing Javascript floating point arithmetic in Python

I am writing a Python program which interacts with a webapp which I did not write. 我正在编写一个Python程序,它与我没写过的webapp交互。 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. 我需要在我的程序中表示一些状态,该状态不是由服务器发送到(javascript)客户端,而是在客户端和服务器上分别使用共享信息计算。

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 . 我的Python代码成功收到0.73346,但我需要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. 乘以2 ^ 30的结果在javascript和Python中似乎是相同的,但我无法直接掩盖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. 但是这在Python中给出了696的值,而当我在节点中运行上面的javascript时,得到的值为566.我还尝试了一些打包和解包格式的其他组合,但没有成功。

My last resort would be executing javascript from inside Python with a node subprocess, but I'd prefer to avoid that. 我的最后一招是使用节点子进程从Python内部执行javascript,但我宁愿避免这种情况。 How can I solve this? 我怎么解决这个问题?

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

gives 566 in python 在python中给出566

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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