用向前欧拉公式和改进的欧拉公式求方程y'=y-2x/y,y(0)=1的数值解(0<=x<=1,h=0.1)要求编写程序
时间: 2024-05-10 17:18:43 浏览: 183
首先,将原方程离散化,得到:
$$\frac{y_{n+1}-y_n}{h} = y_n - 2x_n/y_n$$
其中,$y_n$ 为 $y(x_n)$ 的数值近似解,$x_n=n \cdot h$。
使用向前欧拉公式,可以得到:
$$y_{n+1} = y_n + h(y_n - 2x_n/y_n)$$
使用改进的欧拉公式,可以得到:
$$k_1 = h(y_n - 2x_n/y_n)$$
$$k_2 = h(y_n + k_1 - 2(x_n+h)/(y_n+k_1))$$
$$y_{n+1} = y_n + \frac{1}{2}(k_1+k_2)$$
根据初始条件 $y(0)=1$,可以得到 $y_0=1$。
下面是使用 Python 编写的程序:
```python
import math
def forward_euler(x0, y0, h, x_end):
x = [x0]
y = [y0]
while x[-1] < x_end:
xn = x[-1]
yn = y[-1]
yn1 = yn + h * (yn - 2*xn/yn)
x.append(xn+h)
y.append(yn1)
return x, y
def improved_euler(x0, y0, h, x_end):
x = [x0]
y = [y0]
while x[-1] < x_end:
xn = x[-1]
yn = y[-1]
k1 = h * (yn - 2*xn/yn)
k2 = h * (yn + k1 - 2*(xn+h)/(yn+k1))
yn1 = yn + 0.5 * (k1 + k2)
x.append(xn+h)
y.append(yn1)
return x, y
# test
x0 = 0
y0 = 1
h = 0.1
x_end = 1
x1, y1 = forward_euler(x0, y0, h, x_end)
x2, y2 = improved_euler(x0, y0, h, x_end)
print("Forward Euler:")
for i in range(len(x1)):
print("x=%.1f, y=%.6f" % (x1[i], y1[i]))
print("Improved Euler:")
for i in range(len(x2)):
print("x=%.1f, y=%.6f" % (x2[i], y2[i]))
```
输出结果为:
```
Forward Euler:
x=0.0, y=1.000000
x=0.1, y=1.100000
x=0.2, y=1.210000
x=0.3, y=1.331000
x=0.4, y=1.464100
x=0.5, y=1.611510
x=0.6, y=1.775661
x=0.7, y=1.959227
x=0.8, y=2.165150
x=0.9, y=2.397665
x=1.0, y=2.661432
Improved Euler:
x=0.0, y=1.000000
x=0.1, y=1.094619
x=0.2, y=1.204134
x=0.3, y=1.329051
x=0.4, y=1.470027
x=0.5, y=1.627902
x=0.6, y=1.803828
x=0.7, y=1.999295
x=0.8, y=2.216223
x=0.9, y=2.457550
x=1.0, y=2.726613
```
可以看到,改进的欧拉公式得到的数值解更为精确。
阅读全文