Skip to content

Commit eaa9d8a

Browse files
authored
Ensure BigMath.sin and BigMath.cos to be within -1..1 (#317)
1 parent 9fe85e5 commit eaa9d8a

File tree

2 files changed

+6
-1
lines changed

2 files changed

+6
-1
lines changed

lib/bigdecimal/math.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ def sin(x, prec)
8585
d = sign * x1.div(z,m)
8686
y += d
8787
end
88+
y = BigDecimal("1") if y > 1
8889
neg ? -y : y
8990
end
9091

@@ -130,7 +131,7 @@ def cos(x, prec)
130131
d = sign * x1.div(z,m)
131132
y += d
132133
end
133-
y
134+
y < -1 ? BigDecimal("-1") : y > 1 ? BigDecimal("1") : y
134135
end
135136

136137
# call-seq:

test/bigdecimal/test_bigmath.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ def test_sin
5353
assert_fixed_point_precision {|n| sin(BigDecimal("1e-30"), n) }
5454
assert_fixed_point_precision {|n| sin(BigDecimal(PI(50)), n) }
5555
assert_fixed_point_precision {|n| sin(BigDecimal(PI(50) * 100), n) }
56+
assert_operator(sin(PI(30) / 2, 30), :<=, 1)
57+
assert_operator(sin(-PI(30) / 2, 30), :>=, -1)
5658
end
5759

5860
def test_cos
@@ -74,6 +76,8 @@ def test_cos
7476
assert_fixed_point_precision {|n| cos(BigDecimal("1e50"), n) }
7577
assert_fixed_point_precision {|n| cos(BigDecimal(PI(50) / 2), n) }
7678
assert_fixed_point_precision {|n| cos(BigDecimal(PI(50) * 201 / 2), n) }
79+
assert_operator(cos(PI(30), 30), :>=, -1)
80+
assert_operator(cos(PI(30) * 2, 30), :<=, 1)
7781
end
7882

7983
def test_atan

0 commit comments

Comments
 (0)