Python:使用polyval预测X传递Y
Python: Use polyval to predict X passing 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
看起来像这样:
我看到 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, 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")
我有 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
看起来像这样:
我看到 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, 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")