简体   繁体   English

Fortran和C ++计算的值之间的差异

[英]Discrepancy between the values computed by Fortran and C++

I would have dared say that the numeric values computed by Fortran and C++ would be way more similar. 我敢说Fortran和C ++计算的数值会更相似。 However, from what I am experiencing, it turns out that the calculated numbers start to diverge after too few decimal digits. 然而,从我所经历的情况来看,事实证明,计算出的数字在十进制数字太少之后开始发散。 I have come across this problem during the process of porting some legacy code from the former language to the latter. 在将一些遗留代码从前一种语言移植到后一种语言的过程中,我遇到了这个问题。 The original Fortran 77 code... 最初的Fortran 77代码......

  INTEGER M, ROUND
  DOUBLE PRECISION NUMERATOR, DENOMINATOR

  M = 2
  ROUND = 1
  NUMERATOR=5./((M-1+(1.3**M))**1.8)
  DENOMINATOR = 0.7714+0.2286*(ROUND**3.82)
  WRITE (*, '(F20.15)') NUMERATOR/DENOMINATOR
  STOP

... outputs 0.842201471328735 , while its C++ equivalent... ...输出0.842201471328735 ,而它的C ++等价...

int m = 2;
int round = 1;
long double numerator = 5.0 / pow((m-1)+pow(1.3, m), 1.8);
long double denominator = 0.7714 + 0.2286 * pow(round, 3.82);
std::cout << std::setiosflags(std::ios::fixed) << std::setprecision(15)
          << numerator/denominator << std::endl;
exit(1);

... returns 0.842201286195064 . ...返回0.842201286195064 That is, the computed values are equal only up to the sixth decimal . 也就是说,计算值仅等于第六个十进制数 Although not particularly a Fortran advocator, I feel inclined to consider its results as the 'correct' ones, given its legitimate reputation of number cruncher. 虽然不是特别是Fortran的倡导者,但我认为它的结果是“正确的”,因为它的数字cruncher的合法声誉。 However, I am intrigued about the cause of this difference between the computed values. 但是,我对计算值之间的这种差异的原因感到好奇。 Does anyone know what the reason for this discrepancy could be? 有谁知道造成这种差异的原因是什么?

In Fortran, by default, floating point literals are single precision, whereas in C/C++ they are double precision. 在Fortran中,默认情况下,浮点文字是单精度,而在C / C ++中它们是双精度。

Thus, in your Fortran code, the expression for calculating NUMERATOR is done in single precision; 因此,在您的Fortran代码中,计算NUMERATOR的表达式以单精度完成; it is only converted to double precision when assigning the final result to the NUMERATOR variable. 在将最终结果赋给NUMERATOR变量时,它仅转换为双精度。

And the same thing for the expression calculating the value that is assigned to the DENOMINATOR variable. 对于计算分配给DENOMINATOR变量的值的表达式,也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM