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
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 Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!