fortran 95 rounding up on it's own

扶醉桌前 提交于 2019-12-02 02:46:47

A decimal number such as "3.1" will likely not have an exact representation in a binary number of finite length. The source code statement x(1) = 3.1 causes the computer to convert that decimal number into binary and store it. The statement write (*, *) x(1) causes the computer to fetch this binary value and convert it to decimal. Because "3.1" could not be exactly represented in finite-length binary, the conversion to decimal does not precisely recover "3.1". This explains the output of "3.09999990". This is not Fortran specific, but general to finite precision floating point arithmetic.

As to the other problem, key is declared integer in the sort subroutine and is thus rounding the reals to integers. When I compiled your program with full compiler warnings turned on, gfortran notified me of this.

If you you gfortran, try the following compiler options: -O2 -fimplicit-none -Wall -Wline-truncation -Wcharacter-truncation -Wsurprising -Waliasing -Wimplicit-interface -Wunused-parameter -fwhole-file -fcheck=all -std=f2008 -pedantic -fbacktrace. You will also find that your program has a subscript error.

For the first part: it does use IEEE754, and that is the cause why the numbers are "changed".

The What Every Computer Scientist Should Know About Floating-Point Arithmetic article is a must read to understand how this is working, and there are good IEEE754 calculators too...

So 3.1 was never exactly 3.1, but

3.0999999046325684

in the first place.

As for the second part: they are not rounded up but converted to integers, but I'm not into Fortran, so I guess something is declared as int in the insertion_sort_REAL4 routine, that causes the numbers to be converted to integers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!