next up previous contents
Next: Funny conversions Up: Tipical pitfalls with floating Previous: Binary versus decimal   Contents

Floating point comparisons

Because of the inexactities, it is best to avoid strict equality when comparing floating point numbers. For the above example, the code
%{}
if ( (1.0E+8*x**2) == 1.0 ) then
   print*, 'Correct'
end if
should print ``Correct'', but does not, since the left expression is corrupted by roundoff. The right way to do floating point comparisons is to define the epsilon machine, eps, and check that the magnitude of the difference is less than half epsilon times the sum of the operands:
%{}
epsilon = 1.0E-7
w = 1.0E+8 * x**2
if ( abs(w-1.0) .LE. 0.5*epsilon*( abs(w)+abs(1.0) ) ) then
   print*, 'Correct'
end if
This time we allow small roundoff's to appear, and the program takes the right branch.

In the following example the branch correct is taken:

%{}
program quiz_2b             
  implicit none              
  real :: x                  
  x = 1.0/2.0               
  if ( (2.0*x) .eq. 1.0 ) then  
     print*, 'Correct'         
  else     
     print*, 'Funny'    
  end if  
end program quiz_2b
while in the next the branch incorrect is taken:
%{}
program quiz_2a             
  implicit none              
  real :: x                  
  x = 1.0/3.0               
  if ( (3.0*x) .eq. 1.0 ) then  
     print*, 'Correct'         
  else   
     print*, 'Funny'    
  end if 
end program quiz_2a



Adrian Sandu 2001-08-26