Why does this code generate a mix of integers and doubles?
Show older comments
When I run the following code it generates a mixture of integers and decimal points which I can't use for array indexing.
for j = 0:0.1:3
disp(j*10+1);
end
Output:
1
2
3
4
5
6
7.0000
8
9
10
11
12
13.0000
14
15.0000
16
17
18
19
20
21
22
23
24.0000
25.0000
26
27
28
29.0000
30.0000
31
4 Comments
"Why does this code generate a mix of integers and doubles?"
They are all doubles.
V = 0:0.1:3;
fprintf('%.42f\n',V(7),V(7)*10+1)
chiral
on 25 May 2022
"it seems like Matlab interprets the figures which appear as an integer to be an integer"
MATLAB displays binary floating point numbers with zero fractional part without any trailing fractional digits. The trailing zeros e.g. "X.0000" tells us that the fractional part is not zero (not matter how small it might be).
"Why doesn't this work for all of them?"
Because how floating point error accumulates depends on the values and operations concerned: sometimes it might appear to "cancel out", sometime it might increase. That is simply how binary floating point numbers are.
"I'm just curious if there is a reason why Matlab only treats some of these as integers."
Because only some of them are whole numbers.
chiral
on 25 May 2022
Accepted Answer
More Answers (0)
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!