Roots of a function: Difference between revisions

Content added Content deleted
(Scala contribution maintained.)
(made local variable declarations explicit, added explicit types)
Line 1,311: Line 1,311:


Without the Roots package, Newton's method may be defined in this manner:
Without the Roots package, Newton's method may be defined in this manner:
<lang Julia>function newton(f, fp, x,tol=1e-14,maxsteps=100)
<lang Julia>function newton(f, fp, x::Float64,tol=1e-14::Float64,maxsteps=100::Int64)
#f: the function of x
##f: the function of x
#fp: the derivative of f
##fp: the derivative of f

xnew, xold = x, Inf
local xnew, xold = x, Inf
fn, fo = f(xnew), Inf
local fn, fo = f(xnew), Inf
local counter = 1
counter = 1

while (counter < maxsteps) && (abs(xnew - xold) > tol) && ( abs(fn - fo) > tol )
while (counter < maxsteps) && (abs(xnew - xold) > tol) && ( abs(fn - fo) > tol )
x = xnew - f(xnew)/fp(xnew) # update step
x = xnew - f(xnew)/fp(xnew) ## update x
xnew, xold = x, xnew
xnew, xold = x, xnew
fn, fo = f(xnew), fn
fn, fo = f(xnew), fn
counter = counter + 1
counter += 1
end
end

if counter == maxsteps
if counter >= maxsteps
error("Did not converge in ", string(maxsteps), " steps")
error("Did not converge in ", string(maxsteps), " steps")
else
else