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 中的不同精度
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
