brentq

Syntax

brentq(f, a, b, [xtol], [rtol], [maxIter], [funcDataParam])

Arguments

f is a function which returns a number. The function fmust be continuous in [a,b], and f(a) and f(b) must have opposite signs.

a is a numeric scalar that specifies the left boundary of the bracketing interval [a,b].

b is a numeric scalar that specifies the right boundary of the bracketing interval [a,b].

xtol / rtol (optional) are numeric scalars that specify the precision of the computed root. The computed root x0 satisfies |x-x0| <= (xtol + rtol* |x0|), where x is the exact root. The default value of xtol is 2e-12, and the default value of rtol is 4 times the machine epsilon in double precision.

maxIter (optional) is an integer indicating the maximum iterations. The default value is 100.

funcDataParam (optional) is a vector containing extra arguments for the function f.

Details

Find a root x0 of a function f in a bracketing interval [a, b] using Brent's method.

Return value: A vector res of length 2.

  • res[0] is a STRING scalar indicating the convergence information, which can be:

    • CONVERGED: converged.

    • SIGNERR: sign error.

    • CONVERR: convergence error.

  • res[1] is a number representing the root of f between a and b.

Examples

Find the root of f(x) = x^2 - 1 in [-2,0] and [0,2].

def f(x) {
    return (pow(x, 2) - 1)
}

root1 = brentq(f, -2, 0)
root2 = brentq(f, 0, 2)
print("root1 : ", root1)
print("root2 : ", root2)

// output
root1 :
("CONVERGED",-1)
root2 :
("CONVERGED",1)

Find the root of f(x,b) with extra arguments in the [0,2].

def f(x, b) {
    return (pow(x, 2) - b)
}
root = brentq(f, 0, 2, 2e-12, 1e-9, 100, [2])
print("root : ", root)

// output
root : 
("CONVERGED",1.414213562373136)