我们如何使用np.polyfit来拟合多项式而没有常数项

时间:2019-08-30 10:12:32

标签: python numpy

我有两个数组,例如:

x = ([0.004,0.005,0.006,0.007])
y = ([0.001,0.095,0.026,0.307])

我想拟合3度的多项式,但我实际上并不打算在拟合的多项式中包含常数项(截距)。哪种代码适用于这种情况。

我只是尝试

np.polyfit(x,y,3)

但它肯定会返回4个值。

非常感谢任何潜在客户。

2 个答案:

答案 0 :(得分:0)

使用scipy https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html中的curve_fit函数

from scipy.optimize import curve_fit
import numpy as np

# convert your arrays to numpy arrays
x = np.array([0.004,0.005,0.006,0.007])
y = np.array([0.001,0.095,0.026,0.307])

# Choose the function form of your likings here
def f(x, a, b, c):
    return a * x + b * x ** 2 + c * x ** 3

# parameters and parameter covariances
popt, pcov = curve_fit(f, x, y)
a, b, c = popt

答案 1 :(得分:0)

在这种情况下,我会选择scipy的curve_fit方法并在函数中定义我的多边形。

import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

#def a function
def f(x, a, b, c):
    return a*x**3 + b*x**2 + c*x

#convert your data to np arrays
xs = np.array([0.004,0.005,0.006,0.007])
ys = np.array([0.001,0.095,0.026,0.307])

#do the fitting
popt, pcov = curve_fit(f, xs, ys)

#plot the results
plt.figure()
plt.plot(xs,ys)
plt.plot(xs, f(xs, *popt))
plt.grid()
plt.show()

#the parameters
print(popt)
#outputs [ 7.68289022e+06 -7.34702147e+04  1.79106740e+02]