gfortran REAL not accurate to 8 decimal places [duplicate]

╄→尐↘猪︶ㄣ 提交于 2019-12-25 20:00:31

问题


This question has not been previously answered. I am trying to represent a real or any number for that matter in Fortran correctly. What gfortran is doing for me is way off. For example when I declare the variable REAL pi=3.14159 fortran prints pi = 3.14159012 rather than say 3.14159000. See below:

PROGRAM Test
IMPLICIT NONE
REAL:: pi = 3.14159
PRINT *, "PI = ",pi
END PROGRAM Test

This prints:

PI = 3.14159012

I might have expected something like PI = 3.14159000 as a REAL is supposed to be accurate to at least 8 decimal places.


回答1:


I'm in a good mood, so I'll try to answer this question, which is basic knowledge which can be easily googled (as already pointed out in the comments to this and your former question).


Luckily, Fortran provides some really interesting intrinsics to get some understanding of floating point numbers.

The 8 digits, you are talking about, are a rule of thumb and can be related to the function EPSILON(x), which prints the smallest deviation from 1, which can be represented within the chosen model (e.g. REAL4). This value is actually 1.19e-7 which means, that your 8th digit is most likely wrong. I write most likely, because some numbers can be represented exactly.

In the case of PI, the smallest representable deviation can be printed using the intrinsic SPACING(PI). This shows a value of 2.38e-7, which is slightly larger than the epsilon and still allows for 7 correct digits.

Now, why does your value of PI get stored as 3.14159012? When you store a floating point number, you always store the nearest representable number. Using the value of spacing, we can get the possible values for your pi. Possible numbers and their differences to your value of 3.14159 are:

3.14158988         1.20E-007
3.14159012        -1.18E-007
3.14159036        -3.56E-007

As you can see, 3.14159012 is the nearest possible value to 3.14159 and is thus stored and printed.




回答2:


It is common for the last two digit to be erroneous. It is called floating point error.

Check this: Week 1 - Lecture 2: Binary storage and version control / Fixed and floating point real numbers (9-08).mp4 @ https://class.coursera.org/scicomp-002/lecture



来源:https://stackoverflow.com/questions/23736413/gfortran-real-not-accurate-to-8-decimal-places

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