Different precision in C++ and Fortran

痞子三分冷 提交于 2019-12-02 04:34:37

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!