Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Spurious real numbers 1

Status
Not open for further replies.

sleepingSatellite

Programmer
May 13, 2002
20
0
0
DE
FORTRAN introduces small errors handling real numbers, even in the most simple operations.
For example running the following program:

Program try
Real a,b

a=2.555
b=3-a
write (*,100)'a=',a
write (*,100)'c=',b

100 format(A2,E16.10E2)
End program try

one gets the following results:

a=0.2555000100E+01
c=0.4449999300E+00


I'm certainly not the first to discover this.
I'd like to know how people usually put up with this.
Is there anything I can do to avoid it?
Or should I resign to compromise with it ?

Thank you in advance
 
1) Use double precision (or real*8).
2) Assign your numbers as double precision eg
Code:
a = 3D0
Your program will look something like
Code:
      program try
      real*8 a, b
      a = 2.555D0
      b = 3D0 - a
      write (*, 100) 'a=', a
      write (*, 100) 'b=', b
100   format (1X, A, E16.10E2)
      write (*, 200) 'a=', a
      write (*, 200) 'b=', b
200   format (1X, A, F16.10)
      stop
      end
 
And don't forget: you can't represent exactly a decimal fraction 2.555 on binary float point CPU (by float or double)...
 
You will get these errors no matter what you do so it is best to check your algorithm.

I've seen programs where the temperature was converted from Celsius to Farenheit at the start of the routine and converted back on exit. Pass it through 20000 times and the temperature starts creeping up!

There are all sorts of algorithms for getting round the decimal /binary problems. You can find quite a few of them in the papers written in the late 60s.
 
There is one way to avoid such errors: bcd maths... I have an ancient FORTRAN IV compiler that uses this.
 
No errors in that case. Floating point numbers are not math real numbers, that's all.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top