📜  Python中的复数 |第 1 套(介绍)

📅  最后修改于: 2022-05-13 01:54:37.662000             🧑  作者: Mango

Python中的复数 |第 1 套(介绍)

不仅是实数, Python还可以使用文件“cmath”处理复数及其相关函数。复数在许多与数学相关的应用程序中都有其用途, Python提供了有用的工具来处理和操作它们。

将实数转换为复数

复数由“ x + yi ”表示。 Python使用函数complex(x,y)将实数 x 和 y 转换为复数。实部可以使用函数real()访问,虚部可以用imag()表示。

# Python code to demonstrate the working of
# complex(), real() and imag()
  
# importing "cmath" for complex number operations
import cmath
  
# Initializing real numbers
x = 5
y = 3
  
# converting x and y into complex number
z = complex(x,y);
  
# printing real and imaginary part of complex number
print ("The real part of complex number is : ",end="")
print (z.real)
  
print ("The imaginary part of complex number is : ",end="")
print (z.imag)

输出:

The real part of complex number is : 5.0
The imaginary part of complex number is : 3.0

复数的相位

在几何上,复数的相位是正实轴与表示复数的向量之间的角度。这也称为复数自变量。 Phase 使用phase()返回,它以复数作为参数。相位范围从-pi 到+pi。即从-3.14 到 +3.14

# Python code to demonstrate the working of
# phase()
  
# importing "cmath" for complex number operations
import cmath
  
# Initializing real numbers
x = -1.0
y = 0.0
  
# converting x and y into complex number
z = complex(x,y);
  
# printing phase of a complex number using phase()
print ("The phase of complex number is : ",end="")
print (cmath.phase(z))

输出:

The phase of complex number is : 3.141592653589793

从极坐标转换为矩形,反之亦然

转换为极坐标是使用polar()完成的,它返回一个pair(r,ph)表示模量 r和相位角 ph 。可以使用abs()显示模数,使用phase()显示相位。
使用rect(r, ph)将复数转换为直角坐标,其中r 是模数ph 是相位角。它返回一个数值等于r * (math.cos(ph) + math.sin(ph)*1j)

# Python code to demonstrate the working of
# polar() and rect()
  
# importing "cmath" for complex number operations
import cmath
import math
  
# Initializing real numbers
x = 1.0
y = 1.0
  
# converting x and y into complex number
z = complex(x,y);
  
# converting complex number into polar using polar()
w = cmath.polar(z)
  
# printing modulus and argument of polar complex number
print ("The modulus and argument of polar complex number is : ",end="")
print (w)
  
# converting complex number into rectangular using rect()
w = cmath.rect(1.4142135623730951, 0.7853981633974483)
  
# printing rectangular form of complex number
print ("The rectangular form of complex number is : ",end="")
print (w)

输出:

The modulus and argument of polar complex number is : (1.4142135623730951, 0.7853981633974483)
The rectangular form of complex number is : (1.0000000000000002+1j)

Python中的复数 |第 2 组(重要函数和常量)