Why does this fortran program produce only zeros? When I print it out i get -0.00000 everywhere! What have I done wrong? In matlab it runs perfectly. I dont see any reason why its not working to be honest!
It seems like its the fraction that messes it up. if I set x equal to some decimal number it works.
program main
implicit none
integer iMax, jMax
double precision, dimension(:,:), allocatable :: T
double precision x, dx,f,L2old,L2norm,y
integer i, j,n,bc
n=10
allocate(T(1:n+2, 1:n+2))
T=0.0d0
do i=2,n+1
do j=2,n+1
x=(j+1)*1/24
y=(i+1)*1/24
T(i,j)= -18*(x**2+y**2)**2
Write(*,*)'T(',i,'',j,'', T(i,j)
end do
end do
Write(*,*)'T(1,1)',T(1,1)
end program main
1/24
is an integer division that rounds down to 0. You should be able to force floating point division by making at least one of the operands floating point, e.g.As was indicated by Jim Lewis, the answer to the OP's question was indeed the integer division used.
Nonehteless, I think it is important to point out that one should take care of how the floating point fraction is written down. As the OP's program shows,
x
was of typeDOUBLE PRECISION
. Then the correct result should beThe difference here is that now you ensure that the division happens with the same precision as
x
was declared.To following program demonstrates the problem ::
which as the output
You clearly see the differences. The first line is the mathematical correct result. The second line is the integer division leading to zero. The third line, shows the output in case the division is computed as
REAL
while the fourth and fifth line are inDOUBLE PRECISION
. Please take into account that in my caseREAL
implies a 32bit floating point number andDOUBLE PRECISION
a 64 bit version. The precision and representation of bothREAL
andDOUBLE PRECISION
is compiler dependent and not defined in the Standard. It only requires thatDOUBLE PRECISION
has a higher precision thanREAL
.This actually implies that, if you want to ensure that your computations are done using 32bit, 64bit or 128bit floating point representations, you are advised to use the correct
KIND
values as defined in the intrinsic moduleISO_FORTRAN_ENV
.So this would lead to the following code