/
trigonometric_interpolation.js
55 lines (52 loc) · 1.1 KB
/
trigonometric_interpolation.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
54
55
/**
* Trigonometric interpolation
*/
export default class TrigonometricInterpolation {
// https://en.wikipedia.org/wiki/Trigonometric_interpolation
constructor() {
this._alpha = 0
}
/**
* Fit model.
*
* @param {number[]} x Training data
* @param {number[]} y Target values
*/
fit(x, y) {
const d = x.map((v, i) => [v, y[i]])
d.sort((a, b) => a[0] - b[0])
this._x = d.map(v => v[0])
this._y = d.map(v => v[1])
}
_t(x, k) {
const n = this._x.length
let v = 1
if (n % 2 === 0) {
v = Math.sin((x - this._alpha) / 2) / Math.sin((this._x[k] - this._alpha) / 2)
if (!Number.isFinite(v)) {
v = 1
}
}
for (let i = 0; i < n; i++) {
if (i === k) continue
v *= Math.sin((x - this._x[i]) / 2) / Math.sin((this._x[k] - this._x[i]) / 2)
}
return v
}
/**
* Returns predicted interpolated values.
*
* @param {number[]} target Sample data
* @returns {number[]} Predicted values
*/
predict(target) {
const n = this._x.length
return target.map(t => {
let v = 0
for (let i = 0; i < n; i++) {
v += this._y[i] * this._t(t, i)
}
return v
})
}
}