Python:使用polyval预测X传递Y [英] Python: Use polyval to predict X passing Y

查看:49
本文介绍了Python:使用polyval预测X传递Y的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 2 sets of points (X, Y). I want to:

  • 使用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

看起来像这样:

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

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

推荐答案

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

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])

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

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

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

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

这篇关于Python:使用polyval预测X传递Y的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆