编制常微分方程初值问题的欧拉法、改进的欧拉法和经典的R-K法的程序;
时间: 2023-12-20 08:05:00 浏览: 69
欧拉法:
```python
def euler(f, x0, y0, h, n):
x = [x0 + i*h for i in range(n+1)]
y = [y0]
for i in range(n):
y.append(y[i] + h*f(x[i], y[i]))
return x, y
```
改进的欧拉法:
```python
def improved_euler(f, x0, y0, h, n):
x = [x0 + i*h for i in range(n+1)]
y = [y0]
for i in range(n):
y.append(y[i] + h/2*(f(x[i], y[i]) + f(x[i+1], y[i]+h*f(x[i], y[i]))))
return x, y
```
经典的R-K法:
```python
def rk4(f, x0, y0, h, n):
x = [x0 + i*h for i in range(n+1)]
y = [y0]
for i in range(n):
k1 = h*f(x[i], y[i])
k2 = h*f(x[i] + h/2, y[i] + k1/2)
k3 = h*f(x[i] + h/2, y[i] + k2/2)
k4 = h*f(x[i] + h, y[i] + k3)
y.append(y[i] + 1/6*(k1 + 2*k2 + 2*k3 + k4))
return x, y
```
其中,f是常微分方程右侧的函数,x0和y0是初值,h是步长,n是步数。函数返回的是x和y两个列表,分别表示求解出的自变量和因变量序列。
阅读全文