Using complex numbers in python

I am new to math. Now I dig into Python data types. I do not understand how to use a complex number. Please give me examples of using complex numbers in Python.

+46
python complex-numbers
03 Dec '11 at 20:12
source share
2 answers

In python, you can put 'j or' J after the number to make it imaginary so you can easily write complex literals:

>>> 1j 1j >>> 1J 1j >>> 1j * 1j (-1+0j) 

The suffix 'j comes from electrical engineering, where the variable' I is usually used for current. ( Reasoning is found here. )

The type of a complex number is complex , and you can use it as a constructor if you want:

 >>> complex(2,3) (2+3j) 

A complex number has some built-in accessors:

 >>> z = 2+3j >>> z.real 2.0 >>> z.imag 3.0 >>> z.conjugate() (2-3j) 

Several built-in functions support complex numbers:

 >>> abs(3 + 4j) 5.0 >>> pow(3 + 4j, 2) (-7+24j) 

The standard cmath module has more functions that handle complex numbers:

 >>> import cmath >>> cmath.sin(2 + 3j) (9.15449914691143-4.168906959966565j) 
+96
Dec 03 '11 at 20:20
source share

The following example for complex numbers should be clear, including an error message at the end

 >>> x=complex(1,2) >>> print x (1+2j) >>> y=complex(3,4) >>> print y (3+4j) >>> z=x+y >>> print x (1+2j) >>> print z (4+6j) >>> z=x*y >>> print z (-5+10j) >>> z=x/y >>> print z (0.44+0.08j) >>> print x.conjugate() (1-2j) >>> print x.imag 2.0 >>> print x.real 1.0 >>> print x>y Traceback (most recent call last): File "<pyshell#149>", line 1, in <module> print x>y TypeError: no ordering relation is defined for complex numbers >>> print x==y False >>> 
+11
Dec 03 2018-11-12T00:
source share



All Articles