bisect

Use bisection to find the point where the given predicate goes from returning false to returning true.

  1. Tuple!(T, "xTrue", T, "xFalse", R, "fTrue", R, "fFalse") bisect(F f, bool delegate(T, R) predicate, T xTrue, T xFalse, T xTolerance, int maxIterations)
    Tuple!(T, "xTrue", T, "xFalse", R, "fTrue", R, "fFalse")
    bisect
    (
    F
    T
    R = ReturnType!F
    )
    (
    scope F f
    ,
    bool delegate
    (
    T
    ,
    R
    )
    predicate
    ,,,,
    int maxIterations = 40
    )
  2. Tuple!(T, "xTrue", T, "xFalse", R, "fTrue", R, "fFalse") bisect(F f, bool delegate(T, R) predicate, T xTrue, T xFalse, R fTrue, R fFalse, T xTolerance, int maxIterations)

Parameters

f F

The function.

predicate bool delegate
(
T
,
R
)

The predicate, which must take a point and the function value at that point and return a boolean.

xTrue T

A point where the predicate is true.

xFalse T

A point where the predicate is false.

xTolerance T

Success: When the absolute distance between xTrue and xFalse is less than this number, the function returns.

maxIterations int

Failure: When the algorithm has failed to produce a result after maxIterations bisections, an exception is thrown.

Return Value

Type: Tuple!(T, "xTrue", T, "xFalse", R, "fTrue", R, "fFalse")

A tuple containing values named xTrue, xFalse, fTrue, and fFalse, which satisfy

f(xTrue) == fTrue
f(xFalse) == fFalse
predicate(xTrue, fTrue) == true
predicate(xFalse, fFalse) == false
abs(xTrue-xFalse) <= xTolerance

Examples

// Find a root by bisection
auto r = bisect(
    (real x) { return x^^3; },
    (real x, real fx) { return fx < 0; },
    -1.0L, 1.5L, 1e-10L
    );

// Let's check if we got the right answer.
enum root = 0.0L;
assert (abs(r.xTrue - root) <= 1e-10);
assert (abs(r.xFalse - root) <= 1e-10);

assert (r.fTrue < 0);
assert (r.fFalse >= 0);
assert (abs(r.xTrue - r.xFalse) <= 1e-10);
assert (r.xNaN < 0);
assert (abs(r.xValid - r.xNan) <= 1e-6);

Meta