vectors equality test failure - decimals and sign issue on zeros
1 次查看(过去 30 天)
显示 更早的评论
I shall test two vectors of same dimension for their equality: namely, x0 and xhat as defined below (they belong to different functions, xhat is return value of inner called function).
--- x0 ---
support = randsample(n,k);
x0 = zeros(n,1);
x0(support) = randn(k,1);
--- xhat ---
b = A*x0;
cvx_quiet(true);
cvx_begin
variable x(n)
minimize( norm(x,1) )
subject to
A*x == b
cvx_end
xhat = x;
To test equality I use:
if isequal(xhat, x0, 1e-6)
or
if isequal(xhat, x0)
condition which never verifies because x0 contains '0' or other (4 decimals, signed), while xhat contains '0.0000', '-0.0000', or other (4 decimals, signed). The algorithm works properly as values (real) in magnitude are the same in both vectors, and at the same indexes, therefore the condition for 'equality' is satisfied in facts, but I miss the way to code it in matlab.
How can I 'turn' xhat into x0, so to get isequal() function answering TRUE ?
Many thanks!
回答(1 个)
Geoff Hayes
2016-8-13
VMat - see http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F for some details on comparing two floating-point numbers. When doing so, you shouldn't be using equality. Instead, compare the absolute difference to a tolerance. For example,
tol = 1.0e-6;
areEqual = all(abs(xhat-x0) < tol);
will return true if the pairwise absolute difference between each element of the two arrays is less than the tolerance.
1 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Hypothesis Tests 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!