Skip to content

Commit cebd1a5

Browse files
authored
Add support for tangent function (#231)
* Add support for tangent function * Apply review comments for tests * Make tan depend only on sin * Use Ziv's loop method suggested in review * Test failing test * Use first implementation based on sin and cos * Remove unused code
1 parent 23144a7 commit cebd1a5

2 files changed

Lines changed: 30 additions & 0 deletions

File tree

lib/bigdecimal/math.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
# sqrt(x, prec)
88
# sin (x, prec)
99
# cos (x, prec)
10+
# tan (x, prec)
1011
# atan(x, prec)
1112
# PI (prec)
1213
# E (prec) == exp(1.0,prec)
@@ -124,6 +125,24 @@ def cos(x, prec)
124125
sign * sin(x, prec)
125126
end
126127

128+
# call-seq:
129+
# tan(decimal, numeric) -> BigDecimal
130+
#
131+
# Computes the tangent of +decimal+ to the specified number of digits of
132+
# precision, +numeric+.
133+
#
134+
# If +decimal+ is Infinity or NaN, returns NaN.
135+
#
136+
# BigMath.tan(BigDecimal("0.0"), 4).to_s
137+
# #=> "0.0"
138+
#
139+
# BigMath.tan(BigMath.PI(4) / 4, 4).to_s
140+
# #=> "0.99999999999999999999419869652481995799388629632650769e0"
141+
#
142+
def tan(x, prec)
143+
sin(x, prec) / cos(x, prec)
144+
end
145+
127146
# call-seq:
128147
# atan(decimal, numeric) -> BigDecimal
129148
#

test/bigdecimal/test_bigmath.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,17 @@ def test_cos
9191
assert_operator(cos(PI(30) * 2, 30), :<=, 1)
9292
end
9393

94+
def test_tan
95+
assert_in_delta(0.0, tan(BigDecimal("0.0"), N))
96+
assert_in_delta(0.0, tan(PI(N), N))
97+
assert_in_delta(1.0, tan(PI(N) / 4, N))
98+
assert_in_delta(sqrt(BigDecimal(3), N), tan(PI(N) / 3, N))
99+
assert_in_delta(sqrt(BigDecimal(3), 10 * N), tan(PI(10 * N) / 3, 10 * N))
100+
assert_in_delta(0.0, tan(-PI(N), N))
101+
assert_in_delta(-1.0, tan(-PI(N) / 4, N))
102+
assert_in_delta(-sqrt(BigDecimal(3), N), tan(-PI(N) / 3, N))
103+
end
104+
94105
def test_atan
95106
assert_equal(0.0, atan(BigDecimal("0.0"), N))
96107
assert_in_delta(Math::PI/4, atan(BigDecimal("1.0"), N))

0 commit comments

Comments
 (0)