Solve the differential equation with adams

2 vues (au cours des 30 derniers jours)
Nikodin Sedlarevic
Nikodin Sedlarevic le 16 Mai 2022
Modifié(e) : Torsten le 16 Mai 2022
My assingment is this: The following second-order differential equation y′′(x) = (1 − y(x)^2) y(x)′ - y(x), y (0) = 1, y ′ (0) = 1 convert it to a system of first-order differential equations and solve it with the given method. Solve the differential equation with adams for h = 1/3 and h = 1/6. How many times does the approximation error decrease (calculate the error coefficient err (h = 1/3) / err (h = 1/6)), for y (10). For the exact value, take e.g. the one obtained with ode45 for a small enough step. This is how I solve it but I do not get the correct answer, especially I got the error1 = NaN
function [x,y] = RungeKutta(f, a, b, y0, h)
x = a:h:b;
y(:,1) = y0;
A = [0 0 0 0 0 ; 1/3 1/3 0 0 0 ; 2/3 -1/3 1 0 0 ; 1 1 -1 1 0 ;0 1/8 3/8 3/8 1/8];
d = length(y0);
k = zeros(d,length(A)-1);
for z = 1:length(x)-1
for i=1:length(A)-1
sum2 = 0;
for j=2:length(A)
sum2 = sum2 + A(i,j)*k(:,j-1);
end
k(:,i) = h*f(x(z)+A(i,1)*h,y(:,z)+sum2);
end
sum3 = 0;
for i = 2:length(A)
sum3 = sum3 + A(length(A),i)*k(:,i-1);
end
y(:,z+1) = y(:,z) + sum3;
end
end
function [x,y] = adams(f,a,b,y0,h)
x = a:h:b;
y = zeros(length(y0),length(x));
y(:,1) = y0;
[~,yr] = RungeKutta(f,a,b,y0,h);
y(:,2) = yr(:,2);
for i=1:length(x)-2
y(:,i+2) = y(:,i+1)+h*(3/2*f(x(i+1),y(:,i+1))-1/2*f(x(i),y(:,i)));
end
end
F = @(x,y) ([y(2);(1-y(1).^2).*y(2)-y(1)]);
y0 = [1;1];
[xa1, ya1] = adams(F,0,10,y0,1/3);
[xo1,yo1] = ode45(F,0:1/3:10,y0, odeset('RelTol', 10^(-11), 'AbsTol', 10^(-11)));
[xa2, ya2] = adams(F,0,10,y0,1/6);
[xo2,yo2] = ode45(F,0:1/6:10,y0, odeset('RelTol', 10^(-11), 'AbsTol', 10^(-11)));
error1 = abs(ya1(1,end)-yo1(end,1));
error2 = abs(ya2(1,end)-yo2(end,1));
result2 = error1/error2;
  6 commentaires
Nikodin Sedlarevic
Nikodin Sedlarevic le 16 Mai 2022
So how can I correct then this code, other then RungeKutta?
Torsten
Torsten le 16 Mai 2022
Modifié(e) : Torsten le 16 Mai 2022
The code is correct - the assignment is not well-thought-out.
You can't change anything - only your teacher can.
You don't need to call ode45 twice - it has an adaptive step size control, and the tspan interval you supply is for output purposes only. It does not influence the error of integration. The tolerated error can only be influenced by the prarameters AbsTol and RelTol which you chose equal in both cases.

Connectez-vous pour commenter.

Réponses (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by