; NEWTON method for equations

; solves f(x)=0
; function is programmed at label f(x), it receives x on the stack
; it can use the whole stack and registers 4-9 and b-d

; set precision into register "e" (0.01 for example)
; in the X register, put a first guess of the solution and RUN.

; it returns the solution.
; you can start again with new parameters (precision or starting x)

; usage: store error in register e (example 0.01 STO e)
; go to first step ( B/0)
; key in the first x value and RUN.

#c3 1		; auto save to C3 file

#reg e error
#reg a x
#reg 0 delta
#reg 1 h
#reg 2 fxh
#reg 3 fx

DO
	=x
	$1e-4 =delta
	REPEAT
		@x @delta *
		IF(x=0)THEN
			@delta
		ENDIF
		=h			; h=0.0001x or 0.0001 if x=0
		@x + GOSUB f(x) =fxh	; calculates f(x+h)
		@x GOSUB f(x) =fx	; calculates f(x)
		@h *
		@fx @ fxh - /		; calculates dx = hf(x)/(f(x)-f(x+h)) = -f(x)/f'(x)
		ENTER
		sum x			; new x = x + dx
		x<>y abs
		@error -		; abs(dx) - error
	UNTIL(x<0)			; stop if <0 (if abs(dx) < error)
	@x				; display x
	STOP
LOOP

f(x):
RTN
	

		

