0
0
SciPydata~5 mins

Root finding (root, brentq) in SciPy

Choose your learning style9 modes available
Introduction

Root finding helps us find where a function equals zero. This is useful to solve real problems like finding break-even points or crossing points.

You want to find the exact point where a cost equals revenue.
You need to solve equations that cannot be rearranged easily.
You want to find the zero crossing of a sensor signal.
You want to find the temperature where a reaction rate becomes zero.
You want to find the root of a polynomial or any continuous function.
Syntax
SciPy
from scipy.optimize import root, brentq

# root usage
def func(x):
    return x**2 - 4

sol = root(func, x0=1)  # x0 is initial guess

# brentq usage
def func2(x):
    return x**3 - x - 2

root_value = brentq(func2, 1, 2)  # a and b bracket the root

root needs an initial guess and can solve many types of equations.

brentq needs an interval where the function changes sign (one positive, one negative).

Examples
Find root of x² - 9 starting from guess 2. The root is 3 or -3, root returns one close to guess.
SciPy
from scipy.optimize import root

def f(x):
    return x**2 - 9

solution = root(f, x0=2)
print(solution.x)
Find root of x³ - 1 between 0 and 2. The root is 1.
SciPy
from scipy.optimize import brentq

def f(x):
    return x**3 - 1

root_val = brentq(f, 0, 2)
print(root_val)
Sample Program

This program finds roots of two functions. The first uses root with a guess. The second uses brentq with an interval where the function changes sign.

SciPy
from scipy.optimize import root, brentq

def func1(x):
    return x**2 - 16

def func2(x):
    return x**3 - 2*x - 5

# Using root with initial guess
sol1 = root(func1, x0=1)

# Using brentq with interval
sol2 = brentq(func2, 2, 3)

print(f"Root found by root: {sol1.x[0]:.4f}")
print(f"Root found by brentq: {sol2:.4f}")
OutputSuccess
Important Notes

Always check if the function changes sign in the interval when using brentq.

root can find complex roots but needs a good initial guess.

Both methods return numerical approximations, not exact answers.

Summary

Root finding helps locate where a function equals zero.

root uses an initial guess and is flexible.

brentq needs an interval with a sign change and is very reliable.