bisect.js

/**
 * [二分法](https://en.wikipedia.org/wiki/Bisection_method) 是一种求根方法,
 * 通过反复将区间一分为二来找到函数的根。
 *
 * 该函数返回一个数值近似值。
 *
 * @param {Function} func 输入函数
 * @param {number} start - 区间起点
 * @param {number} end - 区间终点
 * @param {number} maxIterations - 最大迭代次数
 * @param {number} errorTolerance - 误差容忍度
 * @returns {number} 估计的根值
 * @throws {TypeError} 参数 func 必须是一个函数
 *
 * @example
 * bisect(Math.cos,0,4,100,0.003); // => 1.572265625
 */
function bisect(func, start, end, maxIterations, errorTolerance) {
    if (typeof func !== "function") throw new TypeError("func 必须是一个函数");

    for (let i = 0; i < maxIterations; i++) {
        const output = (start + end) / 2;

        if (
            func(output) === 0 ||
            Math.abs((end - start) / 2) < errorTolerance
        ) {
            return output;
        }

        if (sign(func(output)) === sign(func(start))) {
            start = output;
        } else {
            end = output;
        }
    }

    throw new Error("超过最大迭代次数");
}

export default bisect;