Brent’s method is a hybrid root-finding algorithm combining the bisection method, the secant method, and inverse quadratic interpolation.

ex335.py

import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as optimize
def f(x):
    return 2*x - 1 + 2*np.cos(np.pi*x)
x = np.linspace(0.0,2.0,201)
y=f(x)
plt.plot(x,y,label='$2x - 1 + 2\\cos(\\pi x) = 0$')
x0 = optimize.brentq(f, 0.0, 1.0)
x1 = optimize.brentq(f, 1.0, 2.0)
print('x0 =',x0)
print('x1 =',x1)
plt.scatter(x0, f(x0),c='red')
plt.scatter(x1, f(x1),c='red')
plt.legend(loc=0)
plt.xlabel('$x$')
plt.ylabel('$f(x)$')
plt.grid(True)
plt.savefig('ex335.png', dpi=72)
plt.show()

Output:

x0 = 0.5
x1 = 1.2364844482415167