What is the correct way to handle a potential divide by zero issue in FORTRAN?

  • Topic: Fortran 
  • Thread starter Thread starter debbieanne
  • Start date Start date
  • Tags Tags
    Arithmetic Fortran
Join the discussion
Registration is free. Start your own thread to ask a follow-up.
7 replies · 2K views
debbieanne
Messages
12
Reaction score
1
Good day,
I'm working with a FORTRAN program that has the line:
EDEN=EDEN+(STVS**2)/(N(J)-1)

I would like to check if N(J)-1 is equal to zero. If so make N(J)-1=1.0

The following doesn't work:
IF ((N(J)-1).EQ.0.0) THEN
N(J)-1=1.0
END IF

I'm using gfortran and am getting unclassified statement at 1. The 1 is pointing to the beginning of the line N(J)-1=1.0
 
Physics news on Phys.org
debbieanne said:
Good day,
I'm working with a FORTRAN program that has the line:
EDEN=EDEN+(STVS**2)/(N(J)-1)

I would like to check if N(J)-1 is equal to zero. If so make N(J)-1=1.0

The following doesn't work:
IF ((N(J)-1).EQ.0.0) THEN
N(J)-1=1.0
END IF

I'm using gfortran and am getting unclassified statement at 1. The 1 is pointing to the beginning of the line N(J)-1=1.0

It would probably be better coding to do
IF ((N(J)-1).EQ.0) THEN
N(J)-1=1
END IF

Make sure N is declared as an INTEGER array, otherwise the compiler won't know how to handle N(J).
 
debbieanne said:
I would like to check if N(J)-1 is equal to zero. If so make N(J)-1=1.0
IF ((N(J)-1).EQ.0.0) THEN
N(J) = 2
END IF
EDEN=EDEN+(STVS**2)/(N(J)-1)

I'm not familiar with FORTRAN, but I don't think you may do calculations to the left of the equality ( = ) in: N(J)-1 = 1
That' s why you get an error.
 
Hesch said:
IF ((N(J)-1).EQ.0.0) THEN
N(J) = 2
END IF
EDEN=EDEN+(STVS**2)/(N(J)-1)

I'm not familiar with FORTRAN, but I don't think you may do calculations to the left of the equality ( = ) in: N(J)-1 = 1
That' s why you get an error.
Good catch. I missed that. :frown:
 
SteamKing said:
Good catch. I missed that. :frown:

Thanks for this.

IF ((N(J)-1).EQ.0.0) THEN
N(J) = 2
END IF
EDEN=EDEN+(STVS**2)/(N(J)-1)

Worked perfect.
 
Last edited by a moderator:
SteamKing said:
It would probably be better coding to do
IF ((N(J)-1).EQ.0) THEN
N(J)-1=1
END IF

Make sure N is declared as an INTEGER array, otherwise the compiler won't know how to handle N(J).
Hi SteamKing...I tried your solution but got the same error. However, Hesch's code worked. Thanks so much for helping.
 
debbieanne said:
Hi SteamKing...I tried your solution but got the same error. However, Hesch's code worked. Thanks so much for helping.
As Hesch said, you can't assign a value to an expression such as N(J) - 1.
 
Yes, it is good to be careful with denominators. But, N(J) may be needed on its own later on and should probably be left unmodified, maybe something like this?
Fortran:
den = N(J) - 1
if (den .eq. 0) den = 1
EDEN = EDEN + STVS**2/den