我一直试图将Fortran用于我的研究项目,使用GNU Fortran编译器(gfortran),最新版本,但我在处理实数方面遇到了一些问题。如果你有例如代码:
程序测试隐式无 真实: :y = 23.234,z z = y * 100000 写(*,*)y,z 结束程序 $ c $ > 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.