Different precision in C++ and Fortran

后端 未结 2 1978
情话喂你
情话喂你 2020-12-07 04:04

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

相关标签:
2条回答
  • 2020-12-07 04:13

    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.

    0 讨论(0)
  • 2020-12-07 04:29

    As High Performance Mark pointed out, the default precision of literals is the issue. Using

    double xx = 3.8938458092314270;
    std::cout << std::setprecision(16);
    std::cout << " (float) * x*x: " << 0.124f*xx*xx << std::endl;
    std::cout << "(double) * x*x: " << 0.124*xx*xx << std::endl;
    

    We get

     (float) * x*x: 1.880092332345832
    (double) * x*x: 1.880092363072574
    

    which is the same difference you noticed.

    0 讨论(0)
提交回复
热议问题