C++ 和 Fortran 中的不同精度

2022-01-14 00:00:00 fortran double c++ fortran77

对于我正在进行的项目,我用 C++ 编写了一个非常简单的函数:

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

Fne(x) = 0.124*x*x,问题是当我计算函数的值时

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

对于 x = 3.8938458092314270 使用 Fortran 77 和 C++ 语言,我得到了不同的精度.

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

对于 Fortran,我得到了 Fne(x) = 1.8800923323458316,而对于 C++,我得到了 Fne(x) = 1.8800923630725743.对于这两种语言,Fne 函数都是为双精度值编码的,并且还返回双精度值.

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++ 代码:

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

Fortran 代码:

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?

推荐答案

差异的一个来源是 C++ 和 Fortran 对文字常量(例如 0.124)的默认处理.默认情况下,Fortran 会将其视为单精度浮点数(在您可能使用的几乎任何计算机和编译器组合上),而 C++ 会将其视为双精度 f-p 数.

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.

在 Fortran 中,您可以通过为 kind-selector 像这样

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.

哦,我在写的时候,你为什么要像 1977 年那样写 Fortran?对于所有其他 Fortran 专家来说,是的,我知道 *8_8 不是最佳实践,但我目前没有时间扩展所有这些.

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.

相关文章