Skip to content

_InvLimit

Description

_InvLimit moves from a starting point in one direction and finds the nearest place where a function changes sign, searching no further than a given limit. PolyInv uses it to locate the confidence limits of an inverse prediction; it returns “undefined” when there is no limit on that side.

Used by: PolyInv

Calls: _Bisect

Source Code

_InvLimit = LAMBDA(
    fn, // LAMBDA(x), elementwise in x
    x0, // starting point
    dir_, // -1 to search to the left, +1 to the right
    h, // rough scale of the distance to the crossing (e.g. the MOE)
    xfar, // furthest point to search
    LET(
        D, ABS(xfar - x0),
        near, MIN(50 * h, D),
        // distances from x0: 2000 evenly spaced out to near, then 400
        // geometrically spaced from near out to D
        dists, SORT(VSTACK(SEQUENCE(2000, 1, near / 2000, near / 2000), near * (D / near) ^ (SEQUENCE(400, 1, 1) / 400))),
        xs, x0 + dir_ * dists,
        s0, SIGN(INDEX(fn(x0), 1, 1)),
        k, XMATCH(TRUE, SIGN(fn(xs)) <> s0),
        IF(
            ISNA(k),
            "undefined",
            _Bisect(fn, IF(k = 1, x0, INDEX(xs, k - 1)), INDEX(xs, k))
        )
    )
);