Python中的复数

170 投票
3 回答
372137 浏览
提问于 2025-04-17 07:37

复数在Python中是一个支持的数据类型吗?如果是的话,怎么使用它们呢?

3 个回答

0

是的,复数类型在Python中是支持的。

对于数字,Python 3支持三种类型:整数浮点数复数,具体如下:

print(type(100), isinstance(100, int))
print(type(100.23), isinstance(100.23, float))
print(type(100 + 2j), isinstance(100 + 2j, complex))

输出结果:

<class 'int'> True
<class 'float'> True
<class 'complex'> True

而在Python 2中,支持四种类型:整数长整数浮点数复数,具体如下:

print(type(100), isinstance(100, int))
print(type(10000000000000000000), isinstance(10000000000000000000, long))
print(type(100.23), isinstance(100.23, float))
print(type(100 + 2j), isinstance(100 + 2j, complex))

输出结果:

(<type 'int'>, True)
(<type 'long'>, True)
(<type 'float'>, True)
(<type 'complex'>, True)
19

下面这个例子是关于复数的,应该很容易理解,最后还有一个错误信息的说明。

>>> 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
>>> 
260

在Python中,你可以在数字后面加上‘j’或‘J’,这样就可以把它变成一个虚数,这样写复数就变得简单了:

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

这个‘j’的后缀来源于电气工程,因为在这个领域,通常用‘i’来表示电流。 (这里有更多解释。)

复数的类型是 complex,如果你愿意的话,可以把这个类型当作构造器来使用:

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

复数有一些内置的访问方法:

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

还有一些内置函数也支持复数:

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

标准模块 cmath 提供了更多处理复数的函数:

>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)

撰写回答