Python是否支持复数数据类型?如果是,如何使用它们?
在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)
i
来表示*-1的正平方根吗?并且用j
来表示-1*的负平方根吗? - joseville下面这个关于复数的示例应该是自解释的,包括最后的错误消息。
>>> 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
>>>
是的,在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 支持以下四种类型:int、long、float 和 complex,如下所示:
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)
help(complex)
似乎是一个合法的文档错误,它不像import decimal; help(decimal)
那样显示任何示例。 - smci