Python复数(complex)

Python复数(complex)教程

Python 可以支持复数,复数的虚部用 j 或 J 来表示。如果需要在程序中对复数进行计算,需要导入 Python 的 cmath 模块,在该模块下包含了各种支持复数运算的函数。

案例

复数

定义 Python 中的复数

print("嗨客网(www.haicoder.net)") # 定义复数 foo = 101 + 3j print(foo) print(type(foo)) # 定义复数 bar = -101 - 0.3j print(bar) print(type(bar))

程序运行后,控制台输出如下:

09 Python复数.png

首先,我们定义了一个复数 变量 foo,其实部为 101,其虚部为 3,虚部后面需要加上字母 j。接着,我们定义了一个复数变量 bar,其实部为 -101,其虚部为 -0.3。

我们打印出这两个变量的类型,都是复数类型,即 complex。

复数运算

Python 中的复数运算

print("嗨客网(www.haicoder.net)") # 复数运算 foo = 101 + 3j bar = -1 - 0.3j result = foo + bar print(result) result2 = foo - bar print(result2)

程序运行后,控制台输出如下:

10 Python复数运算.png

首先,我们定义了一个复数变量 foo,其实部为 101,其虚部为 3,虚部后面需要加上字母 j。接着,我们定义了一个复数变量 bar,其实部为 -1,其虚部为 -0.3。

最后,我们使用加减运算,对两个复数进行了加和减的运算,并得出了正确的结果。

Python复数(complex)总结

Python 可以支持复数,复数的虚部用 j 或 J 来表示。