Why is format long providing a strange result?

18 vues (au cours des 30 derniers jours)
Connor Taylor
Connor Taylor le 5 Déc 2019
Modifié(e) : Adam Danz le 6 Déc 2019
I am having trouble with the output from a code I am running. The answers are correct, but the Matlab command window is outputting them in a funny way.
Instead of printing 19.9998.... it gives this as 0.199998... with 1.0e+02. This is technically correct, but just looks a bit shabby.
I have already played around with the format settings in Customise toolbar > Command window > Text display. This still hasn't fixed the issue.
Format long seems to work well for the code below where dt=2. However changing dt to dt=0.2 is what is causing the problem.
Many thanks in advance.
clc
format long
r=0.5;
k=20;
dt=2;
t_run=30.0;
n_max=t_run/dt +1;
xtrue=zeros(n_max,1);
n=1
x0=0.5;
time=0:dt:t_run;
for n=1:n_max
xtrue(n)=k/(1+((k-x0)*exp(-r*2*(n-1)))/x0);
disp([n xtrue(n)])
end
plot(time,xtrue)
xlim([0 30])
ylim([0 30])
xlabel('Time')
ylabel('Population')
title('True Solution')
hold on
%% True plot with dt = 0.2
dt=0.2;
n_max=t_run/dt +1;
xtrue=zeros(n_max,1);
n=1
time=0:dt:t_run;
for n=1:n_max
xtrue(n)=k/(1+((k-x0)*exp(-r*0.2*(n-1)))/x0);
disp([n xtrue(n)])
end
plot(time,xtrue)
legend('dt=2','dt=0.2')
hold off

Réponses (2)

Steven Lord
Steven Lord le 5 Déc 2019
I recommend using format longg instead of format long for this case.

Adam Danz
Adam Danz le 5 Déc 2019
Modifié(e) : Adam Danz le 6 Déc 2019
It's because of the way you're combing two variables in the output display.
Look at the last iteration of your 2nd for-loop.
% Your 2nd for-loop
for n=1:n_max
xtrue(n)=k/(1+((k-x0)*exp(-r*0.2*(n-1)))/x0);
disp([n xtrue(n)])
end
  • n is equal to 151
  • xtrue(n) is equal to 19.999761399036565 (long format)
  • when you combine them using [n xtrue(n)], the long format reformats the output.
format long
[n xtrue(n)]
% ans =
% 1.0e+02 *
% 1.510000000000000 0.199997613990366
format short
[n xtrue(n)]
% ans =
% 151.0000 19.9998
If you'd like to specify the precision, use fprintf() instead of disp().
format long % or whatever format you want - you'll get the same results
fprintf('%.4f, %.4f\n',n, xtrue(n))
% Result:
% 151.0000, 19.9998
% Or maybe you want
fprintf('%d, %.4f\n',n, xtrue(n))
% Result:
% 151, 19.9998

Catégories

En savoir plus sur Entering Commands dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by