Runge-Kutta for solving differential equation with final value (backward integration)

6 vues (au cours des 30 derniers jours)
Hello,
I have the following simple differential equaiotn: x' = -x-2 with a final value x(2)=0.
I solved it anlytically and got: x(t)=2(exp(2-t) -1). It satisfies the final condition x(2)=0. Also, x(0)=12.77.
Then I tried to solve it numerically using RK4 and plot the numerical solution with the analytical solution togehter
but I can see a big difference at t=0. Here is my code:
% x_f = 0
function y = Test(x_f)
test = -1;
epsn = 0.001;
N = 1000;
t = linspace(0,2,N+1);
h = 1/N;
h2 = h/2;
x = zeros(1,N+1);
x(N+1)=x_f;
while(test < 0)
oldx = x;
% Backward sweep
for i = 1:N
j = N + 2 - i;
k1 = -2-x(j);
k2 = -2-(x(j)-h2*k1);
k3 = -2-(x(j)-h2*k2);
k4 = -2-(x(j)-h*k3);
x(j-1) = x(j)-(h/6)*(k1 + 2*k2 + 2*k3 + k4);
end
temp = epsn*sum(abs(x)) - sum(abs(oldx - x));
test = temp;
end
% Analytical solution
x_cal = 2*(exp(2-t)-1);
y = x;
figure
plot(t,x,t,x_cal)
I'd appreciate any feedback on this issue.
Saleh

Réponses (1)

Divija Aleti
Divija Aleti le 27 Août 2020
The huge difference in the initial values is because the value of ‘h’ should be 2/N.
This value is calculated as follows:
h = (t_final t_initial)/(Number of Points - 1) = (2-0)/((N+1)-1) = 2/N

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by