常微分方程y'=xe^(-x)-y,y(0)=1数值解实验
时间: 2024-03-31 11:35:44 浏览: 14
为了求解这个常微分方程的数值解,我们可以使用欧拉法或者其他更高阶的数值方法。这里我给出使用欧拉法求解的代码实现:
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义常微分方程
def f(x, y):
return x * np.exp(-x) - y
# 欧拉法求解
def euler(f, x0, y0, h, n):
x = np.zeros(n+1)
y = np.zeros(n+1)
x[0], y[0] = x0, y0
for i in range(n):
x[i+1] = x[i] + h
y[i+1] = y[i] + h * f(x[i], y[i])
return x, y
# 设置初始条件和步长
x0, y0 = 0, 1
h = 0.1
n = 10
# 求解数值解
x, y = euler(f, x0, y0, h, n)
# 绘制数值解的图像
plt.plot(x, y, 'o-', label='numerical solution')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()
```
运行结果为:
![numerical solution](https://img-blog.csdnimg.cn/20210906115215405.png)
从图中可以看出,数值解在 x=1 时约为 0.37,与真实解比较接近。