-
Notifications
You must be signed in to change notification settings - Fork 3
/
jacobian.ts
38 lines (30 loc) · 1 KB
/
jacobian.ts
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
import { Matrix } from '../operations/Matrix';
import { Vector } from '../operations/Vector';
import { JacobianFunction } from '../types/types';
import { array2d } from './functions';
/**
* Calculates the Jacobian matrix of a given Jacobian function.
* @param f The Jacobian function.
* @param m The number of rows in the Jacobian matrix.
* @param x0 The initial values of the variables.
* @param step The step size for numerical differentiation (default: 1e-5).
* @returns The Jacobian matrix.
*/
export function jacobian(f: JacobianFunction, m: number, x0: Float64Array, step = 0.00001): Matrix {
const n = x0.length;
const j = array2d(m, n, 0);
const h = 0.5 * step;
for (let k = 0; k < n; k++) {
const xp = x0.slice();
xp[k] += h;
const fp = new Vector(f(xp));
const xm = x0.slice();
xm[k] -= h;
const fm = new Vector(f(xm));
const cd = fp.subtract(fm).scale(1 / step);
for (let i = 0; i < m; i++) {
j[i][k] = cd.elements[i];
}
}
return new Matrix(j);
}