Python: Use Polyval To Predict X Passing Y
I have 2 sets of points (X, Y). I want to: Use polifit to fit the line Given a Y predict an X This is the dataset: X Y -0.00001 5.400000e-08 -0.00001
Solution 1:
As I said in the comments, you can subtract the y
value, fit an appropriate degree polynomial, then find it's roots. numpy
is easily good enough for that task.
Here is a simple example:
import numpy as np
x = np.arange(-10, 10.1, 0.3)
y = x ** 2
def find_x_from_y(x, y, deg, value, threshold=1E-6):
# subtract the y value, fit a polynomial, then find the roots of it
r = np.roots(np.polyfit(x, y - value, deg))
# return only the real roots.. due to numerical errors, you
# must introduce a threshold value to its complex part.
return r.real[abs(r.imag) < threshold]
>>> find_x_from_y(x, y, 2, 0.5)
array([ 0.70710678, -0.70710678])
Finding roots is a numerical algorithm, it produces the numerical approximation of the actual roots. This might result in really small, but nonzero imaginary parts. To avoid this, you need a small threshold to distingush real and imaginary roots. This is why you can't really use np.isreal
:
>>> np.isreal(3.2+1E-7j)
False
A visual example with a 3 degree polynomial:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10, 10.1, 0.3)
y = x ** 3 - 3 * x ** 2 - 9 * x
def find_x_from_y(x, y, deg, value, threshold=1E-6):
r = np.roots(np.polyfit(x, y - value, deg))
return r.real[abs(r.imag) < threshold]
value = -10
rts = find_x_from_y(x, y, 3, value)
fig = plt.figure(figsize=(10, 10))
plt.plot(x, y)
plt.axhline(value, color="r")
for r in rts:
plt.axvline(r, color="k")
Post a Comment for "Python: Use Polyval To Predict X Passing Y"