user3505300
user3505300

Reputation: 1

Fortran 95 Nesting of loops (beginner)

I am new to fortran 95 and I am trying to get a grip on nested loops. Below is a small code with a nested loop. The inner loop is the secant method that calculates the root of the function "Z+X1**2-612" and saves it as X0 via iteration. ISTEP is howmany iterations it took. This loop on its own works. Now I want to repeat this loop for various "Z". For example from 300 to 360 with increments of 10.

If I run this code, the Z will vary from 300 to 360 as it should, but I keep getting the X0 for 300 (i.e. square root of 312).

Is there somebody that has experience with nested loops (not necessarily with the secant method, since this inner loop works), that can tell me why I print out 300 to 360 well, but X0 as if Z never changes from 300? I browsed through the forum, and found some similar issues that had variable declarations placed wrongly, but this doesn't seem the problem in my case.

Hereunder is my code, hope somebody can help me. I am a bit old to start to learn programming, but never too late I guess!

PROGRAM DOLOOP2

 IMPLICIT NONE
  INTEGER :: ISTEP,Z
  REAL :: A,B,DL,DX,X0,X1,D,X2

  DL = 1.0E-06 
  A  = 10 !LOWER GUESS
  B  = 20 !UPPER GUESS
  DX = (B-A)/10.0 !STEPSIZE
  X0 = (A+B)/2.0 
  ISTEP = 0 !first iteration
  X1 = X0+DX

do Z=300,360,10
DO WHILE (ABS(DX).GT.DL)
    D  = (Z+X1**2-612)-(Z+X0**2-612)
    X2 = X1-(Z+X1**2-612)*(X1-X0)/D
    X0 = X1
    X1 = X2
    DX = X1-X0
    ISTEP = ISTEP+1
END DO
print *,'temperature=',Z,', Xzero= ',X0,'iterations=',ISTEP
END DO

END PROGRAM DOLOOP2

Upvotes: 0

Views: 255

Answers (1)

M. S. B.
M. S. B.

Reputation: 29391

Do you need to have some of the initializations for the inner loop repeated before the loop is redone? i.e., relocated to be inside the first loop, before the second loop. For example, the first execution of the inner loop will change the value of dx, which will effect the second execution of that loop.

Upvotes: 1

Related Questions