davem14
(David Emanuel)
January 18, 2024, 12:02am
1
While experimenting with complex numbers, I encountered an unexpected outcome:
>>> (2+2j).imag
2.0
>>> 2+2j.imag
4.0
The first result is as expected, but the second one is not. It appears to have been computed as (2+2)j
for reasons that are unclear.
>>> 2+2j.real
2.0
>>> 2+2j.imag
4.0
While accessing real
, everything is well. However, when attempting to access imag
, the unexpected result is returned.
What might cause this inconsistency?
I am concerned about the potential occurrence of this inconsistency in other cases, which could potentially lead to inaccurate calculations.
bryevdv
(Bryan Van de Ven)
January 18, 2024, 12:09am
2
You are computing this:
In [2]: 2+(2j.imag)
Out[2]: 4.0
kknechtel
(Karl Knechtel)
January 18, 2024, 12:09am
3
No; it’s computed as 2 + (2j.imag)
. Attribute access has higher precedence than arithmetic operators, and the +
is an actual operator, not part of a literal syntax for the complex value.
This is a well-known issue that has been fairly commonly asked about, and there isn’t an obvious way to fix it without breaking anything else.
tjreedy
(Terry Jan Reedy)
January 18, 2024, 4:41am
4
When puzzled by an expression involving at least 2 operations, think about priority.
When in doubt about operation priority, parenthesize.