Hi, Karl:
Karl posted:
""I pity the fool" who must program in RPL! ;-)"
Indeed ! Especially as the algorithm itself is so simple. This would be the no-frills HP-71B version, and I'm sure everyone would agree it's much more understandable (line numbers are arbitrary and comments aren't needed, of course):
100 ! Basic Newton's Method: x1=x0-f(x)/f'(x)
110 !
120 ! Ask for initial guess and tolerance
130 !
140 INPUT "Initial guess=";X0 @ INPUT "Tolerance=";T @ D=.00001
150 !
160 ! Perform up to 50 iterations and output result
170 !
180 FOR I=1 TO 50 @ X1=X0-FNF(X0)/FND(X0)
190 IF ABS(X1-X0)<T THEN PRINT "Root=";X1 @ END ELSE X0=X1
200 NEXT I @ PRINT "No convergence after 50 iterations"
210 !
220 ! Derivative computation: f'(x)
230 !
240 DEF FND(X)=(FNF(X+D)-FNF(X-D))/(2*D)
250 !
260 ! Define your function below: f(x)
270 !
280 DEF FNF(X)=X^3-6*X-2
where the equation being solved is
x3-6x-2=0, simply defined at line 230 as FNF(X). For instance, to compute all three distinct roots:
>RUN
Initial guess = 2
Tolerance = 1E-10
Root = 2.60167913188
>RUN
Initial guess = 0
Tolerance = 1E-10
Root = -.339876886624
>RUN
Initial guess = -2
Tolerance = 1E-10
Root = -2.26180224527
if no convergence occurs within 50 iterations (because the
equations has no real roots, for instance), such as when
f(x)=
x2+1 = 0, this is what happens:
>230 DEF FNF(X)=X^2+1
>RUN
Initial guess = 2
Tolerance = 1E-10
No convergence after 50 iterations
An important difference between my HP-71B version and Namir's RPL one is that I compute the derivative using a much more accurate 2nd-order method (error proportional to h2) instead of the 1st-order method (error proportional to h) he uses. Not that great accuracy is required for Newton's method, mind you, and you need three calls to f(x) instead of only two, but then you have the bonus of being able to compute a fairly accurate derivative right from the keyboard by simply calling FND with your argument.
" Good thing that the 49G+ has equation solving built in."
Oh, if built-in solvers are permitted then the HP-71B version is
simply:
PRINT FNROOT(0,3,FVAR^3-6*FVAR-2)
2.60167913189
where you can even omit the PRINT. I don't know why, but I
strongly suspect that the 49G+ built-in equation solving process is still more
complicated than that. As some clever contributor told me recently in a private communication:
"I have to admit that RPL makes you focus more on the technicalities of the stack (DUP, DUP2, ROLL,
ROLLD, OVER, PICK, etc...) rather than on your algorithms ..."
I couldn't have said it better.
Best regards from V.
Edited: 9 Mar 2006, 6:57 a.m.