查找指定复数的 poly1d 解

Find poly1d Solutions for a Specified Complex Number

假设我有一个 np.poly1d 函数:5 x^2 + 2 x + 1。如何生成所有复杂的解决方案 5 x^2 + 2 x + 1 == a,其中 a 是另一个参数输入?

我看到的例子只是改变函数本身,或者在 poly1d 函数中插入变量输入时给出输出(即 5 a^2 + 2 a + 1 的输出)。

很简单,当你进行数学运算时,numpy会为你创建另一个实例:

>>> f = np.poly1d([5,2,1])
>>> a = 2                       # number
>>> b = [1, -2]                 # list
>>> c = np.array([-4, -4, -4])  # numpy array
>>> 
>>> f
poly1d([5, 2, 1])
>>> f-a
poly1d([ 5,  2, -1]
>>> f-b
poly1d([5, 1, 3])
>>> f+c
poly1d([ 1, -2, -3])
>>> 
>>> f.roots                     # roots of f(x) = 0
array([-0.2+0.4j, -0.2-0.4j])
>>> (f-a).roots                 # roots of f(x) - 2 = 0
array([-0.68989795,  0.28989795])
>>> (f-b).roots                 # roots of f(x) - (1x - 2) = 0
array([-0.1+0.76811457j, -0.1-0.76811457j])
>>> (f+c).roots                 # roots of f(x) + (-4x^2 - 4x - 4) = 0
array([ 3., -1.])

但是,如果您尝试使用维度大于 1 的数组,这将引发错误,因为这是一维函数。

>>> d = np.array([[1], [2]])
>>> (f-d).roots
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "\lib\site-packages\numpy\lib\polynomial.py", line 1291, in __sub__
    other = poly1d(other)
  File "\lib\site-packages\numpy\lib\polynomial.py", line 1171, in __init__
    raise ValueError("Polynomial must be 1d only.")
ValueError: Polynomial must be 1d only.