Beliavsky / FortranTip

Short instructional Fortran codes associated with Twitter @FortranTip
https://zmoon.github.io/FortranTipBrowser/
The Unlicense
64 stars 14 forks source link

Tip: integer division #42

Open Beliavsky opened 2 years ago

Beliavsky commented 2 years ago

Given integer variables i and j write

real(i,wp)/j or i/real(j,wp) or real(i,wp)/real(j,wp)

where wp is the KIND argument to get a real(kind=wp) quotient, unless you want the truncating integer division resulting from

i/j

In Fortran 1/2 = 0.

tkoenig1 commented 2 years ago

Possibly a better way to write the same statement:

When dividing two integer numbers, you will get a truncated integer, not a real number, so 1/2 is 0 (gfortran will warn about this with -Wall, but for constants only).

If what you really want is the real number, write real(i,wp)/j , i/real(j,wp), ...