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?
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 thisTry 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.As High Performance Mark pointed out, the default precision of literals is the issue. Using
We get
which is the same difference you noticed.