@tangent.to/opt 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +138 -0
- package/THIRD_PARTY_NOTICES.md +37 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +7 -0
- package/package.json +60 -0
- package/src/blas1.js +56 -0
- package/src/bounds.js +187 -0
- package/src/compat.js +148 -0
- package/src/evaluate.js +66 -0
- package/src/gradient.js +236 -0
- package/src/index.js +67 -0
- package/src/lbfgs.js +176 -0
- package/src/leastsq.js +418 -0
- package/src/linesearch.js +134 -0
- package/src/linsolve.js +99 -0
- package/src/minimize.js +97 -0
- package/src/neldermead.js +192 -0
- package/src/numdiff.js +112 -0
- package/src/scalar.js +623 -0
package/src/scalar.js
ADDED
|
@@ -0,0 +1,623 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scalar (univariate) minimization and root finding.
|
|
3
|
+
*
|
|
4
|
+
* minimizeScalar: Brent's minimization method (parabolic interpolation with
|
|
5
|
+
* golden-section safeguards) or plain golden-section search. When no 3-point
|
|
6
|
+
* bracket is supplied, a scipy-style downhill golden-ratio expansion
|
|
7
|
+
* (with parabolic extrapolation and a grow limit) brackets the minimum first.
|
|
8
|
+
*
|
|
9
|
+
* rootScalar: the Brent-Dekker method (inverse quadratic interpolation and
|
|
10
|
+
* secant steps with bisection safeguards) or plain bisection.
|
|
11
|
+
*
|
|
12
|
+
* Both are written from the standard algorithm descriptions and follow the
|
|
13
|
+
* package's declarative options-object style, returning
|
|
14
|
+
* {x, fx, iterations, fevals, converged}.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const GOLD = 1.618034; // golden ratio, downhill expansion factor
|
|
18
|
+
const CGOLD = 0.3819660112501051; // 2 - phi, golden-section fraction
|
|
19
|
+
const MIN_TOL = 1e-11; // absolute floor added to relative x tolerances
|
|
20
|
+
const VERY_SMALL = 1e-21; // denominator guard in parabolic extrapolation
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Bracket a minimum by golden-ratio downhill expansion from two points,
|
|
24
|
+
* with a parabolic extrapolation step and a grow limit (as in
|
|
25
|
+
* scipy.optimize.bracket).
|
|
26
|
+
*
|
|
27
|
+
* @param {Function} fn - Counted objective: (x) => number
|
|
28
|
+
* @param {number} xa0 - First starting point
|
|
29
|
+
* @param {number} xb0 - Second starting point
|
|
30
|
+
* @param {number} [growLimit=110] - Maximum grow factor per parabolic step
|
|
31
|
+
* @param {number} [maxIter=1000] - Maximum number of expansions
|
|
32
|
+
* @returns {Object} {xa, xb, xc, fa, fb, fc} with fb <= fa and fb <= fc
|
|
33
|
+
*/
|
|
34
|
+
function bracketMinimum(fn, xa0, xb0, growLimit = 110, maxIter = 1000) {
|
|
35
|
+
let xa = xa0;
|
|
36
|
+
let xb = xb0;
|
|
37
|
+
let fa = fn(xa);
|
|
38
|
+
let fb = fn(xb);
|
|
39
|
+
if (!Number.isFinite(fa) || !Number.isFinite(fb)) {
|
|
40
|
+
throw new Error(
|
|
41
|
+
`minimizeScalar: f is not finite at the initial bracket points ` +
|
|
42
|
+
`(f(${xa}) = ${fa}, f(${xb}) = ${fb})`,
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
if (fa < fb) {
|
|
46
|
+
// Ensure the downhill direction is from xa to xb.
|
|
47
|
+
let tmp = xa;
|
|
48
|
+
xa = xb;
|
|
49
|
+
xb = tmp;
|
|
50
|
+
tmp = fa;
|
|
51
|
+
fa = fb;
|
|
52
|
+
fb = tmp;
|
|
53
|
+
}
|
|
54
|
+
let xc = xb + GOLD * (xb - xa);
|
|
55
|
+
let fc = fn(xc);
|
|
56
|
+
if (fc !== fc) fc = Infinity;
|
|
57
|
+
|
|
58
|
+
let iteration = 0;
|
|
59
|
+
while (fc < fb) {
|
|
60
|
+
if (iteration >= maxIter) {
|
|
61
|
+
throw new Error(
|
|
62
|
+
`minimizeScalar: failed to bracket a minimum after ${maxIter} expansions from ` +
|
|
63
|
+
`[${xa0}, ${xb0}] (the function may be monotonic or unbounded below)`,
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
iteration++;
|
|
67
|
+
|
|
68
|
+
// Parabolic extrapolation through (xa, fa), (xb, fb), (xc, fc).
|
|
69
|
+
const tmp1 = (xb - xa) * (fb - fc);
|
|
70
|
+
const tmp2 = (xb - xc) * (fb - fa);
|
|
71
|
+
const val = tmp2 - tmp1;
|
|
72
|
+
const denom = Math.abs(val) < VERY_SMALL
|
|
73
|
+
? 2 * VERY_SMALL
|
|
74
|
+
: 2 * val;
|
|
75
|
+
let w = xb - ((xb - xc) * tmp2 - (xb - xa) * tmp1) / denom;
|
|
76
|
+
const wlim = xb + growLimit * (xc - xb);
|
|
77
|
+
let fw;
|
|
78
|
+
|
|
79
|
+
if ((w - xc) * (xb - w) > 0) {
|
|
80
|
+
// Parabolic point is between xb and xc.
|
|
81
|
+
fw = fn(w);
|
|
82
|
+
if (fw !== fw) fw = Infinity;
|
|
83
|
+
if (fw < fc) {
|
|
84
|
+
// Minimum between xb and xc.
|
|
85
|
+
xa = xb;
|
|
86
|
+
xb = w;
|
|
87
|
+
fa = fb;
|
|
88
|
+
fb = fw;
|
|
89
|
+
break;
|
|
90
|
+
} else if (fw > fb) {
|
|
91
|
+
// Minimum between xa and w.
|
|
92
|
+
xc = w;
|
|
93
|
+
fc = fw;
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
// Parabolic step did not help: default golden-ratio expansion.
|
|
97
|
+
w = xc + GOLD * (xc - xb);
|
|
98
|
+
fw = fn(w);
|
|
99
|
+
if (fw !== fw) fw = Infinity;
|
|
100
|
+
} else if ((w - wlim) * (wlim - xc) >= 0) {
|
|
101
|
+
// Parabolic point is at or beyond the grow limit: clamp to it.
|
|
102
|
+
w = wlim;
|
|
103
|
+
fw = fn(w);
|
|
104
|
+
if (fw !== fw) fw = Infinity;
|
|
105
|
+
} else if ((w - wlim) * (xc - w) > 0) {
|
|
106
|
+
// Parabolic point is between xc and the grow limit.
|
|
107
|
+
fw = fn(w);
|
|
108
|
+
if (fw !== fw) fw = Infinity;
|
|
109
|
+
if (fw < fc) {
|
|
110
|
+
xb = xc;
|
|
111
|
+
xc = w;
|
|
112
|
+
w = xc + GOLD * (xc - xb);
|
|
113
|
+
fb = fc;
|
|
114
|
+
fc = fw;
|
|
115
|
+
fw = fn(w);
|
|
116
|
+
if (fw !== fw) fw = Infinity;
|
|
117
|
+
}
|
|
118
|
+
} else {
|
|
119
|
+
// Reject the parabolic point: default golden-ratio expansion.
|
|
120
|
+
w = xc + GOLD * (xc - xb);
|
|
121
|
+
fw = fn(w);
|
|
122
|
+
if (fw !== fw) fw = Infinity;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
xa = xb;
|
|
126
|
+
xb = xc;
|
|
127
|
+
xc = w;
|
|
128
|
+
fa = fb;
|
|
129
|
+
fb = fc;
|
|
130
|
+
fc = fw;
|
|
131
|
+
|
|
132
|
+
if (!Number.isFinite(xc)) {
|
|
133
|
+
throw new Error(
|
|
134
|
+
`minimizeScalar: failed to bracket a minimum starting from [${xa0}, ${xb0}]; ` +
|
|
135
|
+
'the expansion diverged (the function may be monotonic or unbounded below)',
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const bracketed = (fb < fc && fb <= fa) || (fb < fa && fb <= fc);
|
|
141
|
+
if (!bracketed || !Number.isFinite(fb)) {
|
|
142
|
+
throw new Error(
|
|
143
|
+
`minimizeScalar: failed to bracket a minimum starting from [${xa0}, ${xb0}] ` +
|
|
144
|
+
'(the function may be monotonic)',
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
return { xa, xb, xc, fa, fb, fc };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Brent minimization on a bracketing triple (xa, xb, xc) with f(xb) known.
|
|
152
|
+
* Parabolic interpolation is attempted each step and rejected in favor of a
|
|
153
|
+
* golden-section step when unacceptable; steps are floored at
|
|
154
|
+
* tol1 = xTol * |x| + MIN_TOL.
|
|
155
|
+
*
|
|
156
|
+
* @param {Function} fn - Counted objective: (x) => number
|
|
157
|
+
* @param {number} xa - Bracket endpoint
|
|
158
|
+
* @param {number} xb - Interior point with the lowest known f
|
|
159
|
+
* @param {number} xc - Bracket endpoint
|
|
160
|
+
* @param {number} fxb - f(xb)
|
|
161
|
+
* @param {number} xTol - Relative tolerance on x
|
|
162
|
+
* @param {number} maxIter - Maximum iterations
|
|
163
|
+
* @returns {Object} {x, fx, iterations, converged}
|
|
164
|
+
*/
|
|
165
|
+
function brentMinimize(fn, xa, xb, xc, fxb, xTol, maxIter) {
|
|
166
|
+
let a = xa < xc ? xa : xc;
|
|
167
|
+
let b = xa < xc ? xc : xa;
|
|
168
|
+
let x = xb;
|
|
169
|
+
let w = xb;
|
|
170
|
+
let v = xb;
|
|
171
|
+
let fx = fxb;
|
|
172
|
+
let fw = fxb;
|
|
173
|
+
let fv = fxb;
|
|
174
|
+
let d = 0;
|
|
175
|
+
let e = 0;
|
|
176
|
+
let converged = false;
|
|
177
|
+
let iteration = 0;
|
|
178
|
+
|
|
179
|
+
for (; iteration < maxIter; ++iteration) {
|
|
180
|
+
const xm = 0.5 * (a + b);
|
|
181
|
+
const tol1 = xTol * Math.abs(x) + MIN_TOL;
|
|
182
|
+
const tol2 = 2 * tol1;
|
|
183
|
+
|
|
184
|
+
if (Math.abs(x - xm) <= tol2 - 0.5 * (b - a)) {
|
|
185
|
+
converged = true;
|
|
186
|
+
break;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
let useGolden = true;
|
|
190
|
+
if (Math.abs(e) > tol1) {
|
|
191
|
+
// Fit a parabola through (v, fv), (w, fw), (x, fx).
|
|
192
|
+
const r = (x - w) * (fx - fv);
|
|
193
|
+
let q = (x - v) * (fx - fw);
|
|
194
|
+
let p = (x - v) * q - (x - w) * r;
|
|
195
|
+
q = 2 * (q - r);
|
|
196
|
+
if (q > 0) p = -p;
|
|
197
|
+
q = Math.abs(q);
|
|
198
|
+
const etemp = e;
|
|
199
|
+
e = d;
|
|
200
|
+
// Accept the parabolic step only if it is finite, smaller than half the
|
|
201
|
+
// second-to-last step, and lands strictly inside the bracket.
|
|
202
|
+
if (
|
|
203
|
+
Number.isFinite(p) && Number.isFinite(q) && q !== 0 &&
|
|
204
|
+
Math.abs(p) < Math.abs(0.5 * q * etemp) &&
|
|
205
|
+
p > q * (a - x) && p < q * (b - x)
|
|
206
|
+
) {
|
|
207
|
+
d = p / q;
|
|
208
|
+
const u = x + d;
|
|
209
|
+
if (u - a < tol2 || b - u < tol2) {
|
|
210
|
+
d = xm - x >= 0 ? tol1 : -tol1;
|
|
211
|
+
}
|
|
212
|
+
useGolden = false;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (useGolden) {
|
|
216
|
+
e = x >= xm ? a - x : b - x;
|
|
217
|
+
d = CGOLD * e;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Never step by less than tol1.
|
|
221
|
+
const u = Math.abs(d) >= tol1 ? x + d : x + (d >= 0 ? tol1 : -tol1);
|
|
222
|
+
let fu = fn(u);
|
|
223
|
+
if (!Number.isFinite(fu)) fu = Infinity;
|
|
224
|
+
|
|
225
|
+
if (fu <= fx) {
|
|
226
|
+
if (u >= x) {
|
|
227
|
+
a = x;
|
|
228
|
+
} else {
|
|
229
|
+
b = x;
|
|
230
|
+
}
|
|
231
|
+
v = w;
|
|
232
|
+
fv = fw;
|
|
233
|
+
w = x;
|
|
234
|
+
fw = fx;
|
|
235
|
+
x = u;
|
|
236
|
+
fx = fu;
|
|
237
|
+
} else {
|
|
238
|
+
if (u < x) {
|
|
239
|
+
a = u;
|
|
240
|
+
} else {
|
|
241
|
+
b = u;
|
|
242
|
+
}
|
|
243
|
+
if (fu <= fw || w === x) {
|
|
244
|
+
v = w;
|
|
245
|
+
fv = fw;
|
|
246
|
+
w = u;
|
|
247
|
+
fw = fu;
|
|
248
|
+
} else if (fu <= fv || v === x || v === w) {
|
|
249
|
+
v = u;
|
|
250
|
+
fv = fu;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return { x, fx, iterations: iteration, converged };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Plain golden-section search on a bracketing triple (xa, xb, xc).
|
|
260
|
+
*
|
|
261
|
+
* @param {Function} fn - Counted objective: (x) => number
|
|
262
|
+
* @param {number} xa - Bracket endpoint
|
|
263
|
+
* @param {number} xb - Interior point with the lowest known f
|
|
264
|
+
* @param {number} xc - Bracket endpoint
|
|
265
|
+
* @param {number} fxb - f(xb)
|
|
266
|
+
* @param {number} xTol - Relative tolerance on x
|
|
267
|
+
* @param {number} maxIter - Maximum iterations
|
|
268
|
+
* @returns {Object} {x, fx, iterations, converged}
|
|
269
|
+
*/
|
|
270
|
+
function goldenMinimize(fn, xa, xb, xc, fxb, xTol, maxIter) {
|
|
271
|
+
const gr = 1 - CGOLD;
|
|
272
|
+
let x0 = xa < xc ? xa : xc;
|
|
273
|
+
let x3 = xa < xc ? xc : xa;
|
|
274
|
+
let x1;
|
|
275
|
+
let x2;
|
|
276
|
+
let f1;
|
|
277
|
+
let f2;
|
|
278
|
+
|
|
279
|
+
// Place the new interior point in the larger of the two sub-intervals.
|
|
280
|
+
if (Math.abs(x3 - xb) > Math.abs(xb - x0)) {
|
|
281
|
+
x1 = xb;
|
|
282
|
+
f1 = fxb;
|
|
283
|
+
x2 = xb + CGOLD * (x3 - xb);
|
|
284
|
+
f2 = fn(x2);
|
|
285
|
+
} else {
|
|
286
|
+
x2 = xb;
|
|
287
|
+
f2 = fxb;
|
|
288
|
+
x1 = xb - CGOLD * (xb - x0);
|
|
289
|
+
f1 = fn(x1);
|
|
290
|
+
}
|
|
291
|
+
if (!Number.isFinite(f1)) f1 = Infinity;
|
|
292
|
+
if (!Number.isFinite(f2)) f2 = Infinity;
|
|
293
|
+
|
|
294
|
+
let converged = false;
|
|
295
|
+
let iteration = 0;
|
|
296
|
+
for (; iteration < maxIter; ++iteration) {
|
|
297
|
+
if (Math.abs(x3 - x0) <= xTol * (Math.abs(x1) + Math.abs(x2)) + MIN_TOL) {
|
|
298
|
+
converged = true;
|
|
299
|
+
break;
|
|
300
|
+
}
|
|
301
|
+
if (f2 < f1) {
|
|
302
|
+
x0 = x1;
|
|
303
|
+
x1 = x2;
|
|
304
|
+
x2 = gr * x2 + CGOLD * x3;
|
|
305
|
+
f1 = f2;
|
|
306
|
+
f2 = fn(x2);
|
|
307
|
+
if (!Number.isFinite(f2)) f2 = Infinity;
|
|
308
|
+
} else {
|
|
309
|
+
x3 = x2;
|
|
310
|
+
x2 = x1;
|
|
311
|
+
x1 = gr * x1 + CGOLD * x0;
|
|
312
|
+
f2 = f1;
|
|
313
|
+
f1 = fn(x1);
|
|
314
|
+
if (!Number.isFinite(f1)) f1 = Infinity;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
if (f1 < f2) {
|
|
319
|
+
return { x: x1, fx: f1, iterations: iteration, converged };
|
|
320
|
+
}
|
|
321
|
+
return { x: x2, fx: f2, iterations: iteration, converged };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Minimize a univariate function.
|
|
326
|
+
*
|
|
327
|
+
* @param {Function} f - Objective: (x: number) => number
|
|
328
|
+
* @param {Object} [options]
|
|
329
|
+
* @param {string} [options.method='brent'] - 'brent' or 'golden'
|
|
330
|
+
* @param {Array<number>} [options.bracket=[0, 1]] - [a, b] to auto-bracket
|
|
331
|
+
* from, or a full bracketing triple [a, b, c] with f(b) <= f(a), f(b) <= f(c)
|
|
332
|
+
* @param {number} [options.xTol=1e-8] - Relative tolerance on x
|
|
333
|
+
* @param {number} [options.maxIter=500] - Maximum iterations
|
|
334
|
+
* @returns {Object} {x, fx, iterations, fevals, converged}
|
|
335
|
+
*/
|
|
336
|
+
export function minimizeScalar(f, options = {}) {
|
|
337
|
+
if (typeof f !== 'function') {
|
|
338
|
+
throw new Error('minimizeScalar: f must be a function');
|
|
339
|
+
}
|
|
340
|
+
const method = options.method !== undefined ? String(options.method).toLowerCase() : 'brent';
|
|
341
|
+
const xTol = options.xTol !== undefined ? options.xTol : 1e-8;
|
|
342
|
+
const maxIter = options.maxIter !== undefined ? options.maxIter : 500;
|
|
343
|
+
const bracket = options.bracket !== undefined ? options.bracket : [0, 1];
|
|
344
|
+
|
|
345
|
+
if (method !== 'brent' && method !== 'golden') {
|
|
346
|
+
throw new Error(
|
|
347
|
+
`minimizeScalar: unknown method '${options.method}'. Available: brent, golden`,
|
|
348
|
+
);
|
|
349
|
+
}
|
|
350
|
+
if (
|
|
351
|
+
!Array.isArray(bracket) || bracket.length < 2 || bracket.length > 3 ||
|
|
352
|
+
bracket.some((v) => typeof v !== 'number' || !Number.isFinite(v))
|
|
353
|
+
) {
|
|
354
|
+
throw new Error('minimizeScalar: options.bracket must be [a, b] or [a, b, c] finite numbers');
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
let fevals = 0;
|
|
358
|
+
const fn = (t) => {
|
|
359
|
+
fevals++;
|
|
360
|
+
return f(t);
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
let xa;
|
|
364
|
+
let xb;
|
|
365
|
+
let xc;
|
|
366
|
+
let fb;
|
|
367
|
+
if (bracket.length === 3) {
|
|
368
|
+
xa = bracket[0];
|
|
369
|
+
xb = bracket[1];
|
|
370
|
+
xc = bracket[2];
|
|
371
|
+
if (!((xa < xb && xb < xc) || (xa > xb && xb > xc))) {
|
|
372
|
+
throw new Error(
|
|
373
|
+
`minimizeScalar: bracket [${xa}, ${xb}, ${xc}] is not monotonically ordered`,
|
|
374
|
+
);
|
|
375
|
+
}
|
|
376
|
+
const fa = fn(xa);
|
|
377
|
+
fb = fn(xb);
|
|
378
|
+
const fc = fn(xc);
|
|
379
|
+
if (!Number.isFinite(fb) || !(fb <= fa) || !(fb <= fc)) {
|
|
380
|
+
throw new Error(
|
|
381
|
+
`minimizeScalar: bracket [${xa}, ${xb}, ${xc}] does not bracket a minimum ` +
|
|
382
|
+
`(f values: ${fa}, ${fb}, ${fc}); f(b) must be finite and <= both f(a) and f(c)`,
|
|
383
|
+
);
|
|
384
|
+
}
|
|
385
|
+
} else {
|
|
386
|
+
const br = bracketMinimum(fn, bracket[0], bracket[1]);
|
|
387
|
+
xa = br.xa;
|
|
388
|
+
xb = br.xb;
|
|
389
|
+
xc = br.xc;
|
|
390
|
+
fb = br.fb;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
const result = method === 'brent'
|
|
394
|
+
? brentMinimize(fn, xa, xb, xc, fb, xTol, maxIter)
|
|
395
|
+
: goldenMinimize(fn, xa, xb, xc, fb, xTol, maxIter);
|
|
396
|
+
result.nfev = fevals;
|
|
397
|
+
result.fevals = fevals; // deprecated alias for nfev
|
|
398
|
+
result.success = result.converged;
|
|
399
|
+
return result;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Brent-Dekker root finding: inverse quadratic interpolation and secant
|
|
404
|
+
* steps, safeguarded by bisection. fa and fb must have opposite signs.
|
|
405
|
+
*
|
|
406
|
+
* @param {Function} fn - Counted function: (x) => number
|
|
407
|
+
* @param {number} a0 - Bracket endpoint
|
|
408
|
+
* @param {number} b0 - Bracket endpoint
|
|
409
|
+
* @param {number} fa0 - f(a0)
|
|
410
|
+
* @param {number} fb0 - f(b0)
|
|
411
|
+
* @param {number} xTol - Absolute tolerance on x
|
|
412
|
+
* @param {number} rTol - Relative tolerance on x
|
|
413
|
+
* @param {number} maxIter - Maximum iterations
|
|
414
|
+
* @returns {Object} {x, fx, iterations, converged}
|
|
415
|
+
*/
|
|
416
|
+
function brentRoot(fn, a0, b0, fa0, fb0, xTol, rTol, maxIter) {
|
|
417
|
+
let a = a0;
|
|
418
|
+
let b = b0;
|
|
419
|
+
let fa = fa0;
|
|
420
|
+
let fb = fb0;
|
|
421
|
+
|
|
422
|
+
// Keep b as the better (smaller |f|) estimate.
|
|
423
|
+
if (Math.abs(fa) < Math.abs(fb)) {
|
|
424
|
+
let tmp = a;
|
|
425
|
+
a = b;
|
|
426
|
+
b = tmp;
|
|
427
|
+
tmp = fa;
|
|
428
|
+
fa = fb;
|
|
429
|
+
fb = tmp;
|
|
430
|
+
}
|
|
431
|
+
let c = a;
|
|
432
|
+
let fc = fa;
|
|
433
|
+
let d = c;
|
|
434
|
+
let mflag = true;
|
|
435
|
+
let converged = false;
|
|
436
|
+
let iteration = 0;
|
|
437
|
+
|
|
438
|
+
for (; iteration < maxIter; ++iteration) {
|
|
439
|
+
const tol = 2 * rTol * Math.abs(b) + xTol;
|
|
440
|
+
if (fb === 0 || Math.abs(b - a) <= tol) {
|
|
441
|
+
converged = true;
|
|
442
|
+
break;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
let s;
|
|
446
|
+
if (fa !== fc && fb !== fc) {
|
|
447
|
+
// Inverse quadratic interpolation.
|
|
448
|
+
s = (a * fb * fc) / ((fa - fb) * (fa - fc)) +
|
|
449
|
+
(b * fa * fc) / ((fb - fa) * (fb - fc)) +
|
|
450
|
+
(c * fa * fb) / ((fc - fa) * (fc - fb));
|
|
451
|
+
} else {
|
|
452
|
+
// Secant step.
|
|
453
|
+
s = b - fb * (b - a) / (fb - fa);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// Safeguards: fall back to bisection when the interpolated step is
|
|
457
|
+
// suspect (outside [(3a + b) / 4, b], or not shrinking fast enough).
|
|
458
|
+
const lo = (3 * a + b) / 4;
|
|
459
|
+
const useBisection = !Number.isFinite(s) ||
|
|
460
|
+
!((s > lo && s < b) || (s < lo && s > b)) ||
|
|
461
|
+
(mflag && Math.abs(s - b) >= Math.abs(b - c) / 2) ||
|
|
462
|
+
(!mflag && Math.abs(s - b) >= Math.abs(c - d) / 2) ||
|
|
463
|
+
(mflag && Math.abs(b - c) < tol) ||
|
|
464
|
+
(!mflag && Math.abs(c - d) < tol);
|
|
465
|
+
if (useBisection) {
|
|
466
|
+
s = 0.5 * (a + b);
|
|
467
|
+
mflag = true;
|
|
468
|
+
} else {
|
|
469
|
+
mflag = false;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
let fs = fn(s);
|
|
473
|
+
if (!Number.isFinite(fs)) {
|
|
474
|
+
// Non-finite interpolated value: fall back to the bisection midpoint.
|
|
475
|
+
const mid = 0.5 * (a + b);
|
|
476
|
+
if (s !== mid) {
|
|
477
|
+
s = mid;
|
|
478
|
+
mflag = true;
|
|
479
|
+
fs = fn(s);
|
|
480
|
+
}
|
|
481
|
+
if (!Number.isFinite(fs)) {
|
|
482
|
+
throw new Error(`rootScalar: f returned a non-finite value (${fs}) at x = ${s}`);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
d = c;
|
|
487
|
+
c = b;
|
|
488
|
+
fc = fb;
|
|
489
|
+
if ((fa > 0) !== (fs > 0)) {
|
|
490
|
+
b = s;
|
|
491
|
+
fb = fs;
|
|
492
|
+
} else {
|
|
493
|
+
a = s;
|
|
494
|
+
fa = fs;
|
|
495
|
+
}
|
|
496
|
+
if (Math.abs(fa) < Math.abs(fb)) {
|
|
497
|
+
let tmp = a;
|
|
498
|
+
a = b;
|
|
499
|
+
b = tmp;
|
|
500
|
+
tmp = fa;
|
|
501
|
+
fa = fb;
|
|
502
|
+
fb = tmp;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
return { x: b, fx: fb, iterations: iteration, converged };
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* Plain bisection root finding. fa and fb must have opposite signs.
|
|
511
|
+
*
|
|
512
|
+
* @param {Function} fn - Counted function: (x) => number
|
|
513
|
+
* @param {number} a0 - Bracket endpoint
|
|
514
|
+
* @param {number} b0 - Bracket endpoint
|
|
515
|
+
* @param {number} fa0 - f(a0)
|
|
516
|
+
* @param {number} xTol - Absolute tolerance on x
|
|
517
|
+
* @param {number} rTol - Relative tolerance on x
|
|
518
|
+
* @param {number} maxIter - Maximum iterations
|
|
519
|
+
* @returns {Object} {x, fx, iterations, converged}
|
|
520
|
+
*/
|
|
521
|
+
function bisectRoot(fn, a0, b0, fa0, xTol, rTol, maxIter) {
|
|
522
|
+
let a = a0;
|
|
523
|
+
let b = b0;
|
|
524
|
+
let fa = fa0;
|
|
525
|
+
let x = 0.5 * (a + b);
|
|
526
|
+
let fx = NaN;
|
|
527
|
+
let converged = false;
|
|
528
|
+
let iteration = 0;
|
|
529
|
+
|
|
530
|
+
for (; iteration < maxIter; ++iteration) {
|
|
531
|
+
x = 0.5 * (a + b);
|
|
532
|
+
fx = fn(x);
|
|
533
|
+
if (!Number.isFinite(fx)) {
|
|
534
|
+
throw new Error(`rootScalar: f returned a non-finite value (${fx}) at x = ${x}`);
|
|
535
|
+
}
|
|
536
|
+
const tol = 2 * rTol * Math.abs(x) + xTol;
|
|
537
|
+
if (fx === 0 || 0.5 * Math.abs(b - a) <= tol) {
|
|
538
|
+
converged = true;
|
|
539
|
+
break;
|
|
540
|
+
}
|
|
541
|
+
if ((fa > 0) !== (fx > 0)) {
|
|
542
|
+
b = x;
|
|
543
|
+
} else {
|
|
544
|
+
a = x;
|
|
545
|
+
fa = fx;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
return { x, fx, iterations: iteration, converged };
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/**
|
|
553
|
+
* Find a root of a univariate function inside a sign-changing bracket.
|
|
554
|
+
*
|
|
555
|
+
* @param {Function} f - Function: (x: number) => number
|
|
556
|
+
* @param {Object} [options]
|
|
557
|
+
* @param {string} [options.method='brent'] - 'brent' or 'bisect'
|
|
558
|
+
* @param {Array<number>} options.bracket - [a, b] with f(a) and f(b) of
|
|
559
|
+
* opposite signs (required)
|
|
560
|
+
* @param {number} [options.xTol=1e-12] - Absolute tolerance on x
|
|
561
|
+
* @param {number} [options.rTol=4 * Number.EPSILON] - Relative tolerance on x
|
|
562
|
+
* @param {number} [options.maxIter=100] - Maximum iterations
|
|
563
|
+
* @returns {Object} {x, fx, iterations, fevals, converged}
|
|
564
|
+
*/
|
|
565
|
+
export function rootScalar(f, options = {}) {
|
|
566
|
+
if (typeof f !== 'function') {
|
|
567
|
+
throw new Error('rootScalar: f must be a function');
|
|
568
|
+
}
|
|
569
|
+
const method = options.method !== undefined ? String(options.method).toLowerCase() : 'brent';
|
|
570
|
+
const xTol = options.xTol !== undefined ? options.xTol : 1e-12;
|
|
571
|
+
const rTol = options.rTol !== undefined ? options.rTol : 4 * Number.EPSILON;
|
|
572
|
+
const maxIter = options.maxIter !== undefined ? options.maxIter : 100;
|
|
573
|
+
const bracket = options.bracket;
|
|
574
|
+
|
|
575
|
+
if (method !== 'brent' && method !== 'bisect') {
|
|
576
|
+
throw new Error(
|
|
577
|
+
`rootScalar: unknown method '${options.method}'. Available: brent, bisect`,
|
|
578
|
+
);
|
|
579
|
+
}
|
|
580
|
+
if (
|
|
581
|
+
!Array.isArray(bracket) || bracket.length !== 2 ||
|
|
582
|
+
bracket.some((v) => typeof v !== 'number' || !Number.isFinite(v))
|
|
583
|
+
) {
|
|
584
|
+
throw new Error('rootScalar: options.bracket = [a, b] (finite numbers) is required');
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
let fevals = 0;
|
|
588
|
+
const fn = (t) => {
|
|
589
|
+
fevals++;
|
|
590
|
+
return f(t);
|
|
591
|
+
};
|
|
592
|
+
|
|
593
|
+
const a = bracket[0];
|
|
594
|
+
const b = bracket[1];
|
|
595
|
+
const fa = fn(a);
|
|
596
|
+
const fb = fn(b);
|
|
597
|
+
if (!Number.isFinite(fa) || !Number.isFinite(fb)) {
|
|
598
|
+
throw new Error(
|
|
599
|
+
`rootScalar: f is not finite at the bracket endpoints ` +
|
|
600
|
+
`(f(${a}) = ${fa}, f(${b}) = ${fb})`,
|
|
601
|
+
);
|
|
602
|
+
}
|
|
603
|
+
if (fa === 0) {
|
|
604
|
+
return { x: a, fx: fa, iterations: 0, nfev: fevals, fevals, converged: true, success: true };
|
|
605
|
+
}
|
|
606
|
+
if (fb === 0) {
|
|
607
|
+
return { x: b, fx: fb, iterations: 0, nfev: fevals, fevals, converged: true, success: true };
|
|
608
|
+
}
|
|
609
|
+
if ((fa > 0) === (fb > 0)) {
|
|
610
|
+
throw new Error(
|
|
611
|
+
`rootScalar: f(a) and f(b) must have opposite signs, but ` +
|
|
612
|
+
`f(${a}) = ${fa} and f(${b}) = ${fb}; a sign change across the bracket is required`,
|
|
613
|
+
);
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
const result = method === 'brent'
|
|
617
|
+
? brentRoot(fn, a, b, fa, fb, xTol, rTol, maxIter)
|
|
618
|
+
: bisectRoot(fn, a, b, fa, xTol, rTol, maxIter);
|
|
619
|
+
result.nfev = fevals;
|
|
620
|
+
result.fevals = fevals; // deprecated alias for nfev
|
|
621
|
+
result.success = result.converged;
|
|
622
|
+
return result;
|
|
623
|
+
}
|