扩展复数库
AlComplex的Python项目详细描述
alComplex
复数库。它使用自己的复数实现。它的主要目标是提供比python中的默认复数实现更完整的api。
很简单:
>>> from AlComplex import I, AlComplex, pi
>>> 2 + 3*I
2.0 + 3.0i
>>> AlComplex(2,3)
2.0 + 3.0i
>>> AlComplex(1)
1.0 + 0.0i
>>> # You can also use Polar Coordinates
>>> AlComplex.polar(2, pi)
0 - 2i
安装
只需运行
pip install AlComplex
它没有外部依赖关系。
详细信息
支持复数和实数的基本运算
>>> -I + 4 + 3*I
4 + 2i
>>> (25+35*I)/5
5.0 + 7.0i
>>> (-8 + 14*I)/(2+3*I)
2.0000000000000018 + 4.000000000000001i
>>> I**I
.20787957635076193 + 0.0i
注意,由于浮点数的行为怪异,我们使用相对相等。如果两个复数的实部和虚部至少接近1e-14
,则它们相等。可以通过将alComplex.Precision修改为0来更改此值。
>>> (-8 + 14*I)/(2+3*I)
2.0000000000000018 + 4.000000000000001i
>>> (-8 + 14*I)/(2+3*I) == 2 + 4*I
True
alComplex对象有一个基本但完整的api:
>>> z = 1 + I
>>> z.real
1.0
>>> z.imag
1.0
>>> z.abs()
1.4142135623730951
>>> z.phase()
0.7853981633974483
>>> z.to_polar()
(1.4142135623730951, 0.7853981633974483)
>>> z.to_rect_coord()
(1,1)
>>> z.conjugate()
1 - i
请注意,有许多别名和获得相同值的方法:
fromAlCompleximportphase,module,conjugate,real,imaginaryz.phase()==z.arg()==z.angle()==phase(z)z.abs()==z.magnitude()==z.module()==abs(z)==module(z)z.real==real(z)z.imag==imaginary(z)z.conjugate()==conjugate(z)
还有一些基本的数学函数,针对复杂的对象进行了优化。
>>> from AlComplex import sin, exp, Ln
>>> from math import pi
>>> exp(2*pi*I)
1.0 + 0.0i
>>> sin(2*pi)
0.0 + 0.0i
>>> sin(2 + I)
1.4031192506220411 - 0.48905625904129324i
>>> Ln(exp(I))
0.0 + 1.0*I
注意,这些函数与cmath
函数的工作方式不同,因为非常小的数字会自动舍入为零。
>>> import cmath
>>> import AlComplex
>>> from math import pi
>>> cmath.sin(2*pi)
(-2.4492935982947064e-16+0j)
>>> AlComplex.sin(2*pi)
0.0 + 0.0i
>>> cmath.sin(2*pi) == 0
False
>>> AlComplex.sin(2*pi) == 0
True
The functions available are sin
, cos
, tan
, sec
, csc
, cot
, asin
, acos
, atan
, sinh
, cosh
, tanh
, sech
, csch
, coth
, asinh
, acosh
, atanh
, exp
, Ln
, sqrt
and inverse
.
如果愿意,可以用j设置复数的表示。
>>> from AlComplex import J, use_j
>>> J
0.0 + 1.0i
>>> use_j(True)
>>> 2 + J
2.0 + 1.0j
>>> use_j(False)
>>> 2 + J
2.0 + 1.0i
对多值函数也有部分支持。它们都会产生发电机。
>>> from AlComplex import int_roots, ln_values
>>> from math import pi
>>> list(int_roots(I, 3))
[0.866025403784439 + 0.5i, -0.866025403784438 + 0.5i, 0.0 - 1.0i]
>>> # Gives log(z.abs()) + (z.phase() + 2*pi*n)*I, where n takes the values from 0 to 2
>>> list(ln_values(I, 0, 3))
[0.0 + 1.5707963267948966i, 0.0 + 7.853981633974483i, 0.0 + 14.137166941154069i]
目前只支持函数的整数根和复对数。还有更多。
您还可以直接获取日志的第n个值
>>> from AlComplex import ln_n_branch
>>> ln_n_branch(I, 2)
0.0 + 14.137166941154069i