【发布时间】:2023-03-12 07:33:02
【问题描述】:
我已经将一个简单的算法从 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() 并没有改变任何东西。
【问题讨论】:
-
你会想要阅读 Javascript 和浮点运算
-
我看到了浮点问题,但我认为这不是问题所在。如果你在数组中使用不同的测试用例/不同的值,真正的问题会变得更加明显。
-
b//e和c//d在 Python 中进行整数除法并将结果向下舍入为零。你可能想要b/e和c/d代替
标签: javascript python-3.x exponent