% example of an external function routine using the Newton-Raphson method
% for finding one root of a function f(x) for which we do not know the 
% analytical expression of the first derivative

% INPUT
% f      function f(x) defined as an anonymous function 
%        (or an external function)
% x0     initial guess of the zero
% dx     dx^2 is the accuracy for first derivative
% err    required precision for knowing the function root

% OUTPUT
% xzero  zero of the function
% fzero  value of the function at xzero
% iter   number of iterations required to find the zero with the accuracy
%        err


function [xzero, fzero, iter] = NewtonRaphson_noanalytic( f, x0, dx, err )
i=0;
while abs(f(x0))>2*err
    fpx0=( f(x0+dx)-f(x0-dx) )/(2*dx);
    x1=x0-f(x0)/fpx0;
    x0=x1;
    i=i+1;
end
xzero=x0;
fzero=f(xzero);
iter=i;
end