- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
[fortran]program prec
double precision :: a,b,x,y
a=1./3.
x=1.
y=3.
b=x/y
print *,"kind=",kind(a), " val=",a
print *,"kind=",kind(b), " val=",b
if(a==b) then
print *,"OK!"
else
print *,"Why 'a' and 'b' are different?!"
end if
end program[/fortran]
We compile this by:
ifort prec.f90
Result:
kind= 8 val= 0.333333343267441
kind= 8 val= 0.333333333333333
Why 'a' and 'b' are different?!
Why such a misleading behavior?
Link Copied
1 Reply
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Please read a few Fortran/programming-related text books and manuals. There is nothing unusual or buggy here at all.
The right-hand sides of lines 5, 6 and 7 are single-precision expressions. In particular, the expression 1./3. is single precision, which implies that it is correct to about seven decimal digits. Assigning such values to double precision variables cannot restore lost precision.
The values assigned to x and y, however, happen to have values (small integers) that are exactly representable in single or double precision. Therefore, the expression x/y is calculated in double precision and the quotient is the best that double precision is capable of delivering.
The right-hand sides of lines 5, 6 and 7 are single-precision expressions. In particular, the expression 1./3. is single precision, which implies that it is correct to about seven decimal digits. Assigning such values to double precision variables cannot restore lost precision.
The values assigned to x and y, however, happen to have values (small integers) that are exactly representable in single or double precision. Therefore, the expression x/y is calculated in double precision and the quotient is the best that double precision is capable of delivering.

Reply
Topic Options
- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page