Skip to content

Commit aa1e42a

Browse files
committed
Make tan depend only on sin
1 parent 3e440c0 commit aa1e42a

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

lib/bigdecimal/math.rb

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,37 @@ def cos(x, prec)
148148
# #=> "0.999999999999999999999955588155008544487055622030633191403625599381672572e0"
149149
#
150150
def tan(x, prec)
151-
sin(x, prec) / cos(x, prec)
151+
sine = sin(x, prec)
152+
153+
n = prec + BigDecimal.double_fig
154+
one = BigDecimal("1")
155+
two = BigDecimal("2")
156+
x = -x if x < 0
157+
if x > (twopi = two * BigMath.PI(prec))
158+
if x > 30
159+
x %= twopi
160+
else
161+
x -= twopi while x > twopi
162+
end
163+
end
164+
x1 = one
165+
x2 = x.mult(x,n)
166+
sign = 1
167+
cosine = one
168+
d = cosine
169+
i = BigDecimal("0")
170+
z = one
171+
while d.nonzero? && ((m = n - (cosine.exponent - d.exponent).abs) > 0)
172+
m = BigDecimal.double_fig if m < BigDecimal.double_fig
173+
sign = -sign
174+
x1 = x2.mult(x1,n)
175+
i += two
176+
z *= (i-one) * i
177+
d = sign * x1.div(z,m)
178+
cosine += d
179+
end
180+
181+
sine / cosine
152182
end
153183

154184
# call-seq:

0 commit comments

Comments
 (0)