Skip to content

Commit

Permalink
Make tan depend only on sin
Browse files Browse the repository at this point in the history
  • Loading branch information
rhannequin committed Oct 30, 2022
1 parent 3e440c0 commit aa1e42a
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion lib/bigdecimal/math.rb
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,37 @@ def cos(x, prec)
# #=> "0.999999999999999999999955588155008544487055622030633191403625599381672572e0"
#
def tan(x, prec)
sin(x, prec) / cos(x, prec)
sine = sin(x, prec)

n = prec + BigDecimal.double_fig
one = BigDecimal("1")
two = BigDecimal("2")
x = -x if x < 0
if x > (twopi = two * BigMath.PI(prec))
if x > 30
x %= twopi
else
x -= twopi while x > twopi
end
end
x1 = one
x2 = x.mult(x,n)
sign = 1
cosine = one
d = cosine
i = BigDecimal("0")
z = one
while d.nonzero? && ((m = n - (cosine.exponent - d.exponent).abs) > 0)
m = BigDecimal.double_fig if m < BigDecimal.double_fig
sign = -sign
x1 = x2.mult(x1,n)
i += two
z *= (i-one) * i
d = sign * x1.div(z,m)
cosine += d
end

sine / cosine
end

# call-seq:
Expand Down

0 comments on commit aa1e42a

Please sign in to comment.