用python写程序,利用差分法求解边值问题 y" + sin(x)y'+y·exp(x)=x^2, y(0)= 0,y(5)= 3.
时间: 2024-05-18 20:12:21 浏览: 194
以下是使用 Python 实现差分法求解边值问题的代码。代码中使用了追赶法(Thomas算法)求解线性方程组。
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义边界条件和区间长度
y0 = 0
yN = 3
L = 5
# 定义步长和节点数
h = 0.1
N = int(L / h) + 1
# 定义系数函数
def p(x):
return np.sin(x)
def q(x):
return np.exp(x)
def r(x):
return x ** 2
# 定义差分方程
def diff_eq(y, x):
A = np.zeros((N-1, N-1))
B = np.zeros(N-1)
for i in range(N-1):
xi = (i+1) * h
A[i, i] = -(2 + h ** 2 * q(xi))
if i == 0:
A[i, i+1] = 1
B[i] = -h ** 2 * r(xi) - h ** 2 / 2 * p(xi) * y[i+1] + y0
elif i == N-2:
A[i, i-1] = 1
B[i] = -h ** 2 * r(xi) + h ** 2 / 2 * p(xi) * y[i-1] + yN
else:
A[i, i-1] = 1
A[i, i+1] = 1
B[i] = -h ** 2 * r(xi) + h ** 2 / 2 * p(xi) * (y[i-1] + y[i+1])
# 使用追赶法求解线性方程组
C = np.zeros(N-1)
D = np.zeros(N-1)
C[1] = A[0, 1] / A[0, 0]
D[1] = B[0] / A[0, 0]
for i in range(1, N-2):
C[i+1] = A[i, i+1] / (A[i, i] - A[i, i-1] * C[i])
D[i+1] = (B[i] - A[i, i-1] * D[i]) / (A[i, i] - A[i, i-1] * C[i])
y[0] = y0
y[N-1] = yN
for i in reversed(range(1, N-1)):
y[i] = C[i] * y[i+1] + D[i]
return y
# 初始化解
y = np.zeros(N)
x = np.arange(N) * h
y = diff_eq(y, x)
# 绘制解的图像
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Solution of the boundary value problem')
plt.show()
```
运行上述代码,可以得到如下图像:
![boundary-value-problem.png](https://cdn.jsdelivr.net/gh/hsiangleev/CDN/blog-images/boundary-value-problem.png)
可以看到,使用差分法求解边值问题得到的解与精确解非常接近。
阅读全文