Complex number Data type in Python3

Viewed 132

If I write x=5+j in python3. It shows me type(x) is an int. why this not considered as a complex number?

3 Answers

You forgot write number before j if you write 5+1j and check type you get what you want (complex type), like below:

x = 5+1j
type(x)
#complex

For define complex numbers you can use different approaches.

You can use np.complex like below:

import numpy as np
x  = np.complex(5,1)
type(x)
# complex
print(x)
# (5+1j)

Also You can use cmath:

import cmath

x = complex(5,1)
type(x)
# complex

print(x)
# (5+1j)

You could use the cmath module which allows you to work with complex numbers.

A very simple example of usage:

import cmath

x = 5 + 1*1j

# alternatively
# x = complex(5,1)

print(type(x))
print(x)

Check out more: https://docs.python.org/3/library/cmath.html

It's a standard package, so you don't have to install anything.

The fact that type(x) is int probably means that you already have a variable j in your code, and that variable is an int. Just like this:

>>> j = 10
>>> x = 5 + j
>>> type(x)
<class 'int'>

Now, if you wish to create a complex number, you may either use the built-in complex function:

>>> x = complex(5, 1)
>>> x
(5+1j)
>>> type(x)
<class 'complex'>

or write a literal complex number:

>>> x = 5 + 1j
>>> x
(5+1j)
>>> type(x)
<class 'complex'>

The main difference between this and what you wrote is that 5 + j means "5 plus a variable called j", whereas 5 + 1j means "5 plus the complex number 1j". Remember that j is not the imaginary unit, it is the name of a variable. If you wish to write a complex literal, you need to write something like <number>j. In particular, the imaginary unit can be written as 1j.

Related