-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
49 lines (48 loc) · 1.36 KB
/
index.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
46
47
48
49
/* Copyright 2016 Paul Brewer, Economic & Financial Technology COnsulting LLC <drpaulbrewer@eaftc.com> */
/* License: MIT https://opensource.org/licenses/MIT */
module.exports = function (l, h, tol, f) {
'use strict';
// returns a two element array giving an inclusive range of zero values of f
// requires strictly everywhere non-descending function f
// use with caution: this code assumes but does and can not check that f is everywhere non-descending
var right = h,
left = l,
intflag = (tol >= 1);
var fl = f(l),
fh = f(h);
if ((fl === 0) && (fh === 0)) return [l, h];
if (fh < fl) throw new Error("findZeroRange: requires non-descending function");
if (fl > 0) return [];
if (fh < 0) return [];
var zleft, zright, mid;
zright = left;
if (fh===0){
zright = right;
} else {
while ((right - zright) > tol) {
mid = (right + zright) / 2;
if (intflag) mid = Math.floor(mid);
if (f(mid) > 0)
right = mid;
else
zright = mid;
}
if (f(zright) < 0)
return [zright];
}
if (fl===0){
zleft = l;
} else {
zleft = zright;
while ((zleft - left) > tol) {
mid = (left + zleft) / 2;
if (intflag) mid = Math.floor(mid);
if (f(mid) < 0)
left = mid;
else
zleft = mid;
}
}
if (zleft === zright) return [zright];
return [zleft, zright];
};