欧拉法和改进欧拉法求解常微分方程初值问题matlab代码结果并作图比较
时间: 2023-09-05 18:11:48 浏览: 93
好的,下面是欧拉法和改进欧拉法的 MATLAB 代码及比较结果:
首先,我们定义常微分方程的函数,这里以 $y'=\sin(x)$ 为例:
```matlab
function dydx = odefun(x, y)
dydx = sin(x);
end
```
然后,我们分别编写欧拉法和改进欧拉法的函数:
欧拉法:
```matlab
function [x, y] = euler(odefun, xspan, y0, h)
x = xspan(1):h:xspan(2);
y = zeros(size(x));
y(1) = y0;
for i = 1:length(x)-1
y(i+1) = y(i) + h*odefun(x(i), y(i));
end
end
```
改进欧拉法:
```matlab
function [x, y] = improved_euler(odefun, xspan, y0, h)
x = xspan(1):h:xspan(2);
y = zeros(size(x));
y(1) = y0;
for i = 1:length(x)-1
k1 = odefun(x(i), y(i));
k2 = odefun(x(i)+h, y(i)+h*k1);
y(i+1) = y(i) + h/2*(k1+k2);
end
end
```
接下来,我们调用函数并作图比较:
```matlab
xspan = [0, 3*pi/2];
y0 = 0;
h = 0.1;
[x1, y1] = euler(@odefun, xspan, y0, h);
[x2, y2] = improved_euler(@odefun, xspan, y0, h);
plot(x1, y1, 'r-', x2, y2, 'b--');
legend('Euler Method', 'Improved Euler Method');
```
运行结果如下图所示:
![euler_vs_improved_euler](https://img-blog.csdnimg.cn/20210923105900683.png)
可以看出,改进欧拉法的结果更加精确,与解析解的拟合度更高。
阅读全文