mirror of
https://github.com/MontFerret/ferret.git
synced 2024-12-16 11:37:36 +02:00
5f94b77a39
* #7 Added ABS * #7 Added ACOS * #7 Added ASIN * #7 Added ATAN * #7 Added ATAN2 * #7 Added AVERAGE * #7 Added CEIL * #7 Added COS * #7 Added DEGREES * #7 Added EXP * #7 Added EXP2 * #7 Added FLOOR * #7 Added LOG * #7 Added LOG2 * #7 Added LOG10 * #7 Added MAX * #7 Added MEDIAN * #7 Added MIN * #7 Added PERCENTILE * #7 Added PI * #7 Added POW * #7 Added RADIANS * #7 Added RAND * #7 Added RANGE * #7 Added ROUND * #7 Added SIN * #7 Added SQRT * #7 Added TAN * #7 Added SUM * #7 Added STDDEV_POPULATION * #7 Added STDDEV_SAMPLE, VARIANCE_POPULATION, VARIANCE_SAMPLE
54 lines
960 B
Go
54 lines
960 B
Go
package math
|
|
|
|
import (
|
|
"context"
|
|
"github.com/MontFerret/ferret/pkg/runtime/core"
|
|
"github.com/MontFerret/ferret/pkg/runtime/values"
|
|
"math"
|
|
)
|
|
|
|
/*
|
|
* Returns the median of the values in array.
|
|
* @param array (Array) - Array of numbers.
|
|
* @returns (Float) - The median of the values in array.
|
|
*/
|
|
func Median(_ context.Context, args ...core.Value) (core.Value, error) {
|
|
var err error
|
|
err = core.ValidateArgs(args, 1, 1)
|
|
|
|
if err != nil {
|
|
return values.None, err
|
|
}
|
|
|
|
err = core.ValidateType(args[0], core.ArrayType)
|
|
|
|
if err != nil {
|
|
return values.None, err
|
|
}
|
|
|
|
arr := args[0].(*values.Array)
|
|
sorted := arr.Sort()
|
|
|
|
l := sorted.Length()
|
|
|
|
var median core.Value
|
|
|
|
if l == 0 {
|
|
return values.NewFloat(math.NaN()), nil
|
|
} else if l%2 == 0 {
|
|
median, err = mean(sorted.Slice(l/2-1, l/2+1))
|
|
|
|
if err != nil {
|
|
return values.None, nil
|
|
}
|
|
} else {
|
|
median = sorted.Get(l / 2)
|
|
}
|
|
|
|
if err != nil {
|
|
return values.None, nil
|
|
}
|
|
|
|
return median, nil
|
|
}
|