Code: Select all
' Finding a solution of an arbitrary equation.
' Solution method is the Newton-Raphson iteration.
' In the call statement the parameters are:
' a starting value for the variable x (here 1.37)
' the desired precision (here .0000001)
' The algoritm does not converge to a solution for every equation
' and for every starting value, but in most cases it will converge
' to a solution and will do so very fast.
' If the algoritm does not converge to a solution, a result of
' -999 is returned; you can test on this value in the calling
' program.
' If an equation has multiple roots, only one of them will be found
' at one time. If you have some knowledge about the region where the
' desired solution is, then give a starting value somewhere in that
' region.
' You may enter any formula in the def y(x) function after the =
' sign.
'
' test program for Newton-Raphson iteration
'
result=solve(1.37,.0000001)
print result
end
def y(x) = x^3-5*sin(x)*exp(-2*x)-5
def solve(xo,eps)
x=xo ! count=0 ! maxcount=100
do
y_acc=(y(x)-y(x-.01))/.01
dx=y(x)/y_acc ! x=x-dx ! count=count+1
until abs(dx)<eps or count=maxcount
if count<maxcount then solve=x else solve=-999
end def