Two identical programs produce different results

I have a simple question to ask. I have written two similar programs in FORTRAN90 and C. Both sources are built within CYGWIN environment. They are very simple:

1
2
3
4
5
6
7
8
9
10
11
PROGRAM test

      DOUBLE PRECISION Na, Nb, Nr

      Na = 0.2726
      Nb = -0.2727
      Nr = Na + Nb

      WRITE(6,*)'Nr = ',Nr

END


1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>

int main(void) {
double Na, Nb, Nr;

     Na = 0.2726;
     Nb = -0.2727;
     Nr = Na + Nb;

     printf("Nr = %.16E\n", Nr);

     return 0;
}


CYGWIN reported following results:
1
2
3
4
5
6
7
Konstantin@Konstantin-HP /home/lbm2d
$ ./testf.x
 Nr =   -1.0001659393310547E-004

Konstantin@Konstantin-HP /home/lbm2d
$ ./testc.x
Nr = -9.9999999999988987E-05


As you can see, the problem is adding two decimals. However, both results are incorrect and different. Can somebody explain why?

Thank you in advance! Konstantin
Last edited on
The C program gives almost the correct answer.

-9.9999999999988987E-05 = -0.000099999999999988987-0.0001

I don't think you can expect doubles to be more precise than this.


The fortran answer is also close but I don't know why the error is so much bigger than the C program.

-1.0001659393310547E-004 = -0.00010001659393310547-0.0001

Last edited on
Thanks for replying. I figured out the answer. The FORTRAN code must be amended like this:
1
2
3
4
5
6
7
8
9
10
11
PROGRAM test

      DOUBLE PRECISION Na, Nb, Nr

      Na = 0.2726D0
      Nb = -0.2727D0
      Nr = Na + Nb

      WRITE(6,*)'Nr = ',Nr

END

Then CYGWIN ouputs identical results:
1
2
3
4
5
6
7
Konstantin@Konstantin-HP /home/lbm2d
$ ./testf.x
 Nr =   -9.9999999999988987E-005

Konstantin@Konstantin-HP /home/lbm2d
$ ./testc.x
Nr = -9.9999999999988987E-05

Further details are posted in stackoverflow:
http://stackoverflow.com/questions/30455556/diiferent-precision-c-fortran
Topic archived. No new replies allowed.