虚假解析/评估复杂文字 [英] Bogus parsing/eval of complex literals
问题描述
在评估复数时,python喜欢摆弄符号.
When evaluating complex numbers, python likes to fiddle the signs.
>>> -0j
(-0-0j)
>>> (-0-0j)
0j
为什么?
nb:在阅读这个问题时,我注意到了.
nb: I noticed it when reading this question.
推荐答案
这里的问题是Python不会将诸如(-0-0j)
之类的复数解析为文字,它们实际上被解析为一个表达式:
The issue here is that Python doesn't parse complex numbers such as (-0-0j)
as literals, they are actually parsed as an expression:
>>> import ast
>>> ast.dump(ast.parse('(-0-0j)'))
'Module(body=[Expr(value=BinOp(left=UnaryOp(op=USub(), operand=Num(n=0)), op=Sub(), right=Num(n=0j)))])'
所以,这不是一个复杂的文字,而是一个反映的减去一个复杂和一个整数.
So, this is not a complex literal but a reflected subtraction of a complex and an integer.
>>> -0-0j
0j
>>> (0j).__rsub__((0).__neg__())
0j
将int部分强制为具有0j复杂分量,然后我们丢失预期的签名零,因为减去了复杂的分量. 0j - 0j
的结果应带有正号,例如 IEEE 754-2008 规定.
The int part is coerced to having a 0j complex component, and then we lose the expected signed zero from the result because of the subtraction of the complex components. The result of 0j - 0j
should have positive sign, as IEEE 754-2008 dictates.
这可以说是解析器问题,因为零的符号会影响方程的解.但是,问题一直是重复 已关闭为'不是错误",因此看起来该行为不会很快消失.当您关心带符号的零时,初始化复数的可靠方法是调用
This is arguably a parser issue, because the sign of the zero can influence the solutions of equations. However, the issue has been repeatedly raised and closed on the python tracker as 'not a bug', so it doesn't look like that behaviour will be going away any time soon. The reliable way to initialize complex numbers when you care about signed zeros is by calling the complex
built-in:
>>> 0-0j
0j
>>> 0+0j
0j
>>> complex(0., -0.)
-0j
>>> complex(0., +0.)
0j
这篇关于虚假解析/评估复杂文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!