在 Python 中,复数是否是受支持的数据类型? 如果是,如何使用它们?
下面的 复数示例应该是不言自明的,包括最后的错误消息
>>> 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 中,你可以在一个数字后面加上“ j”或者“ J”,这样你就可以很容易地写出复杂的文字:
>>> 1j 1j >>> 1J 1j >>> 1j * 1j (-1+0j)
后缀“ j”来自电气工程,其中变量“ i”通常用于表示电流
复数的类型是 complex ,如果愿意,可以将该类型用作构造函数:
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 有更多处理复数的函数:
cmath
>>> import cmath >>> cmath.sin(2 + 3j) (9.15449914691143-4.168906959966565j)
是的,Python 支持 一个 href = “ https://docs.python.org/3/library/function tions.html # plex”rel = “ nofollow noReferrer”> plex type。
对于数字,巨蟒3支持3种类型的 一个 href = “ https://docs.python.org/3/library/function tions.html # int”rel = “ nofollow noReferrer”> int ,一个 href = “ https://docs.python.org/3/library/function tions.html # plex”rel = “ nofollow noReferrer”> plex type,如下所示:
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
对于数字,巨蟒2支持4种类型的 一个 href = “ https://docs.python.org/2.7/library/function tions.html # int”rel = “ nofollow noReferrer”> int ,一个 href = “ https://docs.python.org/2.7/library/function tions.html # long”rel = “ nofollow noReferrer”> long ,一个 href = “ https://docs.python.org/2.7/library/function tions.html # plex”rel = “ nofollow noReferrer”> plex 类型,如下所示:
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)