Fortran 数字格式
我正在使用英特尔® Visual Fortran 编译器专业版 11.1,当我运行此代码时,
program Console1
implicit none
real(8), parameter:: iterations = 1000.d0
real(8), parameter:: maximum = 0.02d0
integer, parameter:: outfile=1
real(8) force, dforce
integer i
dforce = maximum/iterations
force = 0.d0
open (unit=outfile,file="results.txt",action="write",status="replace")
do i=0,int(iterations)
write(outfile, *) force
force = force+dforce
enddo
close(outfile)
endprogram
文件 results.txt 一团糟,最终数字是 1.999999999999952E-002 而不是 2.d-2
我做错了什么? 谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不会再有!浮点数并不是实数的精确表示。时期。
每个计算机科学家应该了解的浮点运算知识 。
Not again! Floating point numbers are not exact representations of real numbers. Period.
What Every Computer Scientist Should Know About Floating-Point Arithmetic.
你和 fortran 都没有做错什么。您遇到了算术计算方式的基本限制。
计算机以有限的精度以二进制形式存储数字“力”,而不是精确的分数或小数。永远不会使用精确值 - 仅达到一定程度的精度。
kemiisto 发布的链接更详细地解释了这一点,但最主要的是它的口头禅:“真实(浮点)数字永远不会精确”。这意味着每当您需要比较两个实数时,除非它们具有一些非常具体的值(例如零),否则您需要检查它们是否接近,而不是相同。
您可以使用格式说明符修改最后打印数字的方式:
http://www.cs.mtu.edu/ 〜shene/COURSES/cs201/NOTES/chap05/format.html
Neither you nor fortran is doing anything wrong. You are coming up against a fundamental limit of how arithmetic is done computationally.
The computer is storing the number "force" with limited precision, in binary, not as an exact fraction or decimal. The exact value is never used - only a certain level of accuracy is reached.
The link that kemiisto posted explains in more detail, but the main thing to take from it is the mantra: "real (floating point) numbers are never exact". It means that whenever you need to compare two reals, unless they have some very specific value like zero, then you need to check if they are close, not identical.
You can modify how the number is printed out at the end using format specifiers:
http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/chap05/format.html
回答这个问题:
该语句
使用 Fortran 所说的“列表定向 I/O”。 “*”让编译器为变量“force”的输出找出合理的格式。如果要控制输出的格式,请使用 Fortran 的编辑描述符。例如,
将根据描述符“f6.3”格式化数字——这并不完全是提问者想要的,但我希望这能让她走上正确的轨道。
To answer the question:
the statement
uses what Fortran calls 'list-directed I/O'. The '*' leaves it to the compiler to figure out a reasonable format for the output of the variable 'force'. If you want to control the format of your output, use Fortran's edit descriptors. For example
will format the number according to the descriptor 'f6.3' -- which is not quite what the questioner wants, but I hope it will put her on the right track.