Menu Close

Secant Method | Python

The secant method is a root-finding algorithm that uses a succession of roots of secant lines to better approximate a root of a function.

It is similar to the Newton-Raphson method, but does not require the computation of derivatives.

Secant method in Python:

  • Function

f(x) = $x^{2} – x – 1$

				
					def secant(f, x0, x1, tol=1e-9):
    """
    f: a function that takes a single argument
    x0: initial estimate for the root
    x1: second initial estimate for the root
    tol: tolerance for the stopping criterion
    """
     # Secant Method [By Bottom Science]
    
    while abs(x1 - x0) > tol:
        x2 = x1 - f(x1)*(x1 - x0)/(f(x1) - f(x0))
        x0, x1 = x1, x2
    return x1

# Test
def f(x):
    return x**2 - x - 1

root = secant(f, 0, 2, 1e-6)
print(root)
# Output: 1.61803399

				
			

More Related Stuff