deno.land / x / simplestatistic@v7.7.1 / src / bisect.js

نووسراو ببینە
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import sign from "./sign";
/** * [Bisection method](https://en.wikipedia.org/wiki/Bisection_method) is a root-finding * method that repeatedly bisects an interval to find the root. * * This function returns a numerical approximation to the exact value. * * @param {Function} func input function * @param {number} start - start of interval * @param {number} end - end of interval * @param {number} maxIterations - the maximum number of iterations * @param {number} errorTolerance - the error tolerance * @returns {number} estimated root value * @throws {TypeError} Argument func must be a function * * @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 must be a function");
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("maximum number of iterations exceeded");}
export default bisect;
simplestatistic

Version Info

Tagged at
2 years ago