Commodore 64: Using the Newton/Raphson method and Halley’s method to find the zeros of a function

Click for good descriptions of Newton’s method and Halley’s method.

I decided to write my C64 Basic code for two different functions:

  • f(x) = x*x*x – 2*x – 5
  • f(x) = exp(x) – x*x

Here are the plots for these functions, with the roots indicated by a blue dot:

These methods require choosing a first guess for the root. In both cases I chose x = 2 as a first guess.

Here is the code:

 10 REM ===============================
 20 REM
 30 REM FIND THE ZEROS OF A FUNCTION
 35 REM USING NEWTON/RAPHSON METHOD
 40 REM AND HALLEY'S METHOD
 60 REM
 70 REM ===============================
 100 PRINT CHR$(147)
 200 DEF FN F(A) = A*A*A - 2*A - 5 
 210 DEF FN F1(A) = 3*A*A - 2 
 220 DEF FN F2(A) = 6*A
 230 E$ = "XXX - 2X - 5" 
 235 PRINT "--------------------------------------" 
 240 GOSUB 10000 
 245 PRINT "--------------------------------------" 
 250 GOSUB 20000 
 300 DEF FN F(A) = EXP(A) - A*A
 310 DEF FN F1(A) = EXP(A) - 2*A 
 320 DEF FN F2(A) = EXP(A) - 2  
 330 E$ = "EXP(X) - X*X"
 335 PRINT "--------------------------------------"
 340 GOSUB 10000
 345 PRINT "--------------------------------------"
 350 GOSUB 20000
 1000 END
 10000 REM NEWTON/RAPHSON
 10002 X = 2
 10005 S = 0 : DI = 10 : TL = 0.000001
 10010 IF DI < TL THEN GOTO 10100
 10020 G = FN F(X) : G1 = FN F1(X)
 10030 X1 = X - G/G1
 10040 DI = ABS(X - X1)
 10050 X = X1
 10060 S = S + 1
 10070 GOTO 10010
 10100 PRINT "NEWTON'S METHOD FOR: ";E$
 10110 PRINT "ROOT = ";X
 10120 PRINT "F(ROOT) = "; FN F(X)
 10130 PRINT "FOUND IN ";S;" STEPS"
 10200 RETURN
 20000 REM HALLEY
 20002 X = 2
 20005 S = 0 : DI = 10 : TL = 0.000001
 20010 IF DI < TL THEN GOTO 20100
 20020 G = FN F(X) : G1 = FN F1(X)
 20025 G2 = FN F2(X)
 20030 NU = 2 * G * G1
 20040 DE = 2 * G1 * G1 - G * G2
 20050 X1 = X - NU/DE
 20060 DI = ABS(X - X1)
 20070 X = X1
 20080 S = S + 1
 20090 GOTO 20010
 20100 PRINT "HALLEY'S METHOD FOR ";E$
 20110 PRINT "ROOT = ";X
 20120 PRINT "F(ROOT) = "; FN F(X)
 20130 PRINT "FOUND IN ";S;" STEPS"
 20200 RETURN

Here is the screen shot:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s