Python:使用polyval预测X和Y

2024-10-04 01:30:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两组点(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。我该如何反转它


Tags: 数据函数numpy线路polyvalpolifit
1条回答
网友
1楼 · 发布于 2024-10-04 01:30:13

正如我在评论中所说,你可以减去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, y, 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, 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

相关问题 更多 >