This should be self-explanatory
>>> (1+2j).real #Normal Usage
1.0
>>> (1+2j).imag #Normal Usage
2.0
>>> 1+2j.real #Normal Usage
1.0
>>> 1+2j.imag #Flips Out
3.0
>>> 123+657j.real
123.0
>>> 123+657j.imag
780.0
z.imag
somehow adds up the real and imaginary parts.
I found this interesting .. is this a bug or is this an intentional feature?
The problem is that 1+2j.imag
is being parsed as 1+(2j.imag)
. Clearly 2j.imag
is 2.0
, so 1+2j
returns 3.0
. When you do 1+2j.real
, Python adds 1
and 2j.real
. 2j.real
is 0.0
, so you get the correct answer 1.0
in return.
If you parenthesize the complex number, like in your first two examples, you will get the expected results.
This is an operator precedence issue. .
has higher precedence than +
, so you are effectively doing
1+(2j.imag)
which of course is 3.
It is a Very Good Idea™ to always parenthesize complex number literals.
No madness there, really. Here's what happens: the '.' operator has precedence over the +, that's all. That means
>>> 1+2j.imag
is evaluated as 1 + (2j.imag) which is 1 + 2 which is 3. The same is valid for the other examples.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.