Why does this code generate a mix of integers and doubles?

2 vues (au cours des 30 derniers jours)
chiral
chiral le 25 Mai 2022
Commenté : chiral le 25 Mai 2022
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 commentaires
Stephen23
Stephen23 le 25 Mai 2022
Modifié(e) : Stephen23 le 25 Mai 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
chiral le 25 Mai 2022
I see, thanks!

Connectez-vous pour commenter.

Réponse acceptée

Bjorn Gustavsson
Bjorn Gustavsson le 25 Mai 2022
In practice you can look on this problem as "good luck" and "bad luck" when it comes to working and not working. The rounding of fixed precision floating-point arithmetic is intricate, look for the blog-posts on these matters by Cleve Moler or Loren Shure (and possibly others). From a practical perspective the rounding-errors might turn up as you expect, but since 0.1 has an infinite expansion in binary you cannot expect it to always give you that result. Therefore when you calculate indices the robust approach is to explicitly handle this by casting your flint-numbers into proper integers with round - then you know that you have made a concious design-choise of how to handle this (hopefully a good design-choise too).
Once uppon a time matlab used to round general floats in matrix-indexing operations which for my application was incredibly convenient, then they changed that rounding-operation to floor instead of round - which I "handled short-term" by adding 1/2 to my indices, the next change was to require integers into the indexing - which forces us to make this design-choise explicitly.
HTH

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by