Skip to content
Merged
Show file tree
Hide file tree
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
15 changes: 10 additions & 5 deletions lib/bigdecimal/math.rb
Original file line number Diff line number Diff line change
Expand Up @@ -759,11 +759,16 @@ def lgamma(x, prec)
if x < 0.5
return [BigDecimal::INFINITY, 1] if x.frac.zero?

# Euler's reflection formula: gamma(z) * gamma(1-z) = pi/sin(pi*z)
pi = PI(prec2)
sin = _sinpix(x, pi, prec2)
log_gamma = BigMath.log(pi, prec2).sub(lgamma(1 - x, prec2).first + BigMath.log(sin.abs, prec2), prec)
[log_gamma, sin > 0 ? 1 : -1]
loop do
# Euler's reflection formula: gamma(z) * gamma(1-z) = pi/sin(pi*z)
pi = PI(prec2)
sin = _sinpix(x, pi, prec2)
log_gamma = BigMath.log(pi, prec2).sub(lgamma(1 - x, prec2).first + BigMath.log(sin.abs, prec2), prec)
return [log_gamma, sin > 0 ? 1 : -1] if prec2 + log_gamma.exponent > prec + BigDecimal.double_fig

# Retry with higher precision if loss of significance is too large
prec2 = prec2 * 3 / 2
end
elsif x.frac.zero? && x < 1000 * prec
log_gamma = BigMath.log(_gamma_positive_integer(x, prec2), prec)
[log_gamma, 1]
Expand Down
4 changes: 4 additions & 0 deletions test/bigdecimal/test_bigmath.rb
Original file line number Diff line number Diff line change
Expand Up @@ -580,5 +580,9 @@ def test_lgamma
assert_converge_in_precision {|n| lgamma(BigDecimal("987.65421"), n).first }
assert_converge_in_precision {|n| lgamma(BigDecimal("-1234.56789"), n).first }
assert_converge_in_precision {|n| lgamma(BigDecimal("1e+400"), n).first }

# gamma close 1 or -1 cases
assert_converge_in_precision {|n| lgamma(BigDecimal('-3.143580888349980058694358781820227899566'), n).first }
assert_converge_in_precision {|n| lgamma(BigDecimal('-4.991544640560047722345260122806465721667'), n).first }
end
end