Skip to content
Merged
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
13 changes: 8 additions & 5 deletions lib/bigdecimal.rb
Original file line number Diff line number Diff line change
Expand Up @@ -303,10 +303,13 @@ def log(x, prec)

prec2 = prec + BigDecimal.double_fig

if x < 0.1 || x > 10
exponent = (3 * x).exponent - 1
x = x._decimal_shift(-exponent)
return log(10, prec2).mult(exponent, prec2).add(log(x, prec2), prec)
# Reduce x to near 1
if x > 1.01 || x < 0.99
# log(x) = log(x/exp(logx_approx)) + logx_approx
logx_approx = BigDecimal(BigDecimal::Internal.float_log(x), 0)
x = x.div(exp(logx_approx, prec2), prec2)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Precision of exp should be larger than prec2 - logx_approx.exponent.abs theoretically and also experimentally. Just using prec2 is simple and enough.

else
logx_approx = BigDecimal(0)
end

# Solve exp(y) - x = 0 with Newton's method
Expand All @@ -317,7 +320,7 @@ def log(x, prec)
expy = exp(y, p + exp_additional_prec)
y = y.sub(expy.sub(x, p).div(expy, p), p)
end
y.mult(1, prec)
y.add(logx_approx, prec)
end

private_class_method def _exp_binary_splitting(x, prec) # :nodoc:
Expand Down