1

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.

1
  • 1
    a = 2 + x*1j or use cmath Commented Dec 15, 2020 at 0:27

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Just add to @gilch notes: >>> cmath.sqrt(-1) # 1j >>> y = cmath.sqrt(-1); >>> x * y # 5j
3

Use the complex() constructor:

Code:

x = 5
a = complex(2, x)
print(a)

Output:

(2+5j)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.