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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With