Skip to content

Commit 4b80634

Browse files
authored
Fix w type 1 calculation of lagrange model (#1027)
1 parent 435cbea commit 4b80634

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

lib/model/lagrange.js

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,10 +55,16 @@ export default class LagrangeInterpolation {
5555
const w = x.map((d, j) => 1 / x.reduce((p, v, i) => (i === j ? p : p * (d - v)), 1))
5656
if (this._w_type === 1) {
5757
return target.map(t => {
58-
const l = x.reduce((p, k) => p * (t - k), 1)
59-
return x.reduce((s, d, j) => {
60-
return s + (y[j] * l * w[j]) / (t - d + 1.0e-8)
61-
}, 0)
58+
let l = 1
59+
let v = 0
60+
for (let i = 0; i < x.length; i++) {
61+
if (t === x[i]) {
62+
return y[i]
63+
}
64+
l *= t - x[i]
65+
v += (y[i] * w[i]) / (t - x[i])
66+
}
67+
return l * v
6268
})
6369
} else {
6470
return target.map(t => {

tests/lib/model/lagrange.test.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,25 @@ test.each([undefined, '', 'weighted', 'newton'])('interpolation %s', { retry: 3
2323
const err = rmse(y0, x0.map(Math.sin))
2424
expect(err).toBeLessThan(0.1)
2525
})
26+
27+
test('interpolation w type 1', () => {
28+
const model = new LagrangeInterpolation()
29+
model._w_type = 1
30+
const x = Matrix.random(20, 1, -2, 2).value
31+
const t = []
32+
for (let i = 0; i < x.length; i++) {
33+
t[i] = Math.sin(x[i])
34+
}
35+
model.fit(x, t)
36+
37+
const y = model.predict(x)
38+
expect(y).toHaveLength(x.length)
39+
for (let i = 0; i < y.length; i++) {
40+
expect(y[i]).toBeCloseTo(t[i])
41+
}
42+
43+
const x0 = Matrix.random(100, 1, -2, 2).value
44+
const y0 = model.predict(x0)
45+
const err = rmse(y0, x0.map(Math.sin))
46+
expect(err).toBeLessThan(0.1)
47+
})

0 commit comments

Comments
 (0)