function success = testclose(x, y, tol) %TESTCLOSE verbosely check two inputs are close. Use in test cases. % % success = testclose(x, y, tol) % checks whether max fractional difference is less than tolerance: % max(abs(x(:)-y(:)))./abs(min(x(:), y(:))) < tol. % % This function is verbose, outputting a result suitable for use in test cases. % Also returns true/false for further processing, e.g. assert(testclose(...)) to % force stopping a test case. % % tol = 1e-9 by default % Iain Murray, November 2007, September 2010 if nargin < 3 tol = 1e-9; end assert(tol >= 0); % Annoying special cases if ~isequal(size(x), size(y)) success = false; fprintf('FAILURE: matrices are not the same size\n'); return; end if isempty(x) success = true; fprintf('OK (matrices are both empty and of the same size)\n'); return end nanx = isnan(x); if ~isequal(nanx, isnan(y)) success = false; fprintf('FAILURE: Some values were NaN only in one of the arrays.\n'); return end idx = (x ~= y) & ~nanx; if any(idx) max_err = max(abs(x(idx) - y(idx))./min(abs(x(idx)), abs(y(idx)))); else max_err = 0; end success = max_err < tol; if success fprintf('OK (fractional difference of %0.3g < (tol=%0.3g))\n', max_err, tol); else fprintf('FAILURE: fractional difference of %0.3g exceeds tolerance of %0.3g\n', max_err, tol); end if any(nanx) fprintf('WARNING: some of the values tested were NaNs\n'); end