Different precision in C++ and Fortran(C++ 和 Fortran 中的不同精度)
问题描述
对于我正在进行的项目,我用 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.
这篇关于C++ 和 Fortran 中的不同精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 和 Fortran 中的不同精度
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
