Python中的复数

170

Python是否支持复数数据类型?如果是,如何使用它们?


1
你说你对数学很新,你能用数学符号写出你想做的事情吗? - mmmmmm
26
我认为这个问题不应该被关闭。我也觉得使用工程常见的 'j' 虚数语法比数学、统计学、R等常见的更直观的 'i' 语法让人感到困惑。下面的第一个答案介绍得很好。 - Mittenchops
2
在Python中,help(complex)似乎是一个合法的文档错误,它不像import decimal; help(decimal)那样显示任何示例。 - smci
3个回答

258

在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)

14
“i”也被数学家、物理学家以及几乎所有其他科学家使用。如果这还不够令人困惑,有些人使用“i”来代表1的“正”平方根,而“j”则是1的“负”平方根。因此,i == -j。FYJ... - jvriesem
2
@jvriesem "1的正平方根"是1。你的意思是他们用i来表示*-1的正平方根吗?并且用j来表示-1*的负平方根吗? - joseville
当前的i/j参数有点弱,j用于表示电流密度。 - copper.hat

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

0

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

对于数字,Python 3支持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 支持以下四种类型:intlongfloatcomplex,如下所示:

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接