필터 지우기
필터 지우기

How to solve 1.0000 not equal to 1 in MATLAB?

조회 수: 26 (최근 30일)
Rahim Rahim
Rahim Rahim 2022년 12월 30일
편집: Stephen23 2023년 6월 19일
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.

답변 (2개)

Stephen23
Stephen23 2022년 12월 30일
편집: Stephen23 2023년 6월 19일
"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 2022년 12월 30일
편집: Jan 2022년 12월 30일
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.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by