| 1 |
package matrix |
| 2 |
|
| 3 |
import "errors" |
| 4 |
|
| 5 |
var ( |
| 6 |
|
| 7 |
ErrPolyRegArraysSameLength = errors.New("polynomial array inputs must be the same length") |
| 8 |
) |
| 9 |
|
| 10 |
|
| 11 |
func Poly(xvalues, yvalues []float64, degree int) ([]float64, error) { |
| 12 |
if len(xvalues) != len(yvalues) { |
| 13 |
return nil, ErrPolyRegArraysSameLength |
| 14 |
} |
| 15 |
|
| 16 |
m := len(yvalues) |
| 17 |
n := degree + 1 |
| 18 |
y := New(m, 1, yvalues...) |
| 19 |
x := Zero(m, n) |
| 20 |
|
| 21 |
for i := 0; i < m; i++ { |
| 22 |
ip := float64(1) |
| 23 |
for j := 0; j < n; j++ { |
| 24 |
x.Set(i, j, ip) |
| 25 |
ip *= xvalues[i] |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
q, r := x.QR() |
| 30 |
qty, err := q.Transpose().Times(y) |
| 31 |
if err != nil { |
| 32 |
return nil, err |
| 33 |
} |
| 34 |
|
| 35 |
c := make([]float64, n) |
| 36 |
for i := n - 1; i >= 0; i-- { |
| 37 |
c[i] = qty.Get(i, 0) |
| 38 |
for j := i + 1; j < n; j++ { |
| 39 |
c[i] -= c[j] * r.Get(i, j) |
| 40 |
} |
| 41 |
c[i] /= r.Get(i, i) |
| 42 |
} |
| 43 |
|
| 44 |
return c, nil |
| 45 |
} |