How can I reverse a for loop?

OK so i'm doing a quantum physics simulation with MATLAB. and part of this requires a for loop comparing position/velocity/acceleration against time. The full code can be found here https://github.com/crispyrolls93/Magnetic-Monopoles/blob/master/ForTest.m
The for loop in question is this:
for n = (1:nmax)
t = n * dt;
V = (1/((t)^2))*(M + lamda * (1 - (1/sqrt(1 + (t^2/lamda))))^2);
F = (V - E);
a = F * x - v/t;
v = v + a * dt;
x = x + v * dt;
%Prints to output file
fprintf(fxfid, '%18.18f \n', [x]');
fprintf(fvfid, '%18.18f \n', [v]');
fprintf(fafid, '%18.18f \n', [a]');
end
This starts with an initial value of x and v and iterates through a number of time steps.
To test this I am trying to reverse the for loop, using the end point of the forward loop as the initial for the reverse loop. This is the reverse for loop:
for n = (nmax:-1:1)
t = n * dt;
V = (1/((t)^2))*(M + lamda * (1 - (1/sqrt(1 + (t^2/lamda))))^2);
F = (V - E);
a = F * x - v/t;
v = v + a * dt;
x = x + v * dt;
%Display progress to terminal
check = 10 * n / nmax;
if any(check==A) == 1
disp(100-10*check/4)
end
%Prints to output files
fprintf(fxrid, '%18.18f \n', [x]');
fprintf(fvrid, '%18.18f \n', [v]');
fprintf(farid, '%18.18f \n', [a]');
end
Anyway, they come out different and I'm not sure what's going on. Can anyone help?
If you're struggling to read the code on here please check the github link.

回答 (1 件)

Walter Roberson
Walter Roberson 2016 年 2 月 25 日

0 投票

Accumulated round-off error. Remember, 0.1 + 0.2 - 0.3 is not the same as -0.3 + 0.2 + 0.1 when it comes to floating point arithmetic.

カテゴリ

ヘルプ センター および File ExchangeMATLAB についてさらに検索

製品

タグ

質問済み:

2016 年 2 月 25 日

回答済み:

2016 年 2 月 25 日

Community Treasure Hunt

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

Start Hunting!

Translated by