From 8c2359ccdb536da479abfe1ce9715c2206be7de3 Mon Sep 17 00:00:00 2001 From: tompng Date: Sat, 10 May 2025 17:05:19 +0900 Subject: [PATCH] Ensure BigMath.sin and BigMath.cos to be within -1..1 --- lib/bigdecimal/math.rb | 3 ++- test/bigdecimal/test_bigmath.rb | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/bigdecimal/math.rb b/lib/bigdecimal/math.rb index 3d96e150..b264c8b8 100644 --- a/lib/bigdecimal/math.rb +++ b/lib/bigdecimal/math.rb @@ -85,6 +85,7 @@ def sin(x, prec) d = sign * x1.div(z,m) y += d end + y = BigDecimal("1") if y > 1 neg ? -y : y end @@ -130,7 +131,7 @@ def cos(x, prec) d = sign * x1.div(z,m) y += d end - y + y < -1 ? BigDecimal("-1") : y > 1 ? BigDecimal("1") : y end # call-seq: diff --git a/test/bigdecimal/test_bigmath.rb b/test/bigdecimal/test_bigmath.rb index 545a963e..e3402211 100644 --- a/test/bigdecimal/test_bigmath.rb +++ b/test/bigdecimal/test_bigmath.rb @@ -53,6 +53,8 @@ def test_sin assert_fixed_point_precision {|n| sin(BigDecimal("1e-30"), n) } assert_fixed_point_precision {|n| sin(BigDecimal(PI(50)), n) } assert_fixed_point_precision {|n| sin(BigDecimal(PI(50) * 100), n) } + assert_operator(sin(PI(30) / 2, 30), :<=, 1) + assert_operator(sin(-PI(30) / 2, 30), :>=, -1) end def test_cos @@ -74,6 +76,8 @@ def test_cos assert_fixed_point_precision {|n| cos(BigDecimal("1e50"), n) } assert_fixed_point_precision {|n| cos(BigDecimal(PI(50) / 2), n) } assert_fixed_point_precision {|n| cos(BigDecimal(PI(50) * 201 / 2), n) } + assert_operator(cos(PI(30), 30), :>=, -1) + assert_operator(cos(PI(30) * 2, 30), :<=, 1) end def test_atan