在python中,复数是受支持的数据类型吗?如果是这样,您将如何使用它们?
发布于 2011-12-04 04:20:43
在python中,你可以把‘j’或‘J’放在一个数字后面,使它成为虚构的,这样你就可以很容易地写出复杂的文字:
>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)
“j”后缀来自电气工程,其中变量“i”通常用于表示电流。(Reasoning found here.)
The type of a complex number is 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)
The standard module cmath
有更多处理复数的函数:
>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)
发布于 2011-12-04 04:18:10
下面的complex numbers示例应该是不言自明的,包括末尾的错误消息
>>> 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
>>>
https://stackoverflow.com/questions/8370637
复制相似问题