Fortran中实数的精度问题 [英] Precision problems of real numbers in Fortran

查看:494
本文介绍了Fortran中实数的精度问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图将Fortran用于我的研究项目,使用GNU Fortran编译器(gfortran),最新版本
,但我在处理实数方面遇到了一些问题。如果你有例如代码:

 程序测试
隐式无

真实: :y = 23.234,z

z = y * 100000
写(*,*)y,z

结束程序
  

> 23.23999 2323400.0

我觉得这很奇怪。
有人可以告诉我这里发生了什么?看着z我可以看到y确实保留了它的精确度,所以对于我认为不应该成为问题的计算来说。但为什么y的输出与我指定的值不完全相同,我该怎么做才能使它完全一样?

解决方案

这不是问题 - 您所看到的只是计算机中数字的浮点表示。计算机不能准确处理实际数字,但只能近似处理它们。关于此的一个很好的阅读可以在这里找到:每个计算机科学家应该知道什么关于浮点算术


I've been trying to use Fortran for my research project, with the GNU Fortran compiler (gfortran), latest version, but I've been encountering some problems in the way it processes real numbers. If you have for example the code:

program test
implicit none

real :: y = 23.234, z

z = y * 100000
write(*,*) y, z

end program

You'll get as output:

23.23999    2323400.0 

I find this really strange. Can someone tell me what's exactly happening here? Looking at z I can see that y does retain its precision, so for calculations that shouldn't be a problem I suppose. But why is the output of y not exactly the same as the value that I've specified, and what can I do to make it exactly the same?

解决方案

This is not a problem - all you see is floating-point representation of the number in the computer. The computer cannot handle real numbers exactly, but only approximations of them. A good read about this can be found here: What Every Computer Scientist Should Know About Floating-Point Arithmetic.

这篇关于Fortran中实数的精度问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆