Function bisect

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

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

Tuple!(T,"xTrue",T,"xFalse",R,"fTrue",R,"fFalse") bisect(F, T, R) (
  scope F f,
  bool delegate(T, R) predicate,
  T xTrue,
  T xFalse,
  R fTrue,
  R fFalse,
  T xTolerance,
  int maxIterations = 40
)
if (isFloatingPoint!T && isFloatingPoint!R);

Parameters

NameDescription
f The function.
predicate The predicate, which must take a point and the function value at that point and return a boolean.
xTrue A point where the predicate is true.
xFalse A point where the predicate is false.
fTrue (optional) The value of f at xTrue.
fFalse (optional) The value of f at xFalse.
xTolerance Success: When the absolute distance between xTrue and xFalse is less than this number, the function returns.
maxIterations Failure: When the algorithm has failed to produce a result after maxIterations bisections, an exception is thrown.

Returns

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

Example

// 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);