Added cumprod function. Fixed error in CumSum

This commit is contained in:
btracey
2013-05-17 00:11:39 -07:00
parent f205572009
commit b2c4f68fd6
2 changed files with 23 additions and 2 deletions

View File

@@ -98,7 +98,24 @@ func CumSum(receiver, s []float64) []float64 {
}
receiver[0] = s[0]
for i := 1; i < len(s); i++ {
receiver[i] += receiver[i-1] + s[i]
receiver[i] = receiver[i-1] + s[i]
}
return receiver
}
// Finds the cumulative product of the first i elements in
// s and puts them in place into the ith element of the
// receiver. If the receiver is nil a new slice is created
func CumProd(receiver, s []float64) []float64 {
if receiver == nil {
receiver = make([]float64, len(s))
}
if len(s) == 0 {
return receiver[:0]
}
receiver[0] = s[0]
for i := 1; i < len(s); i++ {
receiver[i] = receiver[i-1] + s[i]
}
return receiver
}

View File

@@ -108,6 +108,10 @@ func TestCumSum(t *testing.T) {
val := CumSum(nil, s)
truth := []float64{3, 7, 8, 15, 20}
if !Eq(val, truth, 1E-15) {
t.Errorf("Wrong cumsum returned. Expected %v, returned %v", truth, val)
t.Errorf("Wrong cumsum returned with nil receiver. Expected %v, returned %v", truth, val)
}
val = CumSum(val, s)
if !Eq(val, truth, 1E-15) {
t.Errorf("Wrong cumsum returned with non-nil receiver. Expected %v, returned %v", truth, val)
}
}