In the code below I am adding together 865398.78 and -865398.78. I expect to get 0, but instead I get -0.03.
The number 865398.78 is represented in single precision in your code. Single precision can handle about 7 significant digits, while your number has 8. You can make it double precision by writing
x=x+865398.78_8
I will make one big assumption in this answer: that real(8)
corresponds to double precision
.
You are probably assuming that your 865398.78
means the same thing wherever it occurs. In source code that is true: it is a default real literal constant which approximates 865398.78.
When you have
x=x+865398.78
for x
double precision, then the default real constant is converted to a double precision value.
However, in the read statement
read(10,*)x
given input "-865398.78
" then x
takes a double precision approximation to that value.
Your non-zero answer comes from the fact that a default real/single precision approximation converted to a double precision value is not in general, and isn't in this case, the same thing as an initial double precision approximation.
This last fact is explained in more detail in other questions. As is the solution to use x=x+865398.78_8
(or better, don't use 8
as the kind value).