提问人:Arlo 提问时间:12/20/2022 更新时间:12/20/2022 访问量:44
为什么当我将字符串转换为浮点数时,我会得到不同的答案,而不是从一开始就只使用浮点值
Why am I getting different answers when I convert a string to a float, vs just using the float value from the start
问:
我正在尝试将 2 根弦转换为浮点数,然后将一根绳子提高到另一根弦的幂。由于某种原因,float('x') ** float('y') 与 x ** y 的输出有时不相同
例如:
float('-5') ** float('-5')
0.00032
与
-5 ** -5
0.00032
这工作正常;但是,有些数字没有。 例如:
float('-5.04') ** float('-5.04')
-0.00028596440705202706+3.612570580059258e-05j
与:
-5.04 ** -5.04
-0.0002882372438117746
(顺便说一句,这个底部是正确答案)
关于为什么会发生这种情况的任何建议?
答:
4赞
luk2302
12/20/2022
#1
-5.04 ** -5.04
计算为 因为具有比一元更高的运算符优先级。通过比较结果可以看出:-(5.04 ** -5.04)
**
-
>>> 5.04 ** -5.04
0.0002882372438117746
>>> -5.04 ** -5.04
-0.0002882372438117746
>>> -(5.04 ** -5.04)
-0.0002882372438117746
要“修复”此问题,您需要在第一个数字及其一元数周围添加括号:-
>>> (-5.04) ** -5.04
(-0.0002859644070520271+3.6125705800592075e-05j)
评论
(-5.04) ** (-5.04)
(-5.04) ** -5.04
**
-