Skip to content

Commit

Permalink
get stddev working
Browse files Browse the repository at this point in the history
this includes avoiding overflow for large values
  • Loading branch information
neonstalwart committed Apr 23, 2015
1 parent 94030b2 commit 23c38fb
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 10 deletions.
6 changes: 3 additions & 3 deletions cmd/influxd/server_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -581,14 +581,14 @@ func runTestsData(t *testing.T, testName string, nodes Cluster, database, retent
// Aggregations
{
reset: true,
name: "large mean",
name: "large mean and stddev",
write: `{"database" : "%DB%", "retentionPolicy" : "%RP%", "points": [
{"name": "cpu", "timestamp": "2015-04-20T14:27:40Z", "fields": {"value": ` + string(maxFloat64) + `}},
{"name": "cpu", "timestamp": "2015-04-20T14:27:41Z", "fields": {"value": ` + string(maxFloat64) + `}}
]}`,
query: `SELECT mean(value) FROM cpu`,
query: `SELECT mean(value), stddev(value) FROM cpu`,
queryDb: "%DB%",
expected: `{"results":[{"series":[{"name":"cpu","columns":["time","mean"],"values":[["1970-01-01T00:00:00Z",` + string(maxFloat64) + `]]}]}]}`,
expected: `{"results":[{"series":[{"name":"cpu","columns":["time","mean","stddev"],"values":[["1970-01-01T00:00:00Z",` + string(maxFloat64) + `,0]]}]}]}`,
},
{
reset: true,
Expand Down
16 changes: 9 additions & 7 deletions influxql/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -397,29 +397,31 @@ func ReduceStddev(values []interface{}) interface{} {
if value == nil {
continue
}
data = append(data, value.([]float64)...)
for _, val := range value.([]float64) {
data = append(data, val)
}
}

// If no data or we only have one point, it's nil or undefined
if len(data) < 2 {
return nil
}

// Get the sum
var sum float64
// Get the mean
var mean float64
var count int
for _, v := range data {
sum += v
count++
mean += (v - mean) / float64(count)
}
// Get the mean
mean := sum / float64(len(data))
// Get the variance
var variance float64
for _, v := range data {
dif := v - mean
sq := math.Pow(dif, 2)
variance += sq
}
variance = variance / float64(len(data)-1)
variance = variance / float64(count-1)
stddev := math.Sqrt(variance)

return stddev
Expand Down

0 comments on commit 23c38fb

Please sign in to comment.