Python多项式处理基础命令#

NumPyPython 生态中的地位无需再多言,完全可以说「没有NumPy就没有Python在大数据和机器学习领域的流行」。 在NumPy 1.4前,对多项式的操作使用的包是 numpy.poly1d ; NumPy 1.4 后(当下版本1.23),推荐使用更方便易用的包numpy.polynomial

引用方法如下:

from numpy.polynomial import Polynomial
p = Polynomial([3, 2, 1])
print(p)
p
3.0 + 2.0·x¹ + 1.0·x²
\[x \mapsto \text{3.0} + \text{2.0}\,x + \text{1.0}\,x^{2}\]

具有下述属性:

# 系数
p.coef
array([3., 2., 1.])
# 定义域 : 默认为[-1,1]
p.domain
array([-1,  1])
# 窗口: 默认为[-1,1]
p.window
array([-1,  1])

基本代数算术操作#

加/减/乘/乘方

p + p
\[x \mapsto \text{6.0} + \text{4.0}\,x + \text{2.0}\,x^{2}\]
p - p
\[x \mapsto \color{LightGray}{\text{0.0}}\]
p * p
\[x \mapsto \text{9.0} + \text{12.0}\,x + \text{10.0}\,x^{2} + \text{4.0}\,x^{3} + \text{1.0}\,x^{4}\]
p ** 2
\[x \mapsto \text{9.0} + \text{12.0}\,x + \text{10.0}\,x^{2} + \text{4.0}\,x^{3} + \text{1.0}\,x^{4}\]

除法

p // Polynomial([-1, 1])
\[x \mapsto \text{3.0} + \text{1.0}\,x\]
p / 2
\[x \mapsto \text{1.5} + \text{1.0}\,x + \text{0.5}\,x^{2}\]

余数

p % Polynomial([-1, 1])
\[x \mapsto \text{6.0}\]

带余除法

quo, rem = divmod(p, Polynomial([-1, 1]))
print(quo,rem)
3.0 + 1.0·x¹ 6.0

求值

x = np.arange(5)
p(x)
array([ 3.,  6., 11., 18., 27.])
x = np.arange(6).reshape(3,2)
p(x)
array([[ 3.,  6.],
       [11., 18.],
       [27., 38.]])

代换(将x代换为相应值)

p(p)
\[x \mapsto \text{18.0} + \text{16.0}\,x + \text{12.0}\,x^{2} + \text{4.0}\,x^{3} + \text{1.0}\,x^{4}\]

求根

p.roots()
array([-1.-1.41421356j, -1.+1.41421356j])

直接用list表示多项式

p + [1,2,3]
\[x \mapsto \text{4.0} + \text{4.0}\,x + \text{4.0}\,x^{2}\]
[1,2,3] * p
\[x \mapsto \text{3.0} + \text{8.0}\,x + \text{14.0}\,x^{2} + \text{8.0}\,x^{3} + \text{3.0}\,x^{4}\]

微积分操作#

下界-1,积分常数2,二重积分

p.integ(2,lbnd=-1,k=2)
\[x \mapsto \text{3.083333333333333} + \text{4.333333333333333}\,x + \text{1.5}\,x^{2} + \text{0.3333333333333333}\,x^{3} + \text{0.08333333333333333}\,x^{4}\]

二阶导数

p.deriv(2)
\[x \mapsto \text{2.0}\]

其他多项式构造方法#

从根构造

p = Polynomial.fromroots([1, 2, 3])
p
\[x \mapsto \text{-6.0} + \text{11.0}\,x - \text{6.0}\,x^{2} + \text{1.0}\,x^{3}\]
Polynomial.basis(3)
\[x \mapsto \color{LightGray}{\text{0.0}}\color{LightGray}{ + \text{0.0}\,x}\color{LightGray}{ + \text{0.0}\,x^{2}} + \text{1.0}\,x^{3}\]

插值#

rng = np.random.default_rng()
x = np.arange(10)
y = np.arange(10) + rng.standard_normal(10)
p_fitted = Polynomial.fit(x, y, deg=2)
p_fitted
\[x \mapsto \text{4.492417291372314} + \text{4.042024325791734}\,\left(\text{-1.0} + \text{0.2222222222222222}x\right) - \text{0.048761234928195965}\,\left(\text{-1.0} + \text{0.2222222222222222}x\right)^{2}\]

参考#