@ac-kit/math-analysis 0.1.11 → 0.3.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.
Files changed (111) hide show
  1. package/CHANGELOG.md +155 -0
  2. package/README.md +167 -10
  3. package/dist/differentiation/finite-difference.d.ts +41 -0
  4. package/dist/differentiation/finite-difference.d.ts.map +1 -0
  5. package/dist/differentiation/finite-difference.js +53 -0
  6. package/dist/differentiation/finite-difference.js.map +1 -0
  7. package/dist/differentiation/gradient.d.ts +73 -0
  8. package/dist/differentiation/gradient.d.ts.map +1 -0
  9. package/dist/differentiation/gradient.js +167 -0
  10. package/dist/differentiation/gradient.js.map +1 -0
  11. package/dist/index.d.ts +20 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +20 -0
  14. package/dist/index.js.map +1 -1
  15. package/dist/interpolation/barycentric-interpolator.d.ts +29 -0
  16. package/dist/interpolation/barycentric-interpolator.d.ts.map +1 -0
  17. package/dist/interpolation/barycentric-interpolator.js +94 -0
  18. package/dist/interpolation/barycentric-interpolator.js.map +1 -0
  19. package/dist/legendre/_legendre-kernel.d.ts +22 -0
  20. package/dist/legendre/_legendre-kernel.d.ts.map +1 -0
  21. package/dist/legendre/_legendre-kernel.js +232 -0
  22. package/dist/legendre/_legendre-kernel.js.map +1 -0
  23. package/dist/legendre/legendre-fully-normalized.d.ts +52 -0
  24. package/dist/legendre/legendre-fully-normalized.d.ts.map +1 -0
  25. package/dist/legendre/legendre-fully-normalized.js +62 -0
  26. package/dist/legendre/legendre-fully-normalized.js.map +1 -0
  27. package/dist/legendre/legendre-index.d.ts +27 -0
  28. package/dist/legendre/legendre-index.d.ts.map +1 -0
  29. package/dist/legendre/legendre-index.js +31 -0
  30. package/dist/legendre/legendre-index.js.map +1 -0
  31. package/dist/legendre/legendre-schmidt.d.ts +37 -0
  32. package/dist/legendre/legendre-schmidt.d.ts.map +1 -0
  33. package/dist/legendre/legendre-schmidt.js +47 -0
  34. package/dist/legendre/legendre-schmidt.js.map +1 -0
  35. package/dist/ode/runge-kutta4.d.ts +46 -0
  36. package/dist/ode/runge-kutta4.d.ts.map +1 -0
  37. package/dist/ode/runge-kutta4.js +85 -0
  38. package/dist/ode/runge-kutta4.js.map +1 -0
  39. package/dist/optimize/_more-thuente.d.ts +95 -0
  40. package/dist/optimize/_more-thuente.d.ts.map +1 -0
  41. package/dist/optimize/_more-thuente.js +333 -0
  42. package/dist/optimize/_more-thuente.js.map +1 -0
  43. package/dist/optimize/_wolfe-line-search.d.ts +85 -0
  44. package/dist/optimize/_wolfe-line-search.d.ts.map +1 -0
  45. package/dist/optimize/_wolfe-line-search.js +193 -0
  46. package/dist/optimize/_wolfe-line-search.js.map +1 -0
  47. package/dist/optimize/bfgs.d.ts +262 -0
  48. package/dist/optimize/bfgs.d.ts.map +1 -0
  49. package/dist/optimize/bfgs.js +418 -0
  50. package/dist/optimize/bfgs.js.map +1 -0
  51. package/dist/optimize/lbfgs.d.ts +199 -0
  52. package/dist/optimize/lbfgs.d.ts.map +1 -0
  53. package/dist/optimize/lbfgs.js +383 -0
  54. package/dist/optimize/lbfgs.js.map +1 -0
  55. package/dist/optimize/levenberg-marquardt.d.ts +78 -0
  56. package/dist/optimize/levenberg-marquardt.d.ts.map +1 -0
  57. package/dist/optimize/levenberg-marquardt.js +204 -0
  58. package/dist/optimize/levenberg-marquardt.js.map +1 -0
  59. package/dist/optimize/nelder-mead.d.ts +68 -0
  60. package/dist/optimize/nelder-mead.d.ts.map +1 -0
  61. package/dist/optimize/nelder-mead.js +198 -0
  62. package/dist/optimize/nelder-mead.js.map +1 -0
  63. package/dist/quadrature/adaptive-quadrature.d.ts +53 -0
  64. package/dist/quadrature/adaptive-quadrature.d.ts.map +1 -0
  65. package/dist/quadrature/adaptive-quadrature.js +175 -0
  66. package/dist/quadrature/adaptive-quadrature.js.map +1 -0
  67. package/dist/quadrature/gauss-legendre.d.ts +27 -0
  68. package/dist/quadrature/gauss-legendre.d.ts.map +1 -0
  69. package/dist/quadrature/gauss-legendre.js +111 -0
  70. package/dist/quadrature/gauss-legendre.js.map +1 -0
  71. package/dist/quadrature/simpsons-rule.d.ts +27 -0
  72. package/dist/quadrature/simpsons-rule.d.ts.map +1 -0
  73. package/dist/quadrature/simpsons-rule.js +44 -0
  74. package/dist/quadrature/simpsons-rule.js.map +1 -0
  75. package/dist/roots/_brent-kernel.d.ts +38 -0
  76. package/dist/roots/_brent-kernel.d.ts.map +1 -0
  77. package/dist/roots/_brent-kernel.js +112 -0
  78. package/dist/roots/_brent-kernel.js.map +1 -0
  79. package/dist/roots/_grown.d.ts +7 -0
  80. package/dist/roots/_grown.d.ts.map +1 -0
  81. package/dist/roots/_grown.js +19 -0
  82. package/dist/roots/_grown.js.map +1 -0
  83. package/dist/roots/_level-search.d.ts +154 -0
  84. package/dist/roots/_level-search.d.ts.map +1 -0
  85. package/dist/roots/_level-search.js +556 -0
  86. package/dist/roots/_level-search.js.map +1 -0
  87. package/dist/roots/brent.d.ts +59 -0
  88. package/dist/roots/brent.d.ts.map +1 -0
  89. package/dist/roots/brent.js +115 -0
  90. package/dist/roots/brent.js.map +1 -0
  91. package/dist/roots/find-level-bands.d.ts +148 -0
  92. package/dist/roots/find-level-bands.d.ts.map +1 -0
  93. package/dist/roots/find-level-bands.js +351 -0
  94. package/dist/roots/find-level-bands.js.map +1 -0
  95. package/dist/roots/find-level-crossings.d.ts +143 -0
  96. package/dist/roots/find-level-crossings.d.ts.map +1 -0
  97. package/dist/roots/find-level-crossings.js +162 -0
  98. package/dist/roots/find-level-crossings.js.map +1 -0
  99. package/dist/roots/level-search-options.d.ts +56 -0
  100. package/dist/roots/level-search-options.d.ts.map +1 -0
  101. package/dist/roots/level-search-options.js +2 -0
  102. package/dist/roots/level-search-options.js.map +1 -0
  103. package/dist/roots/newton-raphson.d.ts +31 -0
  104. package/dist/roots/newton-raphson.d.ts.map +1 -0
  105. package/dist/roots/newton-raphson.js +69 -0
  106. package/dist/roots/newton-raphson.js.map +1 -0
  107. package/dist/series/sum-series.d.ts +43 -0
  108. package/dist/series/sum-series.d.ts.map +1 -0
  109. package/dist/series/sum-series.js +70 -0
  110. package/dist/series/sum-series.js.map +1 -0
  111. package/package.json +8 -5
package/CHANGELOG.md CHANGED
@@ -1,5 +1,160 @@
1
1
  # @ac-kit/math-analysis
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 5c203e7: Minimisation by BFGS. Depends on `@ac-kit/math-linear` (its dense `Matrix`).
8
+
9
+ - `BfgsMinimizer(dimension, options)` minimises a smooth function of several
10
+ variables given as one objective `(point, gradient) => value` that writes
11
+ its gradient: BFGS quasi-Newton steps along `−H·∇f`, each line searched by
12
+ Moré and Thuente's algorithm (MINPACK-2 `dcsrch`) to the strong Wolfe
13
+ conditions (`sufficientDecrease`, `curvature`), with Hager and Zhang's
14
+ approximate Wolfe acceptance where `f` no longer resolves a decrease.
15
+ `minimize(out, objective, start, { initialInverseHessian, budget, signal })`
16
+ writes the point reached and leaves `value`, `gradient`, `inverseHessian`
17
+ (a `Matrix`), `iterations`, `evaluations`, `status` (`"gradient"`,
18
+ `"value"`, `"step"`, `"max-iterations"`, `"line-search"`) and `converged`;
19
+ it allocates nothing after the constructor. A non-finite trial value halves
20
+ the step (a domain boundary is never crossed); a non-descent direction or a
21
+ failed search resets to the steepest descent. `RangeError` for bad options,
22
+ lengths or a non-finite start; the signal's reason and the budget's error
23
+ (one unit per evaluation) propagate. O(n²) per step.
24
+ - `bfgs(objective, start, options)`: the one-shot form, returning a result
25
+ object.
26
+ - 5c203e7: - `gradient(out, f, point)`, `jacobian(out, f, point)` and
27
+ `hessian(out, f, point)`: multivariate derivatives by central differences
28
+ into a `Float64Array` or a `@ac-kit/math-linear` `Matrix`.
29
+ - `levenbergMarquardt(residuals, start, { residualCount, jacobian, … })`:
30
+ non-linear least squares by damped QR steps (Moré's scaling, Nielsen's
31
+ damping update), with a finite-difference Jacobian when none is given;
32
+ returns the point, residuals, cost, status and whether it converged.
33
+ - 5c203e7: Associated Legendre functions, with their colatitude derivatives, into a
34
+ caller's triangular `Float64Array` table:
35
+ `legendreSchmidt(out, maxDegree, colatitude, derivativesOut?)` writes the
36
+ Schmidt semi-normalised `Pₙᵐ(cos θ)` of geomagnetism (WMM, IGRF) and
37
+ `legendreFullyNormalized(out, maxDegree, colatitude, derivativesOut?)` the
38
+ fully normalised `P̄ₙₘ(cos θ)` of geodesy (EGM2008), both without the
39
+ Condon–Shortley phase, every degree and order up to `maxDegree`;
40
+ `legendreIndex(degree, order)` and `legendreTableLength(maxDegree)` address the
41
+ table. Finite and accurate at every colatitude to degree 2190 and beyond (to
42
+ 2700; Holmes–Featherstone's modified forward column method), values below the
43
+ binary64 range underflowing rather than spoiling their column, derivatives
44
+ exact at the poles. O(maxDegree²), no allocation once the package's table of
45
+ integer roots has grown to the degree. `RangeError` for a degree that is not a
46
+ non-negative integer, a table that is too short, overlapping tables or a
47
+ colatitude outside `[0, π]`; `NaN` fills both tables.
48
+ - 5c203e7: - Quadrature: `simpsonsRule(f, lower, upper, intervals)`,
49
+ `gaussLegendre(f, lower, upper, nodes)` (exact to degree `2n − 1`, up to 1024
50
+ nodes) and `adaptiveQuadrature(f, lower, upper, options)` (adaptive
51
+ Gauss–Kronrod 7–15, returning the value, an error estimate, the evaluations
52
+ and whether the tolerances were met).
53
+ - `newtonRaphson(f, df, x0, options)`: throws a `RangeError` on a vanishing
54
+ derivative or divergence, a `ConvergenceError` when `maxIterations` runs out.
55
+ - `finiteDifference(f, x, { scheme, step })`: central, forward or backward,
56
+ the step rounded to representable points.
57
+ - `rungeKutta4(f, y0, tSpan, steps)`: classical RK4 over systems
58
+ (`OdeSystem`), returning the trajectory (`OdeTrajectory`).
59
+ - `createBarycentricInterpolator(xs, ys)`: polynomial interpolation in the
60
+ barycentric second form.
61
+ - `sumSeries(term, options)`: a series summed until its terms stop changing
62
+ it, with exactly rounded partial sums.
63
+ - `nelderMead(f, start, options)`: derivative-free minimisation with
64
+ Gao–Han adaptive coefficients.
65
+
66
+ ### Patch Changes
67
+
68
+ - 5c203e7: `findLevelCrossings` and `findLevelBands` with a reused `out` now allocate
69
+ nothing whatever their bounds: bounds that are not small integers, such as
70
+ epoch milliseconds, and the level of `findLevelCrossings` were boxed on every
71
+ search until its entry code reached the optimising tier, thousands of searches
72
+ in.
73
+ - Updated dependencies [5c203e7]
74
+ - Updated dependencies [5c203e7]
75
+ - Updated dependencies [5c203e7]
76
+ - Updated dependencies [5c203e7]
77
+ - Updated dependencies [5c203e7]
78
+ - Updated dependencies [5c203e7]
79
+ - Updated dependencies [5c203e7]
80
+ - Updated dependencies [5c203e7]
81
+ - Updated dependencies [5c203e7]
82
+ - Updated dependencies [5c203e7]
83
+ - Updated dependencies [5c203e7]
84
+ - Updated dependencies [5c203e7]
85
+ - Updated dependencies [5c203e7]
86
+ - Updated dependencies [5c203e7]
87
+ - @ac-kit/algo@0.7.0
88
+ - @ac-kit/core@0.14.0
89
+ - @ac-kit/math-linear@0.5.0
90
+ - @ac-kit/math-scalar@0.5.0
91
+
92
+ ## 0.2.0
93
+
94
+ ### Minor Changes
95
+
96
+ - 0b4fe43: `brent(f, lower, upper, options?)` finds a root inside a sign-changing bracket
97
+ with Brent's 1973 algorithm: the root stays bracketed, convergence is
98
+ superlinear on a smooth root and never much worse than bisection. The result
99
+ is within `4ε|x| + 2 · tolerance` of a root (`tolerance` defaults to `0`: what
100
+ binary64 can resolve). It accepts the bracket in either order, throws
101
+ `RangeError` for a bracket without a sign change, non-finite ends or a `NaN`
102
+ from `f`, and `ConvergenceError` only when a caller's `maxIterations` runs out.
103
+
104
+ `findLevelCrossings(f, lower, upper, { maxRate, level?, resolution?,
105
+ tolerance?, integer?, budget?, signal? }, out?)` returns every crossing of a
106
+ level, certified by a bound `maxRate` on `|f′|`: as `LevelCrossings` columns
107
+ (`times`, `directions`, `earliestTimes`/`latestTimes` enclosures, `startSide`),
108
+ plus the `unresolved` intervals where a touch cannot be decided, never guessed.
109
+ With `integer: true`, a crossing is the first integer on the new side.
110
+ `findLevelBands(f, lower, upper, bands, options, out?)` returns, per band
111
+ `[low, high)`, the sorted half-open intervals where `low ≤ f < high`, the
112
+ enclosures of their ends and the band's unresolved intervals, searching every
113
+ edge in one subdivision. Both evaluate `f` at most `2 + 4 · (upper − lower) /
114
+ resolution` times to isolate the crossings, plus a bounded refinement per
115
+ crossing; charge a `WorkBudget` per evaluation; honour an `AbortSignal`; and
116
+ allocate nothing once a reused `out` has grown. `LevelSearchOptions` and
117
+ `LevelCrossingsOptions` type the options. The package now depends on
118
+ `@ac-kit/algo`.
119
+
120
+ ### Patch Changes
121
+
122
+ - Updated dependencies [0b4fe43]
123
+ - Updated dependencies [0b4fe43]
124
+ - Updated dependencies [0b4fe43]
125
+ - Updated dependencies [0b4fe43]
126
+ - Updated dependencies [0b4fe43]
127
+ - Updated dependencies [0b4fe43]
128
+ - Updated dependencies [0b4fe43]
129
+ - Updated dependencies [0b4fe43]
130
+ - Updated dependencies [0b4fe43]
131
+ - Updated dependencies [0b4fe43]
132
+ - Updated dependencies [0b4fe43]
133
+ - Updated dependencies [0b4fe43]
134
+ - Updated dependencies [0b4fe43]
135
+ - Updated dependencies [0b4fe43]
136
+ - Updated dependencies [0b4fe43]
137
+ - Updated dependencies [0b4fe43]
138
+ - Updated dependencies [0b4fe43]
139
+ - Updated dependencies [0b4fe43]
140
+ - Updated dependencies [0b4fe43]
141
+ - Updated dependencies [0b4fe43]
142
+ - Updated dependencies [0b4fe43]
143
+ - Updated dependencies [0b4fe43]
144
+ - Updated dependencies [0b4fe43]
145
+ - Updated dependencies [0b4fe43]
146
+ - Updated dependencies [0b4fe43]
147
+ - Updated dependencies [0b4fe43]
148
+ - Updated dependencies [0b4fe43]
149
+ - Updated dependencies [0b4fe43]
150
+ - Updated dependencies [0b4fe43]
151
+ - Updated dependencies [0b4fe43]
152
+ - Updated dependencies [0b4fe43]
153
+ - Updated dependencies [0b4fe43]
154
+ - @ac-kit/algo@0.6.0
155
+ - @ac-kit/core@0.13.0
156
+ - @ac-kit/math-scalar@0.4.0
157
+
3
158
  ## 0.1.11
4
159
 
5
160
  ### Patch Changes
package/README.md CHANGED
@@ -6,9 +6,12 @@ floating-point steps.
6
6
 
7
7
  ## Scope
8
8
 
9
- Every function here takes a callable `f: (x: number) => number` and returns an
9
+ Every function here takes a callable `f: (x: number) => number` — or, for the
10
+ minimisers, `f: ℝⁿ → ℝ` with its gradient — and returns an
10
11
  approximation with a stated error behaviour. That is the distinguishing trait:
11
- the input is a _function_, not a value.
12
+ the input is a _function_, not a value. The special functions are the
13
+ exception that completes the rule: the functions of analysis themselves,
14
+ evaluated where a closed form or a recursion gives them.
12
15
 
13
16
  Operations on values live in `@ac-kit/math-scalar`; operations on sampled
14
17
  sequences live in `@ac-kit/math-signal`.
@@ -17,9 +20,24 @@ sequences live in `@ac-kit/math-signal`.
17
20
 
18
21
  | Symbol | Description | Convergence |
19
22
  | --------------------------------------------- | ------------------------------------------------------------ | ---------------------- |
23
+ | `brent(f, lower, upper, options)` | Root within a sign-changing bracket, Brent's 1973 algorithm | superlinear, never much worse than bisection |
20
24
  | `bisect(f, lower, upper, options)` | Root of a continuous function within a sign-changing bracket | linear, `(b − a) / 2ⁿ` |
25
+ | `findLevelCrossings(f, lower, upper, options)` | Every crossing of a level, certified by a bound on `\|f′\|` | see below |
26
+ | `findLevelBands(f, lower, upper, bands, options)` | Where `low ≤ f < high`, for several bands at once, certified | see below |
21
27
  | `trapezoidalRule(f, lower, upper, intervals)` | Definite integral by piecewise linear approximation | `O(h²)` |
28
+ | `simpsonsRule(f, lower, upper, intervals)` | Definite integral by piecewise parabolas | `O(h⁴)` |
29
+ | `gaussLegendre(f, lower, upper, nodes)` | Definite integral at the roots of `Pₙ`, exact to degree `2n − 1` | exponential for analytic `f` |
30
+ | `adaptiveQuadrature(f, lower, upper, options)` | Definite integral by adaptive Gauss–Kronrod 7–15 (QUADPACK `qag`), with an error estimate | to the tolerance |
31
+ | `newtonRaphson(f, df, x0, options)` | Root from a starting point and the derivative; throws on a vanishing derivative or divergence | quadratic |
32
+ | `finiteDifference(f, x, options)` | Derivative by a central, forward or backward difference, step rounded to representable points | `O(h²)` / `O(h)` |
33
+ | `rungeKutta4(f, y0, tSpan, steps)` | Trajectory of a system `y′ = f(t, y)`, classical RK4 | `O(h⁴)` |
34
+ | `createBarycentricInterpolator(xs, ys)` | The interpolating polynomial, barycentric second form | exact at the nodes |
35
+ | `sumSeries(term, options)` | Sum of a series, stopped when terms stop changing it, exactly rounded partial sums | to the tolerance |
36
+ | `nelderMead(f, start, options)` | Minimum without derivatives, Nelder–Mead with Gao–Han coefficients | heuristic |
37
+ | `gradient`, `jacobian`, `hessian` | Multivariate derivatives by central differences | `O(h²)` |
38
+ | `levenbergMarquardt(residuals, start, options)` | Non-linear least squares, damped QR steps with Moré scaling and Nielsen's damping update | quadratic near a zero residual |
22
39
  | `continuedFractionEval(fraction, options)` | Value of a continued fraction, by modified Lentz | forward, no truncation guess |
40
+ | `BfgsMinimizer`, `bfgs(objective, start, options)` | Minimum of a smooth function of several variables, BFGS with a strong Wolfe line search | superlinear |
23
41
 
24
42
  ### Special functions
25
43
 
@@ -45,21 +63,160 @@ are not conveniences over `1 − P(a, x)` and `1 − erf(x)`: that subtraction h
45
63
  already discarded the whole answer by the time it is worth asking for. `erf(10)`
46
64
  is exactly `1` in binary64, while `erfc(10)` is `2.09e-45` and correct.
47
65
 
66
+ ### Associated Legendre functions
67
+
68
+ | Symbol | Description |
69
+ | --- | --- |
70
+ | `legendreSchmidt(out, maxDegree, colatitude, derivativesOut?)` | Schmidt semi-normalised `Pₙᵐ(cos θ)` and `dPₙᵐ/dθ`, every degree and order up to `maxDegree` — geomagnetism's (WMM, IGRF) |
71
+ | `legendreFullyNormalized(out, maxDegree, colatitude, derivativesOut?)` | Fully normalised `P̄ₙₘ(cos θ)` and `dP̄ₙₘ/dθ` — geodesy's (EGM2008, the geoid) |
72
+ | `legendreIndex(degree, order)`, `legendreTableLength(maxDegree)` | Where `(n, m)` sits in the triangular table, and its size |
73
+
74
+ Both fill a caller's `Float64Array` table, with no Condon–Shortley phase, in
75
+ O(maxDegree²) and with no allocation. Both run the Holmes–Featherstone modified
76
+ forward column method: each order's column is carried as `Pₙₘ / sinᵐθ` from a
77
+ scaled seed and multiplied back with the exponent of `sinᵐθ` kept apart, so the
78
+ table is finite and accurate at every colatitude to degree 2190 (EGM2008's)
79
+ and beyond, where the textbook recursion's seed `sinᵐθ` underflows to zero (past
80
+ order 180 at 1° from a pole) and takes every later degree of its column with
81
+ it. Near a pole the cosine is taken from the half angle, so a degree-2190
82
+ entry at `θ = 10⁻⁶` is not ruined by `cos θ` rounding. The derivatives come
83
+ from neighbouring orders, never through `1 / sin θ`, and are exact at the
84
+ poles.
85
+
86
+ ```ts
87
+ import { legendreIndex, legendreSchmidt, legendreTableLength } from "@ac-kit/math-analysis";
88
+
89
+ const values = new Float64Array(legendreTableLength(12));
90
+ const derivatives = new Float64Array(legendreTableLength(12));
91
+ legendreSchmidt(values, 12, colatitude, derivatives);
92
+ values[legendreIndex(3, 2)]; // P₃²(cos θ)
93
+ ```
94
+
48
95
  ## Reliability over speed
49
96
 
50
- `bisect` converges linearly, which is slow next to Newton's quadratic rate. It
51
- is nonetheless the right default: given a bracket where `f` changes sign, the
52
- intermediate value theorem guarantees a root inside, and bisection cannot fail
53
- to find it. Newton's method diverges from a poor starting point, stalls at
54
- inflection points, and needs a derivative. Faster methods belong here too, but
55
- as explicit choices, not as the default.
97
+ Given a bracket where `f` changes sign, the intermediate value theorem
98
+ guarantees a root inside, and bisection cannot fail to find it — but it buys
99
+ one bit per evaluation. `brent` keeps that guarantee (the root stays
100
+ bracketed, and Brent proves it never needs more than about N² evaluations
101
+ where bisection needs N) while interpolating its way to a smooth root in a
102
+ handful of steps, so it is the root finder to reach for. Its tolerance is
103
+ Brent's: the result is within `4ε|x| + 2 · tolerance` of a root, and the
104
+ default `tolerance: 0` asks for what binary64 can resolve. Newton's method,
105
+ faster still, diverges from a poor starting point, stalls at inflection points
106
+ and needs a derivative; it belongs here as an explicit choice, never the
107
+ default.
108
+
109
+ ## Certified level crossings
110
+
111
+ Sampling a function at a fixed step and watching for sign changes misses any
112
+ excursion shorter than the step, and nothing says so. `findLevelCrossings`
113
+ takes a bound `maxRate` on `|f′|` instead, and with it a certificate: between
114
+ two samples `a` and `b`, `|f(a) − level| + |f(b) − level| > maxRate · (b − a)`
115
+ proves that `f` cannot reach the level. Certified stretches are skipped whole,
116
+ the rest bisected down to `resolution`, each sign change refined by `brent`
117
+ (or, with `integer: true`, to the first integer on the new side through
118
+ `@ac-kit/algo`'s `binarySearch`).
119
+
120
+ ```ts
121
+ import { findLevelCrossings } from "@ac-kit/math-analysis";
122
+
123
+ const crossings = findLevelCrossings(altitude, startMs, endMs, {
124
+ level: -0.833, // degrees: sunrise and sunset
125
+ maxRate: 400 / 86_400_000, // the Sun never moves faster, in degrees a ms
126
+ resolution: 60_000, // examine touches down to a minute
127
+ integer: true, // epoch milliseconds
128
+ });
129
+ for (let index = 0; index < crossings.count; index++) {
130
+ crossings.times[index]; // the first millisecond on the new side
131
+ crossings.directions[index]; // 1 rising, -1 setting
132
+ }
133
+ ```
134
+
135
+ What comes back is never a guess:
136
+
137
+ - **Crossings**, as columns (`times`, `directions`), with the side of `f` at
138
+ `lower` in `startSide`. Each crossing carries an **enclosure**
139
+ `[earliestTimes[i], latestTimes[i]]` holding every zero of its cluster: `f`
140
+ is certified on the old side before it and on the new side after. A crossing
141
+ at a slope near `maxRate` is enclosed within `resolution`; a slow one more
142
+ loosely, since a loose bound cannot rule out a brief return there.
143
+ - **Unresolved intervals** (`unresolvedStarts`, `unresolvedEnds`): stretches
144
+ away from any crossing where `f` may touch the level and come back — a
145
+ tangent, or a dip shorter than `resolution` — which the bound cannot decide.
146
+ A tangent leaves one about `2 · √(resolution · maxRate / |f″|)` wide.
147
+
148
+ Everywhere else the side of `f` is certified, provided `maxRate` truly bounds
149
+ `|f′|`. A bound that is too small, or a jump, can hide a crossing and its
150
+ return inside an interval it certified; a sign change between samples is still
151
+ found (at the jump, for a discontinuity), and every reported crossing is a real
152
+ sign change in either case.
153
+
154
+ The search is bounded: at most `2 + 2 · (upper − lower) / resolution`
155
+ evaluations (`4 ·` in integer mode) isolate the crossings, since no interval
156
+ narrower than `resolution` is split, and far fewer in practice — a stretch
157
+ where `|f − level| ≥ c` is certified in pieces `2c / maxRate` wide. Each
158
+ crossing then costs Brent's own bound, or `⌈log₂ resolution⌉` in integer mode.
159
+ A `WorkBudget` is charged one unit per evaluation and an `AbortSignal` checked
160
+ before each.
161
+
162
+ `findLevelBands(f, lower, upper, bands, options)` answers the question one
163
+ level up: for each band `[low, high)`, the sorted half-open intervals where
164
+ `low ≤ f < high`, with the enclosures of their ends and the band's unresolved
165
+ intervals. All the band edges are searched in one subdivision, so `f` is
166
+ evaluated once per point whatever the number of bands, and an edge shared by
167
+ two bands — golden hour's lower edge and blue hour's upper one — once.
168
+
169
+ Both write into a result object that can be passed back in (`out`): once its
170
+ columns have grown to the answer, a search allocates nothing. As anywhere in
171
+ V8, a double crossing a call the engine does not inline is boxed by its caller:
172
+ `f`'s result, unless `f` is inlined, and the arguments of a call site that has
173
+ seen many shapes of `f` or of the options object are the caller's allocations.
174
+
175
+ ## Minimisation
176
+
177
+ `BfgsMinimizer` minimises a smooth `f: ℝⁿ → ℝ` given with its gradient — the
178
+ objective writes `∇f` into an array and returns `f` — by the BFGS
179
+ quasi-Newton method: SciPy's `minimize(method="BFGS")` and Optim.jl's `BFGS`,
180
+ for up to a few hundred variables. Each step searches its line with Moré and
181
+ Thuente's algorithm (MINPACK-2's `dcsrch`, step for step) until the strong
182
+ Wolfe conditions hold, which keeps the inverse Hessian approximation positive
183
+ definite; near the minimum, where `f` can no longer resolve a decrease, Hager
184
+ and Zhang's approximate Wolfe conditions let the gradient converge past the
185
+ precision of `f`. A trial point where `f` is not finite halves the step, so a
186
+ domain boundary is approached and never crossed.
187
+
188
+ ```ts
189
+ import { BfgsMinimizer } from "@ac-kit/math-analysis";
190
+
191
+ const minimizer = new BfgsMinimizer(2, { gradientTolerance: 1e-10 });
192
+ const point = minimizer.minimize(
193
+ new Float64Array(2),
194
+ (x, gradient) => {
195
+ const a = 1 - x[0]!;
196
+ const b = x[1]! - x[0]! * x[0]!;
197
+ gradient[0] = -2 * a - 400 * x[0]! * b;
198
+ gradient[1] = 200 * b;
199
+ return a * a + 100 * b * b;
200
+ },
201
+ Float64Array.of(-1.2, 1),
202
+ );
203
+ minimizer.status; // "gradient": converged; also "value", "step",
204
+ // "max-iterations" or "line-search"
205
+ minimizer.inverseHessian; // a Matrix (@ac-kit/math-linear), ≈ (∇²f)⁻¹
206
+ ```
207
+
208
+ A minimiser is made once per dimension and options and allocates nothing
209
+ afterwards; `bfgs(objective, start, options)` is the one-shot form. A
210
+ `WorkBudget` is charged one unit per evaluation and an `AbortSignal` checked
211
+ before each. The variables are unconstrained: reparametrise a bounded one
212
+ (`σ = eᵗ` for a scale).
56
213
 
57
214
  ## Usage
58
215
 
59
216
  ```ts
60
- import { bisect, trapezoidalRule } from "@ac-kit/math-analysis";
217
+ import { brent, trapezoidalRule } from "@ac-kit/math-analysis";
61
218
 
62
- bisect((x) => x * x - 2, 0, 2); // ≈ 1.4142135623…
219
+ brent((x) => x * x - 2, 0, 2); // ≈ 1.4142135623…
63
220
  trapezoidalRule(Math.sin, 0, Math.PI); // ≈ 2
64
221
  ```
65
222
 
@@ -0,0 +1,41 @@
1
+ /** Which side of `x` a finite difference samples. */
2
+ export type FiniteDifferenceScheme = "central" | "forward" | "backward";
3
+ /** The options of {@link finiteDifference}. */
4
+ export type FiniteDifferenceOptions = {
5
+ /** `"central"` (the default, `O(h²)`), `"forward"` or `"backward"` (`O(h)`). */
6
+ scheme?: FiniteDifferenceScheme;
7
+ /**
8
+ * The step. By default the one that balances truncation against rounding for
9
+ * a function computed to full precision: `∛ε · max(|x|, 1)` for the central
10
+ * scheme, `√ε · max(|x|, 1)` for the one-sided ones.
11
+ */
12
+ step?: number;
13
+ };
14
+ /**
15
+ * The derivative of `f` at `x` by a finite difference: `(f(x + h) − f(x − h)) /
16
+ * 2h` for the central scheme, `(f(x + h) − f(x)) / h` forward and `(f(x) − f(x
17
+ * − h)) / h` backward.
18
+ *
19
+ * The step is rounded so that `x + h` and `x − h` are exactly representable and
20
+ * differ from `x` by exactly the `h` divided by — without that, the rounding of
21
+ * `x + h` alone is an error of up to half an ulp of `x` in the denominator.
22
+ * With the default step, a central difference keeps about two thirds of the
23
+ * significant digits (around 1e-11 relative for a well-scaled smooth function)
24
+ * and a one-sided one about half. Use a one-sided scheme only where `f` is not
25
+ * defined on one side of `x`. Two or three calls to `f`.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * finiteDifference(Math.sin, 0); // ≈ 1, within 1e-10
30
+ * finiteDifference(Math.sqrt, 0, { scheme: "forward", step: 1e-8 }); // 1e4 — √x has no derivative at 0
31
+ * ```;
32
+ *
33
+ * @param f The function to differentiate.
34
+ * @param x Where to take the derivative.
35
+ * @param options The scheme and the step.
36
+ * @returns The estimated derivative.
37
+ * @throws {RangeError} When the step is not positive and finite, or the scheme
38
+ * is unknown.
39
+ */
40
+ export declare function finiteDifference(f: (x: number) => number, x: number, options?: FiniteDifferenceOptions): number;
41
+ //# sourceMappingURL=finite-difference.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"finite-difference.d.ts","sourceRoot":"","sources":["../../src/differentiation/finite-difference.ts"],"names":[],"mappings":"AAEA,qDAAqD;AACrD,MAAM,MAAM,sBAAsB,GAAG,SAAS,GAAG,SAAS,GAAG,UAAU,CAAC;AAExE,+CAA+C;AAC/C,MAAM,MAAM,uBAAuB,GAAG;IACrC,gFAAgF;IAChF,MAAM,CAAC,EAAE,sBAAsB,CAAC;IAChC;;;;OAIG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;CACd,CAAC;AAKF;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,gBAAgB,CAC/B,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,EACxB,CAAC,EAAE,MAAM,EACT,OAAO,CAAC,EAAE,uBAAuB,GAC/B,MAAM,CA2BR"}
@@ -0,0 +1,53 @@
1
+ import { describeValue } from "@ac-kit/core";
2
+ const CUBE_ROOT_EPSILON_ = Math.cbrt(Number.EPSILON);
3
+ const SQUARE_ROOT_EPSILON_ = Math.sqrt(Number.EPSILON);
4
+ /**
5
+ * The derivative of `f` at `x` by a finite difference: `(f(x + h) − f(x − h)) /
6
+ * 2h` for the central scheme, `(f(x + h) − f(x)) / h` forward and `(f(x) − f(x
7
+ * − h)) / h` backward.
8
+ *
9
+ * The step is rounded so that `x + h` and `x − h` are exactly representable and
10
+ * differ from `x` by exactly the `h` divided by — without that, the rounding of
11
+ * `x + h` alone is an error of up to half an ulp of `x` in the denominator.
12
+ * With the default step, a central difference keeps about two thirds of the
13
+ * significant digits (around 1e-11 relative for a well-scaled smooth function)
14
+ * and a one-sided one about half. Use a one-sided scheme only where `f` is not
15
+ * defined on one side of `x`. Two or three calls to `f`.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * finiteDifference(Math.sin, 0); // ≈ 1, within 1e-10
20
+ * finiteDifference(Math.sqrt, 0, { scheme: "forward", step: 1e-8 }); // 1e4 — √x has no derivative at 0
21
+ * ```;
22
+ *
23
+ * @param f The function to differentiate.
24
+ * @param x Where to take the derivative.
25
+ * @param options The scheme and the step.
26
+ * @returns The estimated derivative.
27
+ * @throws {RangeError} When the step is not positive and finite, or the scheme
28
+ * is unknown.
29
+ */
30
+ export function finiteDifference(f, x, options) {
31
+ const scheme = options?.scheme ?? "central";
32
+ if (scheme !== "central" && scheme !== "forward" && scheme !== "backward") {
33
+ throw new RangeError(`finiteDifference: unknown scheme ${describeValue(scheme)}`);
34
+ }
35
+ const scale = Math.max(Math.abs(x), 1);
36
+ const requested = options?.step ??
37
+ (scheme === "central" ? CUBE_ROOT_EPSILON_ : SQUARE_ROOT_EPSILON_) * scale;
38
+ if (!(requested > 0) || requested === Infinity) {
39
+ throw new RangeError(`finiteDifference: step must be positive and finite, got ${describeValue(requested)}`);
40
+ }
41
+ // The step actually taken: the difference of two representable points.
42
+ const above = x + requested;
43
+ const step = above - x;
44
+ if (scheme === "forward") {
45
+ return (f(above) - f(x)) / step;
46
+ }
47
+ const below = x - step;
48
+ if (scheme === "backward") {
49
+ return (f(x) - f(below)) / (x - below);
50
+ }
51
+ return (f(above) - f(below)) / (above - below);
52
+ }
53
+ //# sourceMappingURL=finite-difference.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"finite-difference.js","sourceRoot":"","sources":["../../src/differentiation/finite-difference.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAiB7C,MAAM,kBAAkB,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AACrD,MAAM,oBAAoB,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AAEvD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,UAAU,gBAAgB,CAC/B,CAAwB,EACxB,CAAS,EACT,OAAiC;IAEjC,MAAM,MAAM,GAAG,OAAO,EAAE,MAAM,IAAI,SAAS,CAAC;IAC5C,IAAI,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,UAAU,EAAE,CAAC;QAC3E,MAAM,IAAI,UAAU,CACnB,oCAAoC,aAAa,CAAC,MAAM,CAAC,EAAE,CAC3D,CAAC;IACH,CAAC;IACD,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IACvC,MAAM,SAAS,GACd,OAAO,EAAE,IAAI;QACb,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,oBAAoB,CAAC,GAAG,KAAK,CAAC;IAC5E,IAAI,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,IAAI,SAAS,KAAK,QAAQ,EAAE,CAAC;QAChD,MAAM,IAAI,UAAU,CACnB,2DAA2D,aAAa,CAAC,SAAS,CAAC,EAAE,CACrF,CAAC;IACH,CAAC;IACD,uEAAuE;IACvE,MAAM,KAAK,GAAG,CAAC,GAAG,SAAS,CAAC;IAC5B,MAAM,IAAI,GAAG,KAAK,GAAG,CAAC,CAAC;IACvB,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QAC1B,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;IACjC,CAAC;IACD,MAAM,KAAK,GAAG,CAAC,GAAG,IAAI,CAAC;IACvB,IAAI,MAAM,KAAK,UAAU,EAAE,CAAC;QAC3B,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC;IACxC,CAAC;IACD,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC;AAChD,CAAC"}
@@ -0,0 +1,73 @@
1
+ import type { Matrix } from "@ac-kit/math-linear";
2
+ /** The options of {@link gradient}, {@link jacobian} and {@link hessian}. */
3
+ export type DerivativeStepOptions = {
4
+ /**
5
+ * The step per coordinate, relative to `max(|xᵢ|, 1)`. By default the one
6
+ * that balances truncation against rounding: `∛ε` for the central first
7
+ * differences of `gradient` and `jacobian`, `⁴√ε` for the second differences
8
+ * of `hessian`.
9
+ */
10
+ relativeStep?: number;
11
+ };
12
+ /**
13
+ * The gradient `∇f` of a scalar function of several variables at `point`, by
14
+ * central differences: `∂f/∂xᵢ ≈ (f(x + hᵢeᵢ) − f(x − hᵢeᵢ)) / 2hᵢ`, each step
15
+ * rounded so that both shifted coordinates are representable and exactly `2hᵢ`
16
+ * apart. `2n` calls to `f`, which receives one scratch vector it must not keep.
17
+ * What lets {@link bfgs} minimise a function given without its gradient.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * gradient(new Float64Array(2), (x) => x[0]! ** 2 + 3 * x[1]!, [1, 5]); // ≈ [2, 3]
22
+ * ```;
23
+ *
24
+ * @param out The gradient, one entry per coordinate.
25
+ * @param f The function.
26
+ * @param point Where to differentiate.
27
+ * @param options The relative step.
28
+ * @returns `out`.
29
+ * @throws {RangeError} When `out` has another length than `point`, a coordinate
30
+ * is not finite, or the step is not positive.
31
+ */
32
+ export declare function gradient(out: Float64Array, f: (x: Float64Array) => number, point: ArrayLike<number>, options?: DerivativeStepOptions): Float64Array;
33
+ /**
34
+ * The Jacobian of a vector function `F: ℝⁿ → ℝᵐ` at `point`, by central
35
+ * differences, into the `m × n` matrix `out`: column `j` is `(F(x + hⱼeⱼ) − F(x
36
+ * − hⱼeⱼ)) / 2hⱼ`. `F` writes its `m` values into the array it is given; `2n`
37
+ * calls, two scratch value arrays.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * // F(x, y) = (x·y, x + y²)
42
+ * const out = matrixCreate(2, 2);
43
+ * jacobian(out, (values, x) => { values[0] = x[0]! * x[1]!; values[1] = x[0]! + x[1]! ** 2; }, [2, 3]);
44
+ * // ≈ [[3, 2], [1, 6]]
45
+ * ```;
46
+ *
47
+ * @param out The Jacobian, `m × n`, column-major.
48
+ * @param f The function; writes `out.rows` values.
49
+ * @param point Where to differentiate, `out.columns` coordinates.
50
+ * @param options The relative step.
51
+ * @returns `out`.
52
+ * @throws {RangeError} When the shapes disagree, a coordinate is not finite, or
53
+ * the step is not positive.
54
+ */
55
+ export declare function jacobian(out: Matrix, f: (values: Float64Array, x: Float64Array) => void, point: ArrayLike<number>, options?: DerivativeStepOptions): Matrix;
56
+ /**
57
+ * The Hessian of a scalar function at `point`, by central second differences,
58
+ * into the symmetric `n × n` matrix `out`: `(f(x + hᵢ) − 2f(x) + f(x − hᵢ)) /
59
+ * hᵢ²` on the diagonal, `(f(x + hᵢ + hⱼ) − f(x + hᵢ − hⱼ) − f(x − hᵢ + hⱼ) +
60
+ * f(x − hᵢ − hⱼ)) / 4hᵢhⱼ` off it, written to both halves. `2n² + 1` calls to
61
+ * `f`; about a third of the digits of `f` survive, so prefer an analytic
62
+ * Hessian where one exists.
63
+ *
64
+ * @param out The Hessian, `n × n`.
65
+ * @param f The function.
66
+ * @param point Where to differentiate, `n` coordinates.
67
+ * @param options The relative step.
68
+ * @returns `out`.
69
+ * @throws {RangeError} When `out` is not `n × n`, a coordinate is not finite,
70
+ * or the step is not positive.
71
+ */
72
+ export declare function hessian(out: Matrix, f: (x: Float64Array) => number, point: ArrayLike<number>, options?: DerivativeStepOptions): Matrix;
73
+ //# sourceMappingURL=gradient.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gradient.d.ts","sourceRoot":"","sources":["../../src/differentiation/gradient.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAElD,6EAA6E;AAC7E,MAAM,MAAM,qBAAqB,GAAG;IACnC;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAgCF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,QAAQ,CACvB,GAAG,EAAE,YAAY,EACjB,CAAC,EAAE,CAAC,CAAC,EAAE,YAAY,KAAK,MAAM,EAC9B,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,EACxB,OAAO,CAAC,EAAE,qBAAqB,GAC7B,YAAY,CAoBd;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,QAAQ,CACvB,GAAG,EAAE,MAAM,EACX,CAAC,EAAE,CAAC,MAAM,EAAE,YAAY,EAAE,CAAC,EAAE,YAAY,KAAK,IAAI,EAClD,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,EACxB,OAAO,CAAC,EAAE,qBAAqB,GAC7B,MAAM,CA0BR;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,OAAO,CACtB,GAAG,EAAE,MAAM,EACX,CAAC,EAAE,CAAC,CAAC,EAAE,YAAY,KAAK,MAAM,EAC9B,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,EACxB,OAAO,CAAC,EAAE,qBAAqB,GAC7B,MAAM,CA8CR"}