[CODE START] x=5; y=8; if (x + y + 1E-15 == 13) a = 3 else a = 8 end [CODE END] When x + y + 1E-15, the code above returns a = 8. When x + y + 1E-16, the code above returns a = 3. Why? Kindly advise. Thanks.
"onemilimeter Chen" <onemm@example.com> wrote in message <g7adrj$5tr$1@fred.mathworks.com>... > [CODE START] > x=5; > y=8; > if (x + y + 1E-15 == 13) > a = 3 > else > a = 8 > end > [CODE END] > > When x + y + 1E-15, the code above returns a = 8. > When x + y + 1E-16, the code above returns a = 3. > > Why? Kindly advise. Thanks. i believe it's due to the fact that 1e-16 is less than eps. basically, it gets ignored as roundoff error so the value remains "exactly" 13 for the addition. you shouldn't be comparing floating point numbers to each other directly -- just check that they're within some tolerance.
"onemilimeter Chen" <onemm@example.com> wrote in message <g7adrj$5tr$1@fred.mathworks.com>... > [CODE START] > x=5; > y=8; > if (x + y + 1E-15 == 13) > a = 3 > else > a = 8 > end > [CODE END] > > When x + y + 1E-15, the code above returns a = 8. > When x + y + 1E-16, the code above returns a = 3. > Try help EPS. Everything equal or below eps(x+y)/2 % 8.8818e-016 is numerically 'zero' when adding to (x+y). Bruno
if you use this command >> format long you will see that >> x + y + 1E-15 ans = 13.000000000000002 >> x + y + 1E-16 ans = 13 notice that since 1E-16 is very small Matlab truncates it while 1E-15 is "large" enough for Matlab to considerate it. Thus 13.000000000000002 == 13 => FALSE! Be happy! Ivan "onemilimeter Chen" <onemm@example.com> wrote in message <g7adrj$5tr$1@fred.mathworks.com>... > [CODE START] > x=5; > y=8; > if (x + y + 1E-15 == 13) > a = 3 > else > a = 8 > end > [CODE END] > > When x + y + 1E-15, the code above returns a = 8. > When x + y + 1E-16, the code above returns a = 3. > > Why? Kindly advise. Thanks.
eps(13) = 1.776356839400251e-015 So anything smaller than half this, when added to 13, will not produce a number greater than 13. N = 13; (N + eps(N)/2) == N ans = 1
In article <g7adrj$5tr$1@fred.mathworks.com>, onemm@example.com says... > [CODE START] > x=5; > y=8; > if (x + y + 1E-15 == 13) > a = 3 > else > a = 8 > end > [CODE END] > > When x + y + 1E-15, the code above returns a = 8. > When x + y + 1E-16, the code above returns a = 3. > > Why? Kindly advise. Thanks. > Numerical roundoff. Check out this post: http://blogs.mathworks.com/loren/2006/08/23/a-glimpse-into-floating- point-accuracy/ Look at the help for eps. -- Loren http://blogs.mathworks.com/loren/