import math
print(math.gamma(0.01))
print(gamma(0.01))
точность падает когда n стремится к 0 , попробуй использовать подход ten_powers или использовать значение n > = 1 для определения верного вычисления для значений n < 1
You're correct that the accuracy of your gamma function implementation decreases as ( n ) approaches 0. This is because the Stirling approximation, even with correction terms, is not accurate for small values of ( n ). The Stirling series is an asymptotic expansion valid for large ( n ), and its accuracy deteriorates when ( n ) is small.
To improve the accuracy for ( n < 1 ), you can use several approaches:
Use the Recurrence Relation More Aggressively:
Instead of applying the relation ( \Gamma(n) = \Gamma(n + 1) / n ) only once, apply it multiple times to shift ( n ) to a value greater than or equal to 1. This way, you compute ( \Gamma(n + k) ) where ( n + k \geq 1 ), and then relate it back to ( \Gamma(n) ).
Use a More Suitable Approximation for Small ( n ):
The Stirling approximation isn't suitable for small ( n ). Instead, you can use the Lanczos approximation, which provides high accuracy across the entire positive real axis.
Use Built-in Functions or Libraries:
If exact computation is critical, consider using well-tested numerical libraries like mpmath or scipy.special.
Below, I'll provide updated code implementing these suggestions.
Improved Implementation Using Recurrence Relation
By repeatedly applying the recurrence relation ( \Gamma(n) = \Gamma(n + 1) / n ), you can shift ( n ) to a larger value where the Stirling approximation is more accurate.
python
import math
def gamma(n):
if n <= 0:
raise ValueError("Invalid input: n must be positive.")
# Shift n to n + k where n + k >= 10 for better accuracy
k = 0
n_shifted = n
while n_shifted < 10:
n_shifted += 1
k += 1
# Use the Stirling approximation for ln(Γ(n + k))
ln_n = math.log(n_shifted)
n_inv = 1 / n_shifted
# Stirling series correction terms
stirling_series = (
n_inv / 12
- n_inv**3 / 360
+ n_inv**5 / 1260
- n_inv**7 / 1680
+ n_inv**9 / 1188
- n_inv**11 / 1680
)
ln_two_pi = math.log(2 * math.pi)
ln_gamma_nk = (
(n_shifted - 0.5) * ln_n
- n_shifted
+ 0.5 * ln_two_pi
+ stirling_series
)
# Use the recurrence relation to compute ln(Γ(n))
for i in range(k):
ln_gamma_nk -= math.log(n + i)
gamma_n = math.exp(ln_gamma_nk)
return gamma_n
Explanation:
Shifting ( n ) to a Larger Value:
We increment ( n ) until ( n + k \geq 10 ). The value 10 is chosen because the Stirling approximation becomes more accurate for larger arguments.
Applying the Recurrence Relation:
We adjust the computed ( \ln(\Gamma(n + k)) ) by subtracting ( \ln(n + i) ) for ( i = 0 ) to ( k - 1 ) to get back to ( \ln(\Gamma(n)) ).
Using the Lanczos Approximation
The Lanczos approximation is highly accurate for computing the gamma function across the entire positive real axis.
python
import math
def gamma(n):
if n <= 0:
raise ValueError("Invalid input: n must be positive.")
# Lanczos coefficients for g=7, n=9
p = [
0.99999999999980993,
676.5203681218851,
-1259.1392167224028,
771.32342877765313,
-176.61502916214059,
12.507343278686905,
-0.13857109526572012,
9.9843695780195716e-6,
1.5056327351493116e-7
]
g = 7
n_minus_1 = n - 1
a = p[0]
t = n_minus_1 + g + 0.5
for i in range(1, len(p)):
a += p[i] / (n_minus_1 + i)
sqrt_two_pi = math.sqrt(2 * math.pi)
gamma_n = sqrt_two_pi * t**(n_minus_1 + 0.5) * math.exp(-t) * a
return gamma_n
Explanation:
Lanczos Approximation:
This method approximates the gamma function using a rational function, providing high accuracy even for small ( n ).
Coefficients:
The coefficients ( p ) are precomputed for the approximation. The value ( g ) is a constant that affects the accuracy and range.
Why the Original Implementation Lacks Accuracy Near Zero
Limitations of Stirling's Approximation:
Stirling's approximation is derived under the assumption that ( n ) is large. When ( n ) is small, particularly near zero, the approximation deviates significantly from the true value.
Numerical Instability:
Subtracting large numbers to get small differences can introduce significant rounding errors, which is a problem when using logarithms and exponentials with small arguments.
Insufficient Correction Terms:
Even with additional correction terms, the series may not converge quickly enough for small ( n ).
Understanding the "Ten Powers" Approach
The "ten_powers" approach you mentioned likely involves scaling techniques to improve numerical stability. Here's how you can apply a scaling method:
Scale ( n ) by Powers of Ten:
Multiply ( n ) by ( 10^k ) to shift it to a larger value where the approximation is accurate.
Adjust the Gamma Function Accordingly:
Use the property ( \Gamma(n) = \Gamma(n \times 10^k) / [(10^k)^{n} \times \prod_{i=0}^{k-1} (n + i / 10^k)] ).
However, this approach is more complex and may not offer significant benefits over shifting ( n ) using the recurrence relation.
Example Comparison
Let's compare the results of the original function, the improved function, and Python's built-in math.gamma function:
python
import math
n_values = [0.01, 0.1, 0.5, 1, 5, 10]
print("n\tOriginal\tImproved\tmath.gamma")
for n in n_values:
original = gamma_original(n) # Your original function
improved = gamma(n) # The improved function
builtin = math.gamma(n)
print(f"{n}\t{original:.5e}\t{improved:.5e}\t{builtin:.5e}")
By using the recurrence relation to shift ( n ) to a larger value and applying the Stirling approximation there, or by using the Lanczos approximation, you can significantly improve the accuracy of your gamma function implementation for values of ( n ) approaching zero.
References:
Lanczos, C. (1964). A precision approximation of the gamma function. SIAM Journal on Numerical Analysis, Series B, 1(1), 86-96.
Press, W. H., Teukolsky, S. A., Vetterling, W. T., & Flannery, B. P. (2007). Numerical Recipes 3rd Edition: The Art of Scientific Computing. Cambridge University Press.
Feel free to ask if you have any questions or need further assistance with the implementation!