Python: Use polyval to predict X passing Y

ぃ、小莉子 提交于 2021-01-29 07:31:46

问题


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  5.700000e-08
       0.67187  1.730000e-07
       1.99997  9.150000e-07
       2.67242  1.582000e-06
       4.00001  3.734000e-06
       4.67193  5.414000e-06
       5.99998  9.935000e-06
       6.67223  1.311300e-05
       8.00000  2.102900e-05

Which looks like this:

I have seen numpy has the function polyval. But here you pass an X and get a y. How do i reverse it.


回答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")

1



来源:https://stackoverflow.com/questions/63668483/python-use-polyval-to-predict-x-passing-y

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!