python数学建模代码
时间: 2023-07-22 12:34:08 浏览: 105
以下是一个简单的Python数学建模代码示例,它使用了numpy和matplotlib库:
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义模型函数
def model_func(x, a, b, c):
return a * np.exp(-b * x) + c
# 生成模拟数据
x_data = np.linspace(0, 5, num=50)
y_data = model_func(x_data, 2.5, 1.3, 0.5) + np.random.normal(scale=0.3, size=50)
# 使用最小二乘法拟合模型
from scipy.optimize import curve_fit
popt, pcov = curve_fit(model_func, x_data, y_data)
# 绘制原始数据和拟合曲线
plt.scatter(x_data, y_data)
plt.plot(x_data, model_func(x_data, *popt), 'r-', label='Fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()
```
该代码生成一个模拟数据集,其中包含50个点,使用最小二乘法拟合一个指数形式的模型函数,并将原始数据和拟合曲线绘制到一个图表中。这个示例代码可以作为一个基础模板,用于更复杂的数学建模问题。
阅读全文
相关推荐
















