Skip to content

Commit f48f4fe

Browse files
committed
Ensure BigMath.sin and BigMath.cos to be within -1..1
1 parent a015c8b commit f48f4fe

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

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

135136
# call-seq:

test/bigdecimal/test_bigmath.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ def test_sin
3737
assert_in_delta(0.0, sin(PI(N) * 21, N))
3838
assert_in_delta(0.0, sin(PI(N) * 30, N))
3939
assert_in_delta(-1.0, sin(PI(N) * BigDecimal("301.5"), N))
40+
assert_operator(sin(PI(30) / 2, 30), :<=, 1)
41+
assert_operator(sin(-PI(30) / 2, 30), :>=, -1)
4042
end
4143

4244
def test_cos
@@ -51,6 +53,8 @@ def test_cos
5153
assert_in_delta(-1.0, cos(PI(N) * 21, N))
5254
assert_in_delta(1.0, cos(PI(N) * 30, N))
5355
assert_in_delta(0.0, cos(PI(N) * BigDecimal("301.5"), N))
56+
assert_operator(cos(PI(30), 30), :>=, -1)
57+
assert_operator(cos(PI(30) * 2, 30), :<=, 1)
5458
end
5559

5660
def test_atan

0 commit comments

Comments
 (0)