Search code examples
matlabnumericapproximation

Finding the machine value of epsilon in Matlab


The following Matlab code is meant to find the machine value of epsilon.

e = 1; 
while (1+e>1) 
    if e+1 <= 1
        e = 2*e;
    else e = e/2; 
    end
end
e = 2*e

While the value of epsilon is correctly approximated, modifying the code leads to unexpected results. For example, if the while loop condition is modified, as shown below, to e>0 the program either crashes or outputs 0 rather than an approximation for epsilon even though adding a constant doesn't change the inequality. Could someone explain why this is happening?

e = 1; 
while (e>0) 
    if e+1 <= 1
        e = 2*e;
    else e = e/2; 
    end
end
e=2*e

Solution

  • The concept of “epsilon” is that there is a minimal value that must be added to 1 to obtain a different value. If e is smaller than epsilon, then 1+e==1. Floating-point numbers cannot represent values in between 1 and 1 + epsilon.

    So replacing the condition in the while loop, 1+e>1, with e>0, though mathematically equivalent, breaks the concept we are trying to define: epsilon as the smallest value to add to 1 to get a value larger from 1. Note that you can represent values very close to 0, such as 10-300, but you cannot represent values that close to 1. Epsilon is about 10-16. This means that the two inequalities are not the same when working with floating-point numbers.


    Note that the statement if e+1 <= 1 is only reached when 1+e>1, and so will always be false. You can simplify the code by removing this if statement and keeping only the code in the else clause:

    e = 1;
    while 1+e > 1
       e = e/2;
    end
    e = 2*e