Get the inverse function of a polyfit in numpy
Asked Answered
C

3

7

I have fit a second order polynomial to a number of x/y points in the following way:

poly  = np.polyfit(x, y, 2)

How can I invert this function in python, to get the two x-values corresponding to a specific y-value?

Comport answered 11/2, 2017 at 17:42 Comment(2)
Did you see this #32848105?Cloraclorinda
Also take a look at #23750110Fraxinella
F
14

Here's an example that shows how you can combine your poly with my answer at Inverse function of numpy.polyval().

First some data:

In [44]: x
Out[44]: array([0, 1, 2, 3, 4, 5, 6, 7])

In [45]: y
Out[45]: array([ 9,  4,  0, -1, -1,  4,  8, 16])

Fit a polynomial to the data:

In [46]: poly = np.polyfit(x, y, 2)

Find where the polynomial has the value y0

In [47]: y0 = 4

To do that, create a poly1d object:

In [48]: p = np.poly1d(poly)

And find the roots of p - y0:

In [49]: (p - y0).roots
Out[49]: array([ 5.21787721,  0.90644711])

Check:

In [54]: x0 = (p - y0).roots

In [55]: p(x0)
Out[55]: array([ 4.,  4.])
Fraxinella answered 11/2, 2017 at 18:0 Comment(2)
I don't understand this answer. You want to find the inverse value at 4, and your result is 2 values??Amaurosis
@johnktejik, yes, of course. There are two x values where p(x) is 4.Fraxinella
T
2

np.polyfit returns the coefficients of the best fit polynomial, highest first. Thus your poly contains c2, c1, c0 and you have to solve

.      2
.   c x + c x + c  = y
.    2     1     0

The solution can be found in many places for example here.

Task answered 11/2, 2017 at 17:52 Comment(0)
M
0

Following on Warren's answer

    p = np.poly1d(m1)
    print(p)
    y0 = returns[sr.argmax()]
    x0 = p(y0)
    #x0 = p((p - y0).roots)
    print(x0)
    print(y0)
Mcgehee answered 31/5, 2021 at 3:18 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.