; ************** NEWTON'S METHOD **************
;                Equation solver
;                    f(x)=0
; ********* guillaume.tello@orange.fr *********

#set EXAMPLE

;---------------
; the procedures
;---------------

#label A initial_X
#label B set_precision
#label E function
#label C solve

;--------------
; the variables
;--------------

#reg 0 x
#reg 1 dx
#reg 2 h
#reg 4 precision
#reg 3 temp

;-------------------------
; X0 A to init the x value
;-------------------------

    LBL initial_X
        STO x
    RTN

;-------------------------
; e B to set the precision
;-------------------------

    LBL set_precision
        STO precision
    RTN

;-----------------
; C to solve for x
;-----------------

    LBL solve
    
    DO
            dx,temp={ @x SBR f(x) }     ; dx, temp = f(x)

            h={ 
                0 X/T @x 
                IF(x<>t)
                    *
                ENDIF
                $1e-4 =
              }                         ; if x=0 then h=0.0001 else h=x*0.0001
           
            SUM x                       ; x=x+h
              
            temp-{ @x SBR f(x) }        ; temp=f(x)-f(x+h)
            dx/{ @temp }                ; dx=f(x)/[f(x)-f(x+h)]
            dx*{ x-{ @h } }             ; x restored, dx=h*f(x)/[f(x)-f(x+h)]
                                        ; dx approximates -f(x)/f'(x)
            @precision X%T 
            x+{ @dx }                   ; x=x+dx
            ABS
    UNTIL(X<T)                          ; loop until abs(dx) < precision
    
            X/T   INV EE   RCL x        ; else, display x and precision met in T
    RTN

;------------------------------------
; here the user function with
; variable in RCL x or at the display
;------------------------------------

    LBL function
    f(x):
    
?EXAMPLE - COS =

    RTN

#end