I was wondering is there a convenient inverse function of np.polyval(), where I give the y value and it solves for x?
I know one way I could do this is:
import numpy as np
# Set up the question
p = np.array([1, 1, -10])
y = 100
# Solve
p_temp = p
p_temp[-1] -= y
x = np.roots(p_temp)
However my guess is most would agree on that this code has low readability. Any suggestions?
How about something like this?
In [19]: p = np.poly1d([1, 1, -10]) # Use a poly1d to represent the polynomial.
In [20]: y = 100
In [21]: (p - y).roots
Out[21]: array([-11., 10.])
The poly1d
object implements the arithmetic operations to return a new poly1d
object, so p - y
is a new poly1d
:
In [22]: p - y
Out[22]: poly1d([ 1, 1, -110])
The roots
attribute of a poly1d
returns what you would expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With