# L-6 MCS 471 Fri 2 Sep 2022 : secantmethod.jl # A basic implementation of the secant method. using Printf """ Applies the secant method to a function. ON ENTRY : f a function in one variable x1,x2 two start points dxtol tolerance on the forward error fxtol tolerance on the backward error N maximum number of iterations ON RETURN : (x, absdx, absfx, nbrit, fail) x approximation for the root absdx estimated forward error absfx estimated backward error nbrit number of iterations fail true if tolerances not reached, false otherwise. EXAMPLE: (root, err, res, nit, fail) = secant(cos,pi/4,2*pi/3) """ function secant(f::Function,x1::Float64,x2::Float64, dxtol::Float64=1.0e-8,fxtol::Float64=1.0e-8,N::Int64=10) dx = 1 println("running the secant method...") title = " root |dx| |f(x)|" println("step : $title") fx1 = f(x1) fx2 = f(x2) for i = 1:N dx = fx2*(x2 - x1)/(fx2 - fx1) x1 = x2 # store x2 for next step x2 = x2 - dx fx1 = fx2 fx2 = f(x2) stri = @sprintf("%3d", i) strx = @sprintf("%.16e", x2) strdx = @sprintf("%.2e", abs(dx)) strfx = @sprintf("%.2e", abs(fx2)) println("$stri : $strx $strdx $strfx") if((abs(fx2) < dxtol) | (abs(dx) < fxtol)) stri = string(i) println("succeeded after $stri steps") return (x2, abs(dx), abs(fx2), i, false) end end strN = string(N) println("failed requirements after $strN steps") return (x2, abs(dx), abs(fx2), N, true) end # result = secant(cos,pi/4,2*pi/3)