PGI User Forum
 SearchSearch   MemberlistMemberlist     RegisterRegister   ProfileProfile    Log inLog in 

Free OpenACC Course

The difference between the result from fortran and C program

 
Post new topic   Reply to topic    PGI User Forum Forum Index -> Programming and Compiling
View previous topic :: View next topic  
Author Message
shyboy_6104



Joined: 17 Oct 2011
Posts: 5

PostPosted: Mon Mar 26, 2012 5:00 am    Post subject: The difference between the result from fortran and C program Reply with quote

I tested the following fortran program
Code:

   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
Code:

#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?
Back to top
View user's profile
TheMatt



Joined: 06 Jul 2009
Posts: 335
Location: Greenbelt, MD

PostPosted: Mon Mar 26, 2012 7:45 am    Post subject: Reply with quote

I believe this is due to the usual Fortran assumes all reals are real*4 unless you tell it so. Thus, even if a,b, and c are real*8, 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:

Code:
   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:
Code:
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.)
Back to top
View user's profile
shyboy_6104



Joined: 17 Oct 2011
Posts: 5

PostPosted: Mon Mar 26, 2012 6:21 pm    Post subject: Reply with quote

Thanks. I will fix my code.
Back to top
View user's profile
Display posts from previous:   
Post new topic   Reply to topic    PGI User Forum Forum Index -> Programming and Compiling All times are GMT - 7 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © phpBB Group