Hello, i was writing the following piece of code, in order to get names for some files and at specific numbers seems that sprintf produces wrong results
wv=0:0.2:4;
for i=1:length(wv)
sprintf('%.2d', wv(i)*10)
end
and the resultus i am getting
ans =
04
ans =
6.00e+00
ans =
08
ans =
10
ans =
1.20e+01
ans =
1.40e+01
ans =
16
so it seems wrongly formatted (which causes me problem , because i am constructing filenames with those)
i am using matlab 2013a at a macbook pro (2015)
i found a simple solution by having another variable (wvv=0:2:40) and avoid to multiple in sprintf
so i am just reporting this problem i think it is a bug

1 commentaire

Walter Roberson
Walter Roberson le 27 Jan 2017
The problem is that the values are not integers because of floating point round off. Just like 0.33 added 3 times does not add up to 1, if you add up the representation of 0.2 multiple times you do not always get an integer. Numbers are not represented in decimal.

Connectez-vous pour commenter.

Réponses (2)

Adam
Adam le 27 Jan 2017
Modifié(e) : Adam le 27 Jan 2017

0 votes

The help suggests this if you want true integers from floats:
wv=0:0.2:4;
for i=1:length(wv)
sprintf('%.2d', round( wv(i)*10) )
end
If you create the vector e.g.
wv2 = wv * 10;
and look at it in the variable editor you will see this same behaviour, arising from floating point maths. sprintf does similarly.
the cyclist
the cyclist le 27 Jan 2017
Modifié(e) : the cyclist le 27 Jan 2017

0 votes

Others were quicker than I was to point out why this is expected behavior, so please see those responses. I'll just add that if you type
format long
10*wv'
then you'll see the issues immediately.
I think you can probably get what you intended if you use the format spec
sprintf('%2g', wv(i)*10)
instead.

Catégories

En savoir plus sur Entering Commands dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by