I already read the other discussion here on SO but I still cannot understand why the code does not work as expected.
In my code I check that k
is approximately equal to 1
, but still it does not work:
if approx(k, 1, eps)
display('Approx equal');
else
k
k == 1
approx(k, 1, eps)
abs(k - 1) < eps
end
Instead of displaying the string, this is the result (I have enabled format long
):
k = 1.000000000000000
ans = 0
ans = 0
ans = 0
This is baffling! I also tried to increase the error by k * 1e20
but the result is still 1e20
... What to do here?
Note: although not really relevant to the question, here is the definition of approx
:
function r = approx(a, b, tol)
r = a <= b + tol && a >= b - tol;
end
EDIT: I changed the approx
function to avoid catastrophic cancellation:
function r = approx(a, b, tol)
r = a <= b + tol && a + tol >= b; % assumes tol is positive
end