1

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.

user3263704
  • 71
  • 1
  • 2
  • 8

3 Answers3

6

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
Rems
  • 4,837
  • 3
  • 27
  • 24
2

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

>>> a = 3
>>> b = 4
>>> complex(a, b)
(3+4j)
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

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

>>> first_number = 10
>>> second_number = 15
>>> complex(first_number, second_number)
(10+15j)
Maninder Singh
  • 829
  • 1
  • 7
  • 13