我已经将一个简单的算法从 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 res
Python3 结果: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() 没有任何改变。
最佳答案
请注意,它们不是相同的公式。
在你的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
关于javascript - 我的 Javascript 和 Python 代码是否因为指数或其他原因给出了不同的答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60159181/