Search code examples
pythonpython-3.xcomplex-numbers

Representing complex numbers in python


I'm new to python, sorry if this seems awfully rudimentary for some. I know complex numbers can be simply represented using j after an integer e.g.

a = 2 + 5j

However when I try something like the code below, python returns an error and doesn't recognise this as being complex?

x = 5

a = 2 + xj

Similarly this doesn't work:

a = 2 + x*j

How can I get around this problem. I'm trying to use this principle is some larger bit of code.


Solution

  • The j is like the decimal point or the e in floating point exponent notation: It's part of the notation for the number literal itself, not some operator you can tack on like a minus sign.

    If you want to multiply x by 1j, you have to use the multiplication operator. That's x * 1j.

    The j by itself is an identifier like x is. It's not number notation if it doesn't start with a dot or digit. But you could assign it a value, like j = 1j, and then x * j would make sense and work.

    Similarly, xj is not implicit multiplication of x and j, but a separate identifier word spelled with two characters. You can use it as a variable name and assign it a separate value, just like the names x, j and foo.