我正在尝试对一些数据进行线性拟合,但我无法在 Python 中获得 curve_fit 来给我任何东西,但斜率和 y 截距为 1。这是我的代码示例:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b):
return a*x + b
# This is merely a sample of some of my actual data
x = [290., 300., 310.]
y = [1.87e+21, 2.07e+21, 2.29e+21]
popt, pcov = curve_fit(func, x, y)
print popt
我也试过给 curve_fit 一个“猜测”,但是当我这样做时,它给了我一个溢出错误,我猜这是因为数字太大了。
最佳答案
另一种不使用 curve_fit
的方法是使用 numpy 的 polyfit 。
import matplotlib.pyplot as plt
import numpy as np
# This is merely a sample of some of my actual data
x = [290., 300., 310.]
y = [1.87e+21, 2.07e+21, 2.29e+21]
xp = np.linspace(290, 310, 100)
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
print (z)
fig, ax = plt.subplots()
ax.plot(x, y, '.')
ax.plot(xp, p(xp), '-')
plt.show()
这会将系数打印为
[2.10000000e+19 -4.22333333e+21]
并生成下图:关于python - 线性曲线拟合总是产生 1 的斜率和 y 截距,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43461067/