请用matlab代码完成微分方程数值解: 初值问题y'=-50y+50x^2+2x,0≤x≤1, y(0)=1/3 (1)采用Euler法求解初值问题,包括向前欧拉,向后欧拉,梯形法和改进欧拉法,区间数目n=100. (2)采用Runge-Kutta法求解初值问题,包括2阶,3阶和4阶龙格-库塔法,区间数目n=100.
时间: 2024-03-25 07:38:53 浏览: 118
特征值问题-深入浅出cortex-m7——i.mx rt1050(20180122)
好的,下面是针对该初值问题的matlab代码实现,包括Euler法和Runge-Kutta法的实现,其中,Euler法包括向前欧拉、向后欧拉、梯形法和改进欧拉法,Runge-Kutta法包括2阶、3阶和4阶龙格-库塔法:
Euler法:
```matlab
% 向前欧拉法
function y = forward_euler(f, h, x0, y0, xn)
x = x0:h:xn;
y = zeros(size(x));
y(1) = y0;
for i = 1:length(x)-1
y(i+1) = y(i) + h*f(x(i), y(i));
end
end
% 向后欧拉法
function y = backward_euler(f, h, x0, y0, xn)
x = x0:h:xn;
y = zeros(size(x));
y(1) = y0;
for i = 1:length(x)-1
phi = @(y) y - h*f(x(i+1), y) - y(i);
y(i+1) = fzero(phi, y(i));
end
end
% 梯形法
function y = trapezoidal(f, h, x0, y0, xn)
x = x0:h:xn;
y = zeros(size(x));
y(1) = y0;
for i = 1:length(x)-1
phi = @(y) y - y(i) - 0.5*h*(f(x(i), y(i)) + f(x(i+1), y));
y(i+1) = fzero(phi, y(i));
end
end
% 改进欧拉法
function y = improved_euler(f, h, x0, y0, xn)
x = x0:h:xn;
y = zeros(size(x));
y(1) = y0;
for i = 1:length(x)-1
y_star = y(i) + h*f(x(i), y(i));
y(i+1) = y(i) + 0.5*h*(f(x(i), y(i)) + f(x(i+1), y_star));
end
end
% 测试
f = @(x, y) -50*y + 50*x^2 + 2*x;
h = 1/100;
x0 = 0;
y0 = 1/3;
xn = 1;
y_forward_euler = forward_euler(f, h, x0, y0, xn);
y_backward_euler = backward_euler(f, h, x0, y0, xn);
y_trapezoidal = trapezoidal(f, h, x0, y0, xn);
y_improved_euler = improved_euler(f, h, x0, y0, xn);
x = 0:h:xn;
y_exact = exp(-50*x) + x.^2/3 + (2/25)*x - (1/75);
plot(x, y_forward_euler, 'r-', x, y_backward_euler, 'g-', x, y_trapezoidal, 'b-', x, y_improved_euler, 'm-', x, y_exact, 'k-');
legend('Forward Euler', 'Backward Euler', 'Trapezoidal', 'Improved Euler', 'Exact');
xlabel('x');
ylabel('y');
title('Solutions of ODE using Euler methods');
```
Runge-Kutta法:
```matlab
% 2阶龙格-库塔法
function y = rk2(f, h, x0, y0, xn)
x = x0:h:xn;
y = zeros(size(x));
y(1) = y0;
for i = 1:length(x)-1
k1 = h*f(x(i), y(i));
k2 = h*f(x(i)+h, y(i)+k1);
y(i+1) = y(i) + 0.5*(k1 + k2);
end
end
% 3阶龙格-库塔法
function y = rk3(f, h, x0, y0, xn)
x = x0:h:xn;
y = zeros(size(x));
y(1) = y0;
for i = 1:length(x)-1
k1 = h*f(x(i), y(i));
k2 = h*f(x(i)+0.5*h, y(i)+0.5*k1);
k3 = h*f(x(i)+h, y(i)-k1+2*k2);
y(i+1) = y(i) + (1/6)*(k1+4*k2+k3);
end
end
% 4阶龙格-库塔法
function y = rk4(f, h, x0, y0, xn)
x = x0:h:xn;
y = zeros(size(x));
y(1) = y0;
for i = 1:length(x)-1
k1 = h*f(x(i), y(i));
k2 = h*f(x(i)+0.5*h, y(i)+0.5*k1);
k3 = h*f(x(i)+0.5*h, y(i)+0.5*k2);
k4 = h*f(x(i)+h, y(i)+k3);
y(i+1) = y(i) + (1/6)*(k1+2*k2+2*k3+k4);
end
end
% 测试
f = @(x, y) -50*y + 50*x^2 + 2*x;
h = 1/100;
x0 = 0;
y0 = 1/3;
xn = 1;
y_rk2 = rk2(f, h, x0, y0, xn);
y_rk3 = rk3(f, h, x0, y0, xn);
y_rk4 = rk4(f, h, x0, y0, xn);
x = 0:h:xn;
y_exact = exp(-50*x) + x.^2/3 + (2/25)*x - (1/75);
plot(x, y_rk2, 'r-', x, y_rk3, 'g-', x, y_rk4, 'b-', x, y_exact, 'k-');
legend('RK2', 'RK3', 'RK4', 'Exact');
xlabel('x');
ylabel('y');
title('Solutions of ODE using Runge-Kutta methods');
```
阅读全文