-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
79 lines (73 loc) · 1.97 KB
/
main.go
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Lagrange provides algorithms for working with multivariate Lagrange
// polynomials.
//
// https://en.wikipedia.org/wiki/Lagrange_polynomial
package lagrange
// Interpolant is a Lagrange interpolant.
type Interpolant struct {
nd uint
nn uint
grids [][]float64
values []float64
}
// New creates an interpolant given a set of one-dimensional grids and a set of
// values of the target function obtained at the nodes of the corresponding
// tensor-product grid.
func New(grids [][]float64, values []float64) *Interpolant {
return &Interpolant{
nd: uint(len(grids)),
nn: uint(len(values)),
grids: grids,
values: values,
}
}
// Evaluate computes the values of the interpolant at set of multidimensional
// points.
func (self *Interpolant) Evaluate(points []float64) []float64 {
nd, nn := self.nd, self.nn
grids, values := self.grids, self.values
np := uint(len(points)) / nd
result := make([]float64, np)
for i := uint(0); i < np; i++ {
product := newWeight(nn)
for j := uint(0); j < nd; j++ {
product.next(lagrange(grids[j], points[i*nd+j]))
}
result[i] = dot(product.values, values)
}
return result
}
// Tensor constructs a tensor-product grid given a set of one-dimentional grids.
func Tensor(grids [][]float64) []float64 {
dimensions := uint(len(grids))
count := uint(1)
for i := uint(0); i < dimensions; i++ {
count *= uint(len(grids[i]))
}
product := newGrid(dimensions, count)
for i := uint(0); i < dimensions; i++ {
product.next(grids[i])
}
return product.values
}
func lagrange(nodes []float64, point float64) []float64 {
nn := uint(len(nodes))
values := make([]float64, nn)
for i := uint(0); i < nn; i++ {
values[i] = 1.0
for j := uint(0); j < nn; j++ {
if i != j {
values[i] *= (point - nodes[j]) / (nodes[i] - nodes[j])
}
}
}
return values
}
func dot(vector1, vector2 []float64) float64 {
nn := uint(len(vector1))
value := 0.0
for i := uint(0); i < nn; i++ {
value += vector1[i] * vector2[i]
}
return value
}