diff --git a/lib/bigdecimal/math.rb b/lib/bigdecimal/math.rb index 3ab84d8..4e9cadf 100644 --- a/lib/bigdecimal/math.rb +++ b/lib/bigdecimal/math.rb @@ -7,6 +7,7 @@ # sqrt(x, prec) # sin (x, prec) # cos (x, prec) +# tan (x, prec) # atan(x, prec) # PI (prec) # E (prec) == exp(1.0,prec) @@ -131,6 +132,26 @@ def cos(x, prec) y end + # call-seq: + # tan(decimal, numeric) -> BigDecimal + # + # Computes the tangent of +decimal+ to the specified number of digits of + # precision, +numeric+. + # + # If +decimal+ is Infinity or NaN, returns NaN. + # + # BigMath.tan(BigDecimal("0.0"), 4).to_s + # #=> "0.0" + # + # BigMath.tan(BigMath.PI(4) / 4, 4).to_s + # #=> "0.999999999999999999999955588155008544487055622030633191403625599381672572e0" + # + def tan(x, prec) + sine = sin(x, prec) + cosine = sqrt(1 - sine**2, prec) + sine / cosine + end + # call-seq: # atan(decimal, numeric) -> BigDecimal # diff --git a/test/bigdecimal/test_bigmath.rb b/test/bigdecimal/test_bigmath.rb index 5bf1fbf..2673f7c 100644 --- a/test/bigdecimal/test_bigmath.rb +++ b/test/bigdecimal/test_bigmath.rb @@ -53,6 +53,17 @@ def test_cos assert_in_delta(0.0, cos(PI(N) * BigDecimal("301.5"), N)) end + def test_tan + assert_in_delta(0.0, tan(BigDecimal("0.0"), N)) + assert_in_delta(0.0, tan(PI(N), N)) + assert_in_delta(1.0, tan(PI(N) / 4, N)) + assert_in_delta(sqrt(BigDecimal(3), N), tan(PI(N) / 3, N)) + assert_in_delta(sqrt(BigDecimal(3), 10 * N), tan(PI(10 * N) / 3, 10 * N)) + assert_in_delta(0.0, tan(-PI(N), N)) + assert_in_delta(-1.0, tan(-PI(N) / 4, N)) + assert_in_delta(-sqrt(BigDecimal(3), N), tan(-PI(N) / 3, N)) + end + def test_atan assert_equal(0.0, atan(BigDecimal("0.0"), N)) assert_in_delta(Math::PI/4, atan(BigDecimal("1.0"), N))