Question

How to write a complex number in python? Indeed I have:

import math
a=3
b=4
function=a*j*x+b*y

I don't want to write directly 3j in my function since I absolutely want to use a, so how to convert a into a complex number? Cause in matlab it works when printing :

a=3
b=a*i

The result will gave: 0 + 3.0000i

Thank you for your answers.

Was it helpful?

Solution

j alone is a variable, you can have the complex number by typing 1j

>>> type(j)
NameError: name 'j' is not defined
>>> type(1j)
<type 'complex'>

So your code can be written as a function as

def function(x, y):
    a = 3
    b = 4
    return a*1j*x+b*y

OTHER TIPS

You can use the complex function to create a complex number from variables:

>>> a = 3
>>> b = 4
>>> complex(a, b)
(3+4j)

You can simply use Python's Built in complex() function

>>> first_number = 10
>>> second_number = 15
>>> complex(first_number, second_number)
(10+15j)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top