How to solve 1.0000 not equal to 1 in MATLAB?
83 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have a matrix V. I want to test if the matrix equal to one or not.
Sometimes the sum(V(:))==1.0000 but when I test if sum(V(:))== 1 the results always FALSE.
How to solve that problem.
0 commentaires
Réponses (2)
Stephen23
le 30 Déc 2022
Modifié(e) : Stephen23
le 19 Juin 2023
"How to solve 1.0000 not equal to 1 in MATLAB?"
There is nothing to "solve", because 1.0000 is not equal to 1 (note the trailing zeros: what do they tell us?):
x = 1+eps(1)
y = 1
x==y
"How to solve that problem."
What problem? MATLAB is correctly telling you that two values are not the same.
If you want to compare two values by including some tolerance in the comparison, then try using ISMEMBERTOL(), or else use the simple, easy, efficient, recommended approach of comparing the absolute difference against your selected tolerance:
tol = 1e-6;
abs(x-y)<tol
0 commentaires
Jan
le 30 Déc 2022
Modifié(e) : Jan
le 30 Déc 2022
Welcome to the world of numerical maths.
Remember, that the summation is numerically instable. Even a reordering of the elements can cause different results:
1e16 + 1 - 1e16
1e16 - 1e16 + 1
Rounding effect must be considered for floating point arithmetics:
0.1 + 0.2 == 0.3 % False!
0.1 + 0.2 - 0.3
Most decimal numbers du not have an exact numerical representation in binary format. See FAQ: Why is 0.1+0.2~=0.3?
You have to consider a range:
V = 2 * rand(1e3);
cmp = abs(sum(V(:)) - 1) < 1e-8;
But remember the initial warning: There is no generally matching limit for the accepted range and the instability of the sum can cause large artifacts:
1e32 + 1e16 - 1e32
There are some methods to increase the accuracy of the summation: FEX: XSum, but there is no way to "solve" the problem completely. Most of all this concerns all calculations, not only the sum. Even stable algorithms suffer from the limited precision and the accuray is limited in consequence also.
0 commentaires
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!