Using sprintf (problem with integer)
Show older comments
Hi to everybody, I have got a problem using sprintf. I'm using it for doing the following operation:
step_value=sprintf('step%d',steps(i)*100);
..where "steps" is a simple array containing numbers with two decimals. The problem is that at i=9 I get:
steps(9)*100
ans = 55.0000
sprintf('%d',ans)
ans= 5.500000e+01
...which is not clearly in integer notation. I don't have problems for the other i-elements, just for i=9.
Someone knows what is it the problem? Thanks :)
Accepted Answer
More Answers (1)
Andrea Bracchitta
on 27 Apr 2017
0 votes
1 Comment
Walter Roberson
on 28 Apr 2017
Imagine that you are using 2 digit decimal, starting from 5.33001 and you want to represent that as exact thirds.
5.33001 * 3 -> 15.99003
round(15.99003) -> 16
16/3 -> 5.3333333333333 ... infinitely in theory
5.3333333333333 to 2 decimal -> 5.33
and now you multiply that by 3
5.33 * 3 -> 15.99
Oops, you did not manage to find a value, X, such that X * 3 = 16 exactly.
This happens because 1/3 cannot be exactly represented in finite decimal.
The same difficulty happens in binary with respect to 1/10 : 1/10 cannot be represented exactly in finite binary. In binary it is .00011001100110011... When you take a finite leading portion of that and multiply it by 10, you get something that is not quite 1.
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!