How to solve 1.0000 not equal to 1 in MATLAB?
73 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
回答 (2 件)
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)
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 件のコメント
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
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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!