[0:0.1:1] whys is not exactly 0.1 steps ?
Afficher commentaires plus anciens
Anyone know why this code does not return verification 1
it seems instead of being 0.1 is actually makaing 0.10000000001
step=0.1;
max_value=1;
array = 0:step:max_value;
array1 = round(0:step:max_value,1);
check=[array',array1'];
test=[array==array1]';
% Why not 1 ?
verification=all(test)
1 commentaire
Stephen23
le 31 Mai 2024
This is a completely expected result with binary floating point numbers:
This is worth reading as well:
Instead of incorrectly assuming exact equivalence of binary floating point numbers, compare the absolute difference against a tolerance:
tol = 1e-10; % you select this to suit your data
idx = abs(A-B)<tol;
Réponse acceptée
Plus de réponses (1)
Can you represent the number 0.1 exactly? Remember that MATLAB does not store the exact representation of numbers. Instead, it uses a binary storage form. An exact numeric storage would quickly become impossible to achieve, because numbers would very quickly grow in size/length, and the symbolic computations would become impossible. This means you have no real choice but to use double precision arithmetic, or something like it, where only a reasonably finite number of bits are used to store any number. And doubles use an IEEE standard binary store scheme, where only 52 bits are used to store the mantissa. But in binary, just like you cannot represent the number 1/3 exactly as a decimal, you cannot represent the number 1/10 exactly.
The representation of 0.1 in binary is the infinite sequence...
0.00011001100110011001100110011001100110011001100110011010...
where the ones represent negative powers of 2. We could try this:
P = [-4 -5 -8 -9 -12 -13 -16 -17 -20 -21 -24 -25 -28 -29 -32 -33 -36 -37 -40];
format long g
sum(2.^P)
And you see it is not exactly 0.1, any more than 0.33333333333 is exactly 1/3. And no matter how far out you go, you will never be able to stop. There is never a point where you will find a binary representation of 0.1. And this is true of almost all fractions you might write. The only fractions that are exactly representable in binary are simple things like
0.375 == 3/8 == 1/4 + 1/8
Catégories
En savoir plus sur Logical 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!