Borrar filtros
Borrar filtros

How to solve 1.0000 not equal to 1 in MATLAB?

26 visualizaciones (últimos 30 días)
Rahim Rahim
Rahim Rahim el 30 de Dic. de 2022
Editada: Stephen23 el 19 de Jun. de 2023
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.

Respuestas (2)

Stephen23
Stephen23 el 30 de Dic. de 2022
Editada: Stephen23 el 19 de Jun. de 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)
x = 1.0000
y = 1
y = 1
x==y
ans = logical
0
"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
ans = logical
1

Jan
Jan el 30 de Dic. de 2022
Editada: Jan el 30 de Dic. de 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
ans = 0
1e16 - 1e16 + 1
ans = 1
Rounding effect must be considered for floating point arithmetics:
0.1 + 0.2 == 0.3 % False!
ans = logical
0
0.1 + 0.2 - 0.3
ans = 5.5511e-17
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
ans = 1.8014e+16
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.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by