From fa82d26b64a329051537c909b4f4b9b540653e3e Mon Sep 17 00:00:00 2001 From: Yutaka Ichibangase Date: Sat, 19 Mar 2022 14:02:22 +0900 Subject: [PATCH] add evaluable functor: atan2 --- engine/number.go | 38 ++++++++++++++++++++++++++++---- engine/number_test.go | 50 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 4 deletions(-) diff --git a/engine/number.go b/engine/number.go index 4babfe6..a29da4c 100644 --- a/engine/number.go +++ b/engine/number.go @@ -45,10 +45,11 @@ var DefaultEvaluableFunctors = EvaluableFunctors{ `/\`: BitwiseAnd, `\/`: BitwiseOr, - `div`: IntFloorDiv, - `max`: Max, - `min`: Min, - `^`: IntegerPower, + `div`: IntFloorDiv, + `max`: Max, + `min`: Min, + `^`: IntegerPower, + `atan2`: Atan2, }, } @@ -960,6 +961,35 @@ func Acos(x Number) (Number, error) { return Float(math.Acos(vx)), nil } +// Atan2 returns the arc tangent of y/x. +func Atan2(y, x Number) (Number, error) { + var vy float64 + switch y := y.(type) { + case Integer: + vy = float64(y) + case Float: + vy = float64(y) + default: + return nil, ErrUndefined + } + + var vx float64 + switch x := x.(type) { + case Integer: + vx = float64(x) + case Float: + vx = float64(x) + default: + return nil, ErrUndefined + } + + if vx == 0 && vy == 0 { + return nil, ErrUndefined + } + + return Float(math.Atan2(vy, vx)), nil +} + // Comparison func eqF(x, y Float) bool { diff --git a/engine/number_test.go b/engine/number_test.go index 90ed79b..5f5f6d4 100644 --- a/engine/number_test.go +++ b/engine/number_test.go @@ -1662,6 +1662,56 @@ func TestAcos(t *testing.T) { }) } +func TestAtan2(t *testing.T) { + t.Run("integer", func(t *testing.T) { + t.Run("integer", func(t *testing.T) { + r, err := Atan2(Integer(0), Integer(1)) + assert.NoError(t, err) + assert.Equal(t, Float(0), r) + }) + + t.Run("float", func(t *testing.T) { + r, err := Atan2(Integer(0), Float(1)) + assert.NoError(t, err) + assert.Equal(t, Float(0), r) + }) + + t.Run("not a number", func(t *testing.T) { + _, err := Atan2(Integer(0), mockNumber{}) + assert.Equal(t, ErrUndefined, err) + }) + }) + + t.Run("float", func(t *testing.T) { + t.Run("integer", func(t *testing.T) { + r, err := Atan2(Float(0), Integer(1)) + assert.NoError(t, err) + assert.Equal(t, Float(0), r) + }) + + t.Run("float", func(t *testing.T) { + r, err := Atan2(Float(0), Float(1)) + assert.NoError(t, err) + assert.Equal(t, Float(0), r) + }) + + t.Run("not a number", func(t *testing.T) { + _, err := Atan2(Float(0), mockNumber{}) + assert.Equal(t, ErrUndefined, err) + }) + }) + + t.Run("not a number", func(t *testing.T) { + _, err := Atan2(mockNumber{}, Integer(1)) + assert.Equal(t, ErrUndefined, err) + }) + + t.Run("x and y both equal to 0", func(t *testing.T) { + _, err := Atan2(Integer(0), Integer(0)) + assert.Equal(t, ErrUndefined, err) + }) +} + type mockNumber struct { mock.Mock }