Skip to content

Instantly share code, notes, and snippets.

@nickpresta
Forked from mwarkentin/math.go
Last active December 17, 2015 13:09
Show Gist options
  • Save nickpresta/5614640 to your computer and use it in GitHub Desktop.
Save nickpresta/5614640 to your computer and use it in GitHub Desktop.
package math
import (
"errors"
m "math"
)
// Finds the minimum value in a slice of numbers
func Min(xs []float64) (float64, error) {
if len(xs) == 0 {
return m.NaN(), errors.New("Cannot get minimum value from empty slice")
}
min := xs[0]
for _, v := range xs {
if v < min {
min = v
}
}
return min, nil
}
package math
import (
m "math"
"testing"
)
type testpair struct {
values []float64
min float64
}
var minTests = []testpair{
{[]float64{1, 2}, 1},
{[]float64{1, 1, 1, 1, 1, 1}, 1},
{[]float64{-1, 1}, -1},
}
var minTestsNaN = []testpair{
{[]float64{}, m.NaN()},
}
func TestMin(t *testing.T) {
for _, pair := range minTests {
if v, err := Min(pair.values); err != nil {
t.Error("Got unexpected error: ", err)
} else if v != pair.min {
t.Error(
"For", pair.values,
"expected", pair.min,
"got", v,
)
}
}
}
func TestMinNaN(t *testing.T) {
for _, pair := range minTestsNaN {
v, err := Min(pair.values)
if err != nil {
if !m.IsNaN(v) {
t.Error("Should return NaN")
}
} else {
t.Error("Should've got error for NaN")
}
}
}
@nickpresta
Copy link
Author

math.NaN doesn't compare to anything (including itself) so I would separate out the test case and use an error to notify people when they get back a non-float64 return value (which they can check using IsNaN or whatever)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment