-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumeric.js
53 lines (51 loc) · 1.67 KB
/
numeric.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
50
51
52
53
function numeric_bsearch_decent(f, init, target, eps, max_tries=50) {
/**
* f(x) goes down with x goes up...
*/
let bottom = -Infinity;
let upper = Infinity;
let x = init;
for (let epoch = 1; ; epoch++) {
let y = f(x);
// adjust beta based on result
if (y > target) {
// f(x) too big, x is too small
bottom = x; // move up the bounds
if (upper === Infinity) x *= 2;
else { x = (x + upper) / 2; }
} else {
// f(x) too small, x is too big
upper = x;
if (bottom === -Infinity) x /= 2;
else { x = (x + bottom) / 2; }
}
// stopping conditions: too many tries or got a good precision
if (Math.abs(y - target) < eps || epoch >= max_tries) return x;
}
}
function numeric_bsearch(f, init, target, eps, max_tries=50) {
/**
* f(x) goes up with x goes up...
*/
let bottom = -Infinity;
let upper = Infinity;
let x = init;
for (let epoch = 1; ; epoch++) {
let y = f(x);
// adjust beta based on result
if (y < target) {
// f(x) too small, x is too small
bottom = x; // move up the bounds
if (upper === Infinity) x *= 2;
else { x = (x + upper) / 2; }
} else {
// f(x) too big, x is too big
upper = x;
if (bottom === -Infinity) x /= 2;
else { x = (x + bottom) / 2; }
}
// stopping conditions: too many tries or got a good precision
if (Math.abs(y - target) < eps || epoch >= max_tries) return x;
}
}
export { numeric_bsearch, numeric_bsearch_decent };