我已经将一个简单的算法从Python3移植到Javascript,令人惊讶的是,我得到了不同的答案。Python代码如预期的那样工作,我不知道Javascript为什么有不同的工作方式。
下面是Python:
def foo():
theArray = [1,2,3,4,5,6]
a = theArray[0]
b = theArray[1]
c = theArray[2]
d = theArray[3]
e = theArray[4]
f = theArray[5]
res = (((a**2 + b**2 - (d - e)^3 + (b//e)^2)/ ((a**2 + b**2 - (d - e)^3) + c**2 + (f-4)^2 + (c//d)^2))*0.75)
return resPython3结果: 0.32.
以下是Javascript代码:
function foo() {
theArray = [1,2,3,4,5,6]
var a, b, c, d, e, f
a = theArray[0]
b = theArray[1]
c = theArray[2]
d = theArray[3]
e = theArray[4]
f = theArray[5]
res = (((a**2 + b**2 - (d - e)**3 + (b/e)**2)/ ((a**2 + b**2 - (d - e)**3) + c**2 + (f-4)**2 + (c/d)^2))*0.75)
return res
}Javascript结果:0.27。
在Javascript代码中使用Math.pow()不会改变任何事情。
发布于 2020-02-10 22:50:37
请注意,它们不是相同的公式。
在您的python代码中有:
res = (((a**2 + b**2 - (d - e)^3 + (b//e)^2) / ((a**2 + b**2 - (d - e)^3) + c**2 + (f-4)^2 + (c//d)^2))*0.75其中有(d - e)^3,(b//e)^2和(f-4)^2
在您的js代码中有:
res = (((a**2 + b**2 - (d - e)**3 + (b/e)**2) / ((a**2 + b**2 - (d - e)**3) + c**2 + (f-4)**2 + (c/d)^2))*0.75)其中有(d - e)**3、(b//e)**2和(f-4)**2
异或运算与指数运算有很大不同。
另外,请注意,在python中有很多整数除法。在javascript中,类似的内容如下:
(Math.floor(b/e))^2所以正确的js公式应该是:
res = (((a**2 + b**2 - (d - e)^3 + Math.floor(b/e)^2) / ((a**2 + b**2 - (d - e)^3) + c**2 + (f-4)^2 + Math.floor(c/d)^2))*0.75发布于 2020-02-10 22:39:34
我注意到的第一件事是,你有时使用"**“进行指数运算,有时使用"^”。前者是您应该使用的python和javascript (或至少根据w3学校,但无论如何,他们产生不同的结果为我)
我假设您不是按位使用"XOR“运算符,而是在编写"^”时使用指数,因为您在python和js…中都键入了不同的符号。
当我将计算机上"^“的所有实例更改为"**”时,这两种算法都返回0.2361
https://stackoverflow.com/questions/60159181
复制相似问题