评估输出不一致

huangapple go评论59阅读模式
英文:

Eval giving inconsistent outputs

问题

在使用 Python 中的 eval 函数进行实验时,我发现 eval 函数的工作方式与我预期的不同。

当我传递 eval("(-0.02)**(1/3)") 时,输出结果为 (0.13572088082974537+0.23507546124511977j)

但是当执行 eval("-0.02**(1/3)") 时,输出结果为 -0.2714417616594907

我尝试使用正数而不是负数,它却正常工作了。

eval("(0.02)**(1/3)")
0.2714417616594907

eval("0.02**(1/3)")
0.2714417616594907

有人能解释为什么会发生这种情况以及原因吗?

英文:

While experimenting with the eval function in python I found that eval function was not working as I excepted it to do

when I passed eval("(-0.02)**(1/3)") the output was (0.13572088082974537+0.23507546124511977j)

but when eval("-0.02**(1/3)")was executed the output was -0.2714417616594907

I tried using positive numbers instead and it worked

eval("(0.02)**(1/3)")
0.2714417616594907

eval("0.02**(1/3)")
0.2714417616594907

Can someone explain what and why is it happening

答案1

得分: 1

这是因为 **(幂运算)比 -(一元取反)具有更高的优先级(参见手册)。因此,

-0.02**(1/3)

被计算为

-(0.02**(1/3))

-0.2714417616594907

相比之下,在 (-0.02)**(1/3) 中的 () 使得计算 -0.02 的立方根,结果是 0.13572088082974537+0.23507546124511977j(一个复数)。

请注意,这与 eval 无关,将这些表达式键入Python解释器将得到相同的结果。

英文:

This is because ** (exponentiation) has higher precedence than - (unary negation) (see the manual). As a result,

-0.02**(1/3)

is evaluated as

-(0.02**(1/3))

i.e.

-0.2714417616594907

By comparison, the () around -0.02 in (-0.02)**(1/3) makes that the computation of the cube root of -0.02, which is 0.13572088082974537+0.23507546124511977j (a complex number).

Note this has nothing to do with eval, you will get the same results by typing those expressions into the python interpreter.

huangapple
  • 本文由 发表于 2023年3月1日 13:56:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75600032.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定