How to solve 1.0000 not equal to 1 in MATLAB?
65 次查看(过去 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!