QR decomposition: Difference between revisions

→‎{{header|Go}}: add gonum/matrix solution
m (→‎{{header|Python}}: Add note on Numpy qr function.)
(→‎{{header|Go}}: add gonum/matrix solution)
Line 988:
 
=={{header|Go}}==
===Method of task description, library go.matrix===
{{trans|Common Lisp}}
A fairly close port of the Common Lisp solution, this solution uses the [http://github.com/skelterjohn/go.matrix go.matrix library] for supporting functions. Note though, that go.matrix has QR decomposition, as shown in the [[Polynomial_regression#Go|Go solution]] to Polynomial regression. The solution there is coded more directly than by following the CL example here. Similarly, examination of the go.matrix QR source shows that it computes the decomposition more directly.
Line 1,112 ⟶ 1,113:
2,
3}
</pre>
 
===Library QR, gonum/matrix===
<lang go>package main
 
import (
"fmt"
 
"github.com/gonum/matrix/mat64"
)
 
func main() {
// task 1: show qr decomp of wp example
a := mat64.NewDense(3, 3, []float64{
12, -51, 4,
6, 167, -68,
-4, 24, -41,
})
f := mat64.QR(a)
fmt.Printf("q:\n%.3f\n\n", M{f.Q()})
fmt.Printf("r:\n%.3f\n\n", M{f.R()})
 
// task 2: use qr decomp for polynomial regression example
x := mat64.NewDense(11, 1,
[]float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
y := mat64.NewDense(11, 1,
[]float64{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321})
fmt.Printf("polyfit:\n%.3f\n", M{polyfit(x, y, 2)})
}
 
func polyfit(x, y *mat64.Dense, n int) *mat64.Dense {
m, _ := x.Dims()
a := mat64.NewDense(m, n+1, nil)
for i := 0; i < m; i++ {
v := 1.
a.Set(i, 0, v)
i1 := float64(i)
for j := 1; j <= n; j++ {
v *= i1
a.Set(i, j, v)
}
}
f := mat64.QR(a)
return f.Solve(y)
}
 
type M struct{ mat64.Matrix }
 
func (m M) Format(f fmt.State, c rune) { mat64.Format(m, 0, 0, f, c) }</lang>
{{out}}
<pre>
q:
⎡-0.857 0.394 -0.331⎤
⎢-0.429 -0.903 0.034⎥
⎣ 0.286 -0.171 -0.943⎦
 
r:
⎡ -14.000 -21.000 14.000⎤
⎢ 0.000 -175.000 70.000⎥
⎣ 0.000 0.000 35.000⎦
 
polyfit:
⎡1.000⎤
⎢2.000⎥
⎣3.000⎦
</pre>
 
1,707

edits