问题描述
对于我正在使用C ++编写的一个非常简单的函数的项目:
Fne(x)= 0.124 * x * x
,问题是当我计算<$ p
$ b
的函数值 x = 3.8938458092314270
与Fortran 77和C ++语言,我有不同的精度。
对于Fortran,我得到 Fne(x)= 1.8800923323458316
和C ++我得到 Fne(x)= 1.8800923630725743
。对于这两种语言,Fne函数被编码为双精度值,并且还返回双精度值。
C ++代码:
double FNe(double X){
double FNe_out;
FNe_out = 0.124 * pow(X,2.0);
返回FNe_out;
}
Fortran代码:
real * 8 function FNe(X)
implicit real * 8(ah,oz)
FNe = 0.124 * X * X
return
end
你能帮我找一下这个区别吗?
一个不同的来源是C ++和Fortran的默认处理常数,例如 0.124
。默认情况下,Fortran会将其视为单精度浮点数(几乎可以使用任何计算机和编译器组合),而C ++将其视为双精度fp数。
在Fortran中,您可以指定一个fp数字(或任何其他内在数字常量)的类
,并且没有任何编译器选项可以更改最可能的默认行为)通过后缀 kind-selector 这样
0.124_8
尝试一下,看看有什么结果。
哦而在写作的时候,为什么你写的是Fortran,就像1977?对于所有其他Fortran专家来说,是的,我知道, * 8
和 _8
不是最佳做法,我现在还没有时间来扩展这个。
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.
这篇关于C ++和Fortran的精度不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!