2018-10-14 03:07:28 +02:00
|
|
|
package math
|
|
|
|
|
|
|
|
import (
|
2019-02-13 19:31:18 +02:00
|
|
|
"math"
|
|
|
|
|
2018-10-14 03:07:28 +02:00
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/core"
|
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/values"
|
2019-02-13 19:31:18 +02:00
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/values/types"
|
2018-10-14 03:07:28 +02:00
|
|
|
)
|
|
|
|
|
2019-03-29 16:48:51 +02:00
|
|
|
func variance(input *values.Array, sample values.Int) values.Float {
|
2018-10-14 03:07:28 +02:00
|
|
|
if input.Length() == 0 {
|
2019-03-29 16:48:51 +02:00
|
|
|
return values.NewFloat(math.NaN())
|
2018-10-14 03:07:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
m, _ := mean(input)
|
|
|
|
|
|
|
|
var err error
|
|
|
|
var variance values.Float
|
|
|
|
|
|
|
|
input.ForEach(func(value core.Value, idx int) bool {
|
2019-02-13 19:31:18 +02:00
|
|
|
err = core.ValidateType(value, types.Int, types.Float)
|
2018-10-14 03:07:28 +02:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
n := values.Float(toFloat(value))
|
|
|
|
|
|
|
|
variance += (n - m) * (n - m)
|
|
|
|
|
|
|
|
return true
|
|
|
|
})
|
|
|
|
|
|
|
|
// When getting the mean of the squared differences
|
|
|
|
// "sample" will allow us to know if it's a sample
|
|
|
|
// or population and wether to subtract by one or not
|
|
|
|
l := values.Float(input.Length() - (1 * sample))
|
|
|
|
|
2019-03-29 16:48:51 +02:00
|
|
|
return variance / l
|
2018-10-14 03:07:28 +02:00
|
|
|
}
|