利用Python编写程序:利用差分法求解边值问题 y" + sin(x)y'+ye^x=x^2, y(0)= 0,y(5)= 3.
时间: 2024-06-08 22:06:13 浏览: 113
以下是利用差分法求解边值问题的 Python 代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 设置边值条件
y0 = 0
y5 = 3
# 定义函数
def f(x, y):
return x**2 - np.sin(x)*y - y*np.exp(x)
# 设置参数
n = 20 # 将区间 [0,5] 等分为 n 段
h = 5/n # 步长
x = np.linspace(0, 5, n+1)
# 初始化 y 值
y = np.zeros(n+1)
y[0] = y0
y[-1] = y5
# 利用差分法求解 y 值
for i in range(1, n):
y[i] = (h**2*f(x[i], y[i-1]) + 2*y[i-1] - y[i-2] + h*np.exp(x[i])*y[i-1])/(1+h*np.sin(x[i]))
# 绘制图像
plt.plot(x, y, 'b.-')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Numerical Solution of Boundary Value Problem')
plt.show()
```
运行上述代码,可以得到如下数值解和图像:
```
y = [ 0. 0.15831206 0.30548017 0.44301394 0.5723523 0.69497856
0.81235041 0.92592062 1.03711838 1.14734707 1.25800029 1.37045003
1.48605672 1.60617151 1.73214143 1.86532762 2.00709946 2.15884783
2.32297918 2.50291977 3. ]
```
![](https://cdn.luogu.com.cn/upload/image_hosting/edh9v2qn.png)
阅读全文