Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Modelling the Secant Method in Python
The Secant method is a powerful numerical technique for finding roots (x-intercepts) of polynomial or transcendental functions. Unlike the Newton-Raphson method, it doesn't require derivatives, making it more practical for complex functions.
How the Secant Method Works
The method starts by selecting two initial points (x?, x?) near the expected root. A secant line connects the corresponding points on the function curve. Where this line intersects the x-axis gives us the next approximation x? ?
The process repeats: we use x? and x? to find x?, then x? and x? to find x?, continuing until consecutive approximations are sufficiently close.
Mathematical Formula
The general formula for the next approximation is ?
xn = xn-2 - f(xn-2) × [(xn-1 - xn-2) / (f(xn-1) - f(xn-2))]
Python Implementation
Let's implement the secant method to find roots of f(x) = x² + 3x - 10 ?
import math
def secant_method(func, x0, x1, tolerance=1e-6, max_iterations=50):
"""
Find root using secant method
"""
for i in range(max_iterations):
# Calculate function values
f0 = func(x0)
f1 = func(x1)
# Check if denominator is zero
if abs(f1 - f0) < 1e-14:
print("Division by zero encountered")
return None
# Calculate next approximation
x2 = x1 - f1 * (x1 - x0) / (f1 - f0)
# Check convergence
if abs(x2 - x1) < tolerance:
print(f"Converged after {i+1} iterations")
return x2
# Update values for next iteration
x0, x1 = x1, x2
print(f"Iteration {i+1}: x = {x2:.6f}, f(x) = {func(x2):.6f}")
print("Maximum iterations reached")
return x1
# Define the function f(x) = x^2 + 3x - 10
def f(x):
return x**2 + 3*x - 10
# Find root with initial guesses
print("Finding root of f(x) = x² + 3x - 10")
print("Initial guesses: x0 = -4, x1 = 3")
root = secant_method(f, -4, 3)
print(f"Root found: {root:.6f}")
print(f"Verification: f({root:.6f}) = {f(root):.10f}")
Finding root of f(x) = x² + 3x - 10 Initial guesses: x0 = -4, x1 = 3 Iteration 1: x = 1.846154, f(x) = -0.939645 Iteration 2: x = 2.012658, f(x) = 0.051013 Iteration 3: x = 1.999364, f(x) = -0.001273 Iteration 4: x = 2.000000, f(x) = 0.000000 Converged after 4 iterations Root found: 2.000000 Verification: f(2.000000) = 0.0000000000
Visual Implementation with Plotting
Here's a complete implementation that visualizes the secant method process ?
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return x**2 + 3*x - 10
def secant_visual(x0, x1, tolerance=1e-3, max_iter=10):
# Create x values for plotting
x = np.linspace(-8, 6, 400)
y = f(x)
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'b-', linewidth=2, label='f(x) = x² + 3x - 10')
plt.axhline(y=0, color='k', linestyle='--', alpha=0.7)
plt.grid(True, alpha=0.3)
# Store points for visualization
points = []
for i in range(max_iter):
f0, f1 = f(x0), f(x1)
# Plot current secant line
x_secant = np.linspace(min(x0, x1) - 1, max(x0, x1) + 1, 100)
y_secant = f0 + (f1 - f0) * (x_secant - x0) / (x1 - x0)
plt.plot(x_secant, y_secant, 'r--', alpha=0.6)
# Calculate next point
x2 = x1 - f1 * (x1 - x0) / (f1 - f0)
# Mark points
plt.plot(x1, f1, 'ro', markersize=6)
plt.plot(x2, 0, 'go', markersize=6)
points.append((i+1, x2))
# Check convergence
if abs(x2 - x1) < tolerance:
plt.plot(x2, 0, 'go', markersize=10, label=f'Root ? {x2:.3f}')
break
x0, x1 = x1, x2
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Secant Method Visualization')
plt.legend()
plt.xlim(-8, 6)
plt.ylim(-15, 20)
return points
# Run visualization
points = secant_visual(-4, 3)
print("Iteration points:")
for iteration, x_val in points:
print(f"Iteration {iteration}: x = {x_val:.6f}")
Algorithm Steps
The secant method follows these steps ?
Initialize: Choose two starting points x? and x?
Calculate: x? = x? - f(x?) × [(x? - x?) / (f(x?) - f(x?))]
Check convergence: If |x? - x?|
Update: Set x? = x? and x? = x?
Repeat: Go to step 2
Advantages and Considerations
| Aspect | Secant Method | Newton-Raphson |
|---|---|---|
| Derivative Required | No | Yes |
| Convergence Rate | Superlinear (?1.618) | Quadratic (2.0) |
| Function Evaluations | 1 per iteration | 2 per iteration |
| Initial Points | 2 required | 1 required |
Conclusion
The secant method provides an excellent balance between simplicity and efficiency for root finding. It converges faster than bisection method while avoiding the derivative requirement of Newton-Raphson method, making it ideal for complex functions where derivatives are difficult to compute.
