End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
BigMath#cos
cos(decimal, numeric) → BigDecimal
ext/bigdecimal/lib/bigdecimal/math.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.1.3/ext/bigdecimal/lib/bigdecimal/math.rb, line 102
def cos(x, prec)
raise ArgumentError, "Zero or negative precision for cos" if prec <= 0
return BigDecimal("NaN") if x.infinite? || x.nan?
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
y = one
d = y
i = BigDecimal("0")
z = one
while d.nonzero? && ((m = n - (y.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)
y += d
end
y
end
Computes the cosine of decimal to the specified number of digits of precision, numeric.
If decimal is Infinity or NaN, returns NaN.
Example
BigMath.cos(BigMath.PI(4), 16).to_s #=> "-0.999999999999999999999999999999856613163740061349e0"