The difference between the result from fortran and C program

I tested the following fortran program

	program main
	 real(8)::a,b,c
	 a=1.0000001
	 b=1.0
	 c=800.0*a-b
	 print *, c
	end program main

The result is “799.0000953674316”.
I also tested a C program

#include <stdio>
int main(void)
{
	double a, b;
	a = 1.0000001;
	b = 1.0;
  printf("%10.8f\n",800*a-b);
  return 0;
}

The result is “799.00008000”. We can see that the result from C program is more accurate. Why does the difference exist?

I believe this is due to the usual Fortran assumes all reals are real4 unless you tell it so. Thus, even if a,b, and c are real8, 1.0000001, 1.0 and 800.0 are all real*4! Fortran will initialize even a double-precision variable in single precision if you use a single-precision constant. Thus, your ‘c’ is the compiler filling a double with the results from single-precision math.

There are a few ways to combat this. One, add d0 or a similar kind’ing to your initializations:

   program main 
    real(8)::a,b,c 
    a=1.0000001d0 
    b=1.0d0 
    c=800.0d0*a-b 
    print *, c 
   end program main

Running this gives:

(280) > ./ftest.exe
799.0000800000000

You can also tell the compiler that every real in the code should be thought of as real*8 by using -r8. If you compile your test code with -r8 you’ll see the same thing.

(Also keep in mind another favorite Fortran example. This:

1./3. + 1.d0/3.d0

will result in something like 0.6666666766007741 because even in the same statement, Fortran will do the first division in single-precision before doing the second divide and the addition in DP.)

Thanks. I will fix my code.