1

I am working with some small double precision values (<0.001) in C++. I need to do the same calculation in Fortran. This same calculation is showing different result in Fortran. Most result values differ after the 5th or 6th decimal place, but some values match exactly.

How do I get the correct result in Fortran? Why is this happening?

C++ Code:

    double A[3][10], B[10][5];
    //values of A and B are initialized with values <.001
    double tmp;
    tmp=0.008456278; //for example
    int p;
    for (p=1;p<10;p++)
    {
        tmp=tmp-A[2][p]*B[p][4];
    }
    cout<<"Result="<< tmp;

Fortran Code:

    real*8 :: A(3,10)
    real*8 :: B(10,5)
    !values of A and B are initialized with values <.001
    real*8 :: tmp
    tmp=0.008456278 !value for example
    integer :: p
    do p=1, 10
        tmp=tmp-A(2,p)*B(p,4)
    end do
    write(*,*) "Result=", tmp
veryreverie
  • 2,871
  • 2
  • 13
  • 26
  • could you please print both results... better if you print in every value for **p** – ΦXocę 웃 Пepeúpa ツ Sep 09 '21 at 07:11
  • Have a look here : https://stackoverflow.com/questions/20025924/are-the-reals-in-fortran-the-same-as-floats-in-c, https://stackoverflow.com/questions/838310/fortran-90-kind-parameter Maybe that has some answers. I suspect both languages use different representations for numbers – Pepijn Kramer Sep 09 '21 at 07:11
  • 4
    Your number `0.008456278` is a default (that means *single*) precision literal. You need to use double precision ones. E.g., `0.008456278d0`. See the link. – Vladimir F Героям слава Sep 09 '21 at 07:15
  • 3
    @P.Kramer on typical computers and compilers of the past four decades they use the same representations for floating point numbers (which is also the native representation used by the CPU). What typically differs is the choice of the default precision (C double, Fortran single unless special flags are used). – Vladimir F Героям слава Sep 09 '21 at 07:17
  • 2
    You may also wish to not use `real*8`, but rather `real(kind=real64)` form the iso_fortran module. (See also the SO URL given in an earlier comment.) – Michael Klemm Sep 09 '21 at 13:21

0 Answers0