不存在一般没有简单的方法。用于任意多项式的闭形式解决方案are not available用于七阶多项式。
在相反方向进行拟合是可能的,但只适用于原始多项式的单调变化区域。如果原始多项式对感兴趣的域有最小或最大值,那么即使y是x的函数,x也不能是y的函数,因为它们之间不存在1对1的关系。
如果你是:(i)确定与重做拟合程序,和(ii)与在同一时间处理您的配合单一单调的区域分段确定,那么你可以做这样的事情:
-
import numpy as np
# generate a random coefficient vector a
degree = 1
a = 2 * np.random.random(degree+1) - 1
# an assumed true polynomial y(x)
def y_of_x(x, coeff_vector):
"""
Evaluate a polynomial with coeff_vector and degree len(coeff_vector)-1 using Horner's method.
Coefficients are ordered by increasing degree, from the constant term at coeff_vector[0],
to the linear term at coeff_vector[1], to the n-th degree term at coeff_vector[n]
"""
coeff_rev = coeff_vector[::-1]
b = 0
for a in coeff_rev:
b = b * x + a
return b
# generate some data
my_x = np.arange(-1, 1, 0.01)
my_y = y_of_x(my_x, a)
# verify that polyfit in the "traditional" direction gives the correct result
# [::-1] b/c polyfit returns coeffs in backwards order rel. to y_of_x()
p_test = np.polyfit(my_x, my_y, deg=degree)[::-1]
print p_test, a
# fit the data using polyfit but with y as the independent var, x as the dependent var
p = np.polyfit(my_y, my_x, deg=degree)[::-1]
# define x as a function of y
def x_of_y(yy, a):
return y_of_x(yy, a)
# compare results
import matplotlib.pyplot as plt
%matplotlib inline
plt.plot(my_x, my_y, '-b', x_of_y(my_y, p), my_y, '-r')
注:此代码不检查单调而只是假定它。
通过玩弄的degree
的价值,你应该看到,看到的代码只能用于良好的a
时degree=1
所有随机值。偶尔对其他学位也可以,但在有很多最小/最大值时不会。它从来没有完美的degree > 1
,因为近似平方根函数的抛物线并不总是工作,等等。
你的意思是使用'p'的'y(x)'值来获得一组'p'为'x(y)',还是使用相同的'x'和'y'数据来找到新的'p'?如果是后者,只需在'polyfit'中交换'x'和'y' ... –