General Numerics¶
One-dimensional Secant solver¶
If you have a function \(f\), which is a function of a single variable \(x\) and the derivative of f cannot be found in a simple fashion, a secant solver can be used to find the value of \(x\) that yields the equality \(f(x)=0\).
The secant solver requires two initial guesses which set the search direction of the secant search. It is not necessarily well-behaved, and can struggle to find a solution at times. Also, if there are multiple solutions, you must start quite close to the solution that you want. All that said, it is a simple model to implement, and performs quite admirably most of the time. With the two initial guesses for \(x\) of \(x_0\) and \(x_1\), the function is evaluated at these points, yielding the functional values \(f_0=f(x_0)\) and \(f_1=f(x_1)\). The new guess for \(x\) is then found from
and the values of \(x_i\) and \(f_i\) are updated and this method is repeated until \(|f(x)|\) is small enough.
The Scientific Python package includes an implementation of this method, and a simple example of its use is
#Import the newton function (implements secant method if no function derivative provided)
In [1]: from scipy.optimize import newton
# newton(function handle, x0), also see
# http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.newton.html
In [2]: newton(lambda x: x**2-0.4,1.5)
Out[2]: 0.6324555320337425
# The exact solution - should be the same.
# a**b in Python is a to the power of b
In [3]: 0.4**0.5