diff --git a/sql/funcs.go b/sql/funcs.go index b24afb14..6be16718 100644 --- a/sql/funcs.go +++ b/sql/funcs.go @@ -143,6 +143,7 @@ var funcs = map[string]map[int]interface{}{ "math.round": {1: nil}, "math.sample": {2: nil}, "math.spread": {1: nil}, + "math.sqrt": {1: nil}, "math.stddev": {1: nil}, "math.sum": {1: nil}, "math.top": {2: nil}, diff --git a/util/fncs/fnc.go b/util/fncs/fnc.go index cdaffef5..c9271343 100644 --- a/util/fncs/fnc.go +++ b/util/fncs/fnc.go @@ -154,6 +154,8 @@ func Run(ctx context.Context, name string, args ...interface{}) (interface{}, er return mathSample(ctx, args...) case "math.spread": return mathSpread(ctx, args...) + case "math.sqrt": + return mathSqrt(ctx, args...) case "math.stddev": return mathStddev(ctx, args...) case "math.sum": diff --git a/util/fncs/math.go b/util/fncs/math.go index 50322f41..e651bfb4 100644 --- a/util/fncs/math.go +++ b/util/fncs/math.go @@ -143,6 +143,13 @@ func mathSpread(ctx context.Context, args ...interface{}) (out interface{}, err return outputFloat(math.Spread(vals)) } +func mathSqrt(ctx context.Context, args ...interface{}) (out interface{}, err error) { + if val, ok := ensureFloat(args[0]); ok { + return outputFloat(math.Sqrt(val)) + } + return +} + func mathStddev(ctx context.Context, args ...interface{}) (out interface{}, err error) { vals := ensureFloats(args[0]) return outputFloat(math.PopulationStandardDeviation(vals)) diff --git a/util/fncs/math_test.go b/util/fncs/math_test.go index 4f00e22a..7597e68e 100644 --- a/util/fncs/math_test.go +++ b/util/fncs/math_test.go @@ -219,6 +219,15 @@ func TestMath(t *testing.T) { So(res, ShouldEqual, 4.5) }) + Convey("math.sqrt() works properly", t, func() { + res, _ = Run(context.Background(), "math.sqrt", "test") + So(res, ShouldEqual, nil) + res, _ = Run(context.Background(), "math.sqrt", test) + So(res, ShouldEqual, nil) + res, _ = Run(context.Background(), "math.sqrt", 10) + So(res, ShouldEqual, 3.1622776601683795) + }) + Convey("math.stddev() works properly", t, func() { res, _ = Run(context.Background(), "math.stddev", "test") So(res, ShouldEqual, nil) diff --git a/util/math/sqrt.go b/util/math/sqrt.go new file mode 100644 index 00000000..945170cc --- /dev/null +++ b/util/math/sqrt.go @@ -0,0 +1,21 @@ +// Copyright © 2016 Abcum Ltd +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package math + +import "math" + +func Sqrt(val float64) float64 { + return math.Sqrt(val) +}