bug on sprintf?
显示 更早的评论
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 个评论
Walter Roberson
2017-1-27
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.
回答(2 个)
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
2017-1-27
编辑:the cyclist
2017-1-27
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.
类别
在 帮助中心 和 File Exchange 中查找有关 MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!