Python:使用polyval预测X传递Y

问题描述

我有2组点(X,Y)。我要:

  • 使用polifit来适应线条
  • 给出一个Y来预测一个X

这是数据集:

            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

看起来像这样:

Data to be fitted

我已经看到numpy具有功能polyval。但是在这里,您传递X并获得y。我如何扭转它。

解决方法

正如我在评论中所说,您可以减去y值,拟合适当的次数多项式,然后找到其根。 numpy足以胜任该任务。 这是一个简单的示例:

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,2,0.5)
array([ 0.70710678,-0.70710678])

查找根是一种数值算法,它产生实际根的数值近似值。这可能会导致非常小的虚部,但非零。为避免这种情况,您需要一个较小的阈值来区分实根和虚根。这就是为什么您不能真正使用np.isreal的原因:

>>> np.isreal(3.2+1E-7j)
False

一个3度多项式的视觉示例:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-10,0.3)
y = x ** 3 - 3 * x ** 2 - 9 * x

def find_x_from_y(x,threshold=1E-6):
    r = np.roots(np.polyfit(x,deg))
    return r.real[abs(r.imag) < threshold]

value = -10
rts = find_x_from_y(x,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