I'm trying to Pythonize a FORTRAN77 code. There's a block of code that I just can't seem to grasp the intent of.
ZM is just a scalar between 0 and 1. Z is a 1D array of numbers between 0 and 1 with NJ elements. J, J1, and J1M are type INTEGER. PDFZ is another 1D array with NJ elements. I'm having trouble mapping out the flow of execution.
DO 18 J=2,NJ
IF(ZM.GT.Z(J)) GOTO 18
J1=J
J1M=J-1
GOTO 20
18 CONTINUE
20 CONTINUE
DO 22 J=1,NJ
PDFZ(J)=0.D0
22 CONTINUE
PDFZ(J1)=(ZM-Z(J1M))/(Z(J1)-Z(J1M))
PDFZ(J1M)=1.D0-PDFZ(J1)
I created what I thought was the equivalent in Python2.7. But I'm not so sure anymore that my python code captures the behavior of the Fortran77 code.
loc = np.where(z < z_mean)[0][0]
pdf_z[loc] = (z_mean - z[loc-1])/(z[loc] - z[loc-1])
pdf_z[loc-1] = 1.0 - pdf_z[loc]
I had already been programming for about eight years when 1977 rolled in. Fortunately this code is bedrock with nothing abstruse or complicated. Not that I can discern what it does either.
However, I can translate it. Here it is in a form in which you can experiment with it.
- Fortran arrays were 1-relative; ie, the first element of a 1-D array was number one.
- As you already know, Python floats are doubles.
- Fortran DO-loop variables assume each and every value from the first to the last, unlike Python for-loop variables.
- The
GOTO 18
targets the end of the DO-loop. The loop will continue with the next value of the DO-loop variable, J
.
- In contrast,
GOTO 20
targets a line outside of the loop and is, hence, like a Python break
.
def sample(ZM):
Z = [_/10 for _ in range(0,11)]
NJ = len(Z)
for J in range(1, NJ):
if ZM > Z[J]:
continue
J1 = J
J1M = J - 1
break
PDFZ = NJ * [0]
PDFZ[J1] = (ZM - Z[J1M])/(Z[J1] - Z[J1M])
PDFZ[J1M] = 1 - PDFZ[J1]
print (ZM, PDFZ)
for ZM in [0, .1, .2, .3, ]:
sample(ZM)