Skip to content

Commit

Permalink
Fix {1,-1,inf,-inf}-norm calculation
Browse files Browse the repository at this point in the history
The abs should be applied prior to summing elements.
  • Loading branch information
kortschak committed May 3, 2014
1 parent 8cb72a4 commit 8da3124
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
16 changes: 8 additions & 8 deletions mat64/dense_arithmetic.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,38 +56,38 @@ func (m *Dense) Norm(ord float64) float64 {
for i := 0; i < m.mat.Cols; i++ {
var s float64
for _, e := range m.Col(col, i) {
s += e
s += math.Abs(e)
}
n = math.Max(math.Abs(s), n)
n = math.Max(s, n)
}
case math.IsInf(ord, +1):
row := make([]float64, m.mat.Cols)
for i := 0; i < m.mat.Rows; i++ {
var s float64
for _, e := range m.Row(row, i) {
s += e
s += math.Abs(e)
}
n = math.Max(math.Abs(s), n)
n = math.Max(s, n)
}
case ord == -1:
n = math.MaxFloat64
col := make([]float64, m.mat.Rows)
for i := 0; i < m.mat.Cols; i++ {
var s float64
for _, e := range m.Col(col, i) {
s += e
s += math.Abs(e)
}
n = math.Min(math.Abs(s), n)
n = math.Min(s, n)
}
case math.IsInf(ord, -1):
n = math.MaxFloat64
row := make([]float64, m.mat.Cols)
for i := 0; i < m.mat.Rows; i++ {
var s float64
for _, e := range m.Row(row, i) {
s += e
s += math.Abs(e)
}
n = math.Min(math.Abs(s), n)
n = math.Min(s, n)
}
case ord == 0:
for i := 0; i < len(m.mat.Data); i += m.mat.Stride {
Expand Down
20 changes: 20 additions & 0 deletions mat64/dense_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,26 @@ func (s *S) TestNorm(c *check.C) {
ord: -inf,
norm: 6,
},
{
a: [][]float64{{1, -2, -2}, {-4, 5, 6}},
ord: 1,
norm: 8,
},
{
a: [][]float64{{1, -2, -2}, {-4, 5, 6}},
ord: -1,
norm: 5,
},
{
a: [][]float64{{1, -2, -2}, {-4, 5, 6}},
ord: inf,
norm: 15,
},
{
a: [][]float64{{1, -2, -2}, {-4, 5, 6}},
ord: -inf,
norm: 5,
},
} {
a := NewDense(flatten(test.a))
c.Check(a.Norm(test.ord), check.Equals, test.norm, check.Commentf("Test %d: %v norm = %f", i, test.a, test.norm))
Expand Down

0 comments on commit 8da3124

Please sign in to comment.