def gamma(n): def gamma_ln(z): if z < 0: raise ValueError("Invalid input: z must be…
- User
def gamma(n): def gamma_ln(z): if z < 0: raise ValueError("Invalid input: z must be positive.") elif z < 0.5: # Use the reflection formula for better accuracy when z < 0.5 # Gamma(z) = pi / (sin(pi * z) * Gamma(1 - z)) # ln(Gamma(z)) = ln(pi) - ln(sin(pi * z)) - ln(Gamma(1 - z)) ln_pi = ln(pi) ln_sin_pi_z = ln(sin(pi * z)) ln_gamma_1_minus_z = gamma_ln(1 - z) ln_gamma = ln_pi - ln_sin_pi_z - ln_gamma_1_minus_z return ln_gamma else: # Use Lanczos approximation directly ln_gamma_z = gamma_ln_lanczos(z) return ln_gamma_z
codedef gamma_ln_lanczos(z): # Lanczos approximation coefficients with higher precision # Coefficients are from the GNU Scientific Library (GSL) p = [ 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7, ] # Adjust z for the approximation z_minus_one = z - 1.0 x = 0.99999999999980993 # Initial value for the sum # Manually compute the sum without using loops x += p[0] / (z_minus_one + 1.0) x += p[1] / (z_minus_one + 2.0) x += p[2] / (z_minus_one + 3.0) x += p[3] / (z_minus_one + 4.0) x += p[4] / (z_minus_one + 5.0) x += p[5] / (z_minus_one + 6.0) x += p[6] / (z_minus_one + 7.0) x += p[7] / (z_minus_one + 8.0) t = z_minus_one + 7.5 # g + 0.5 where g = 7 # Compute ln(Gamma(z)) using math functions ln_two_pi = ln(2.0 * pi) ln_gamma = ( (z_minus_one + 0.5) * ln(t) - t + ln(x) + 0.5 * ln_two_pi ) return ln_gammaулучши точность без циклов, рекурсии, встроенных функций ** и ^
- Assistant