function d=myeps(X)

%myeps (X) - returns the distance between X (or its floating point
%representation) and the next largest floating number.  The function will
%only accept values that can be represented in the valid range of Matlab
%double precision floating point numbers.

X_abs=abs(X);  %Deal with distinguishing negative/positive boundary numbers later
j=-1072;       %Smallest number representable in MATLAB.  Not sure why or how
eps=2^-52;     %Machine epsilon.  Included for clarity.

while 2^j < X_abs    %loop until the exponent is identified
    j=j+1;
end

if j<-1071      %number is out of range
    d=0;
end   

if j<=-1023      %This portion of the code is used to deal with the numbers of 2^-1072 through 2^-1023
    d=2^j;       %By trial, one can see that the smallest number representable is 2^-1072, but multiplying
end             %this by eps produces a number that's out of range.  So just stick with 2^j in this case
    
if X_abs==2^j               %deals with boundary numbers (1+0)*2^j
        if X>0              %if x>0, next largest number will be 1+eps multiplied by same 2*j 
            d=2^j*eps;
        end
        if X<0              %if x<0, next largest number will be -1.11111... multiplied by 2^(j-1)
            d=2^(j-1)*eps;
        end
    else 
            d=2^(j-1)*eps;  %if x is not on boundary, next largest number will be 1+eps *2^(j-1)
        end
    end
end
    
