Why the code avoids storing these points

40 Views Asked by At

I have a very simple Euler's integration method. The author avoids storing specific points. I need to know why. This is Fortran 77 code but readable. I don't know the benefit of the variable S in the following code.

PROGRAM main

IMPLICIT REAL*8(A-H)
IMPLICIT REAL*8(O-Z)
OPEN(1,STATUS='UNKNOWN',FILE='DATFIL');
W=2.
T=0.
S=0.
X=0.
XD=W
H=.01
DO WHILE(T <= 10.)
    S=S+H
    XDD=-W*W*X
    XD=XD+H*XDD
    X=X+H*XD
    T=T+H
    IF(S>=.09999)THEN
        S=0.
        XTHEORY=SIN(W*T)
        WRITE(9,*)T,X,XTHEORY
        WRITE(1,*)T,X,XTHEORY
    ENDIF       
END DO  

END PROGRAM main
2

There are 2 best solutions below

2
On BEST ANSWER

S is only being used to produce output, via WRITE, every ten steps. Since all the output is written to units 1 (DATFIL) and 9 (unless your environment defines this unit, I'm used to this defaulting to the file fort.9), there is no reason to store the points.

You could of course, store the points in an array instead of, or in addition to, writing them to the file(s).


If you want to see every step in your file, replace this block

    IF(S>=.09999)THEN
        S=0.
        XTHEORY=SIN(W*T)
        WRITE(9,*)T,X,XTHEORY
        WRITE(1,*)T,X,XTHEORY
    ENDIF     

with this one

    XTHEORY=SIN(W*T)
    WRITE(9,*)T,X,XTHEORY
    WRITE(1,*)T,X,XTHEORY

You are free to also remove S=0. and S=S+H, as they are no longer needed.

2
On

I don't know why you think this "avoids storing specific points": no points are stored at all. The code is solving the differential equation $x''(t) = -w^2 x(t)$ for $0 \le t \le 10$ with step size $h = 0.01$. The S is just there so that results will be printed (along with the "theory" values $\sin(w t)$) at $t$ intervals of $0.1$, thus every $10$ steps.