next up previous contents
Next: Memory versus register operands Up: Tipical pitfalls with floating Previous: Floating point comparisons   Contents

Funny conversions

Sometimes the inexactness in floating point is uncovered by real to integer conversion, which by Fortran default is done using truncation. For example the code

%{}
program test
  real :: x = 1.0E-4
  integer :: i
  i = 10000*x
  print *, i
end program test
produces a stunning result: the value of is 0, not 1!

Another problem appears when a single precision number is converted to double precision. This does not increase the accuracy of the number. For example the code

%{}
program test
  real :: x = 1.234567
  double precision :: y = 0.0D0
  y = x
  print *, 'X =',x,'  Y =',y
end program test
produces the output
%{}
 X=   1.234567       Y=   1.23456704616547
The explanation is that, when converting single to double precision, register entries are padded with zeros in the binary representation. The double precision number is printed with 15 positions and the inexactity shows up. (if we use a formatted print for x with 15 decimal places we obtain the same result). In conclusion, we should only print the number of digits that are significant to the problem.



Adrian Sandu 2001-08-26