Home > database >  Find poly1d Solutions for a Specified Complex Number
Find poly1d Solutions for a Specified Complex Number

Time:09-26

Imagine I have a np.poly1d function: 5 x^2 2 x 1. How do I produce all complex solutions 5 x^2 2 x 1 == a, where a is another parameter input?

The examples I've seen just play with altering the functions, themselves, or give outputs when inserting inputs for the variable in the poly1d function (i.e., the output of 5 a^2 2 a 1).

CodePudding user response:

It is very simple, numpy will create another instance for you when you put it in math operation:

>>> 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.])

However, this will throw error if you try with array that has dimension greater than 1, since this is a 1d function.

>>> 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.
  • Related