Skip to content

Faster exp calculation #399

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 17 additions & 10 deletions lib/bigdecimal.rb
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,18 @@ def self.log(x, prec)
y.mult(2 ** (sqrt_steps + 1), prec)
end

private_class_method def self._exp_taylor(x, prec) # :nodoc:
xn = BigDecimal(1)
y = BigDecimal(1)
1.step do |i|
n = prec + xn.exponent
break if n <= 0 || xn.zero?
xn = xn.mult(x, n).div(i, n)
y = y.add(xn, prec)
end
y
end

# call-seq:
# BigMath.exp(decimal, numeric) -> BigDecimal
#
Expand All @@ -270,17 +282,12 @@ def self.exp(x, prec)
cnt = x > 1 ? x.exponent : 0
prec2 = prec + BigDecimal.double_fig + cnt
x *= BigDecimal("1e-#{cnt}")
xn = BigDecimal(1)
y = BigDecimal(1)

# Taylor series for exp(x) around 0
1.step do |i|
n = prec2 + xn.exponent
break if n <= 0 || xn.zero?
x = x.mult(1, n)
xn = xn.mult(x, n).div(i, n)
y = y.add(xn, prec2)
end
# Calculation of exp(small_prec) is fast because calculation of x**n is fast
# Calculation of exp(small_abs) converges fast.
# exp(x) = exp(small_prec_part + small_abs_part) = exp(small_prec_part) * exp(small_abs_part)
x_small_prec = x.round(Integer.sqrt(prec2))
y = _exp_taylor(x_small_prec, prec2).mult(_exp_taylor(x - x_small_prec, prec2), prec2)

# calculate exp(x * 10**cnt) from exp(x)
# exp(x * 10**k) = exp(x * 10**(k - 1)) ** 10
Expand Down
Loading