Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different precision in C++ and Fortran

For a project I'm working on I've coded in C++ a very simple function :

Fne(x) = 0.124*x*x, the problem is when i compute the value of the function

for x = 3.8938458092314270 with both Fortran 77 and C++ languages , i got different precison.

For Fortran I got Fne(x) = 1.8800923323458316 and for C++i got Fne(x) = 1.8800923630725743. For both languages, the Fne function is coded for double precision values, and return also double precision values.

C++ code:

double FNe(double X) {
    double FNe_out;
    FNe_out = 0.124*pow(X,2.0);
    return FNe_out;
}

Fortran code:

  real*8 function FNe(X)
  implicit real*8 (a-h,o-z)
  FNe = 0.124*X*X
  return
  end

Can you please help me to find where this difference is from?

like image 869
EL KESRI Amine Avatar asked Feb 11 '23 00:02

EL KESRI Amine


1 Answers

One source of difference is the default treatment, by C++ and by Fortran, of literal constants such as your 0.124. By default Fortran will regard this as a single-precision floating-point number (on almost any computer and compiler combination that you are likely to use), while C++ will regard it as a double-precision f-p number.

In Fortran you can specify the kind of a f-p number (or any other intrinsic numeric constant for that matter and absent any compiler options to change the most-likely default behaviour) by suffixing the kind-selector like this

0.124_8

Try that, see what results.

Oh, and while I'm writing, why are you writing Fortran like it was 1977 ? And to all the other Fortran experts hereabouts, yes, I know that *8 and _8 are not best practice, but I haven't the time at the moment to expand on all that.

like image 101
High Performance Mark Avatar answered Feb 12 '23 13:02

High Performance Mark