Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Math Error in gfortran?

I am a beginner with regards to programming in Fortran. I am currently using cygwin and the gfortran compiler running on my Windows XP PC. I'm having difficulty with some simple math - the program I wrote simply won't do the math. The code is:

program convert
real t

t=0
t=8320671.25 - 8000000.00

write(*,*) t
end

The program should give me the answer "320671.25" but gives me 320671.00 instead! What am I doing wrong?

like image 986
Dexter Ferreira Avatar asked Apr 06 '26 20:04

Dexter Ferreira


1 Answers

You're running into the single precision limit. The result of the subtraction is a real*4, and can be safely stored in t. The values used in the subtraction, however, are outside the real*4 range. Outside in the range of precision, with the result that the numbers are rounded to fit into a real*4 before calculating the subtraction.

Try this for example:

program convert
real t

t=0
t=8320671.25_8 - 8000000.00_8

write(*,*) t
end

The appended _8 ensures the two numbers are double precision; the result is then converted to real before assigned to t, but the calculation is now in double precision, and the .25 is "saved" in the subtraction.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!