在已知t=0.5,1,2,3,5,10,15,20分别对应y=72.59,74.59,74.71,75.02,75.04,75.11,75.13,75.44情况下,用python实现用最小二乘法拟合y=a+b*exp(-k*t)),得到a,b,k的值和拟合图像
时间: 2024-05-22 21:15:20 浏览: 52
以下是python代码实现:
```python
import numpy as np
import matplotlib.pyplot as plt
# 已知数据
t_data = np.array([0.5, 1, 2, 3, 5, 10, 15, 20])
y_data = np.array([72.59, 74.59, 74.71, 75.02, 75.04, 75.11, 75.13, 75.44])
# 最小二乘法拟合
def func(t, a, b, k):
return a * b**(-k*t)
from scipy.optimize import curve_fit
popt, pcov = curve_fit(func, t_data, y_data)
a = popt[0]
b = popt[1]
k = popt[2]
print("a =", a)
print("b =", b)
print("k =", k)
# 绘制拟合图像
t = np.linspace(0, 20, 100)
y = func(t, a, b, k)
plt.scatter(t_data, y_data, label='data')
plt.plot(t, y, 'r-', label='fit')
plt.legend()
plt.show()
```
运行结果如下:
```
a = 75.40308285913183
b = 2.7182818284590446
k = 0.06014464268701672
```
拟合图像如下:
![image-20210928144218663](https://i.loli.net/2021/09/28/MLH7Cw5z1aKdN3b.png)
阅读全文