Azzera filtri
Azzera filtri

vectors equality test failure - decimals and sign issue on zeros

1 visualizzazione (ultimi 30 giorni)
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!
  2 Commenti
VMat
VMat il 14 Ago 2016
Thank you very much Geoff: problem solved.
Stephen23
Stephen23 il 14 Ago 2016
Modificato: Stephen23 il 14 Ago 2016
According to the isequal documentation, this syntax
isequal(xhat, x0, 1e-6)
simply tests that all three arrays are equal, i.e. that xhat is the same as x0, and x0 is the same as 1e-6. Is that what you want to test for? Did you read the documentation ?

Accedi per commentare.

Risposte (1)

Geoff Hayes
Geoff Hayes il 13 Ago 2016
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 Commento
Guillaume
Guillaume il 14 Ago 2016
@Vmat,
I guess that this tolerance comparison is what you were trying to do with your isequal(xhat, x0, 1e-6) but that is not how isequal works at all. There is no tolerance argument for isequal. As per the doc, the above simply checks that both xhat and x0 are equal to 1e-6.

Accedi per commentare.

Community Treasure Hunt

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

Start Hunting!

Translated by