尝试在没有内置函数的情况下使用高斯-拉盖尔求积来计算伽玛函数的值

问题描述 投票:0回答:1

我正在尝试编写一个程序,计算 python 中任何值 n 的伽马函数值(由积分(t^(n-1)*e^(-t)*dt) 定义)。然而,我的答案是非常错误的,我不知道我做错了什么。

如有任何帮助,我们将不胜感激!谢谢!

这是 gamma(5) 示例案例的代码:

import math


# Define the function to be integrated (f(x) = x^4 * e^(-x))
def integrand(x):
    return x**4 * math.exp(-x)

# Gauss-Laguerre quadrature weights and nodes for n=5
weights = [0.2635603197181409102030619, 1.413403059106516792218407, 3.59642577104072208112447, 7.08581000585883755692212, 12.64080084427578265943]
nodes = [0.1834346424956498, 0.9165752759150713, 2.4148302753646825, 4.2898664265427511, 7.209661773352202]

# Calculate the value of the gamma function using Gauss-Laguerre quadrature
gamma_value = 0
for i in range(len(weights)):
    gamma_value += weights[i] * integrand(nodes[i])

# Display the result
print("Gamma(5) calculated using Gauss-Laguerre quadrature:", gamma_value)

答案应该是 24,但它打印出 69.47。

python integration gaussian
1个回答
0
投票

问题在于用于高斯-拉盖尔求积的权重和节点。在您的代码中,它们与顺序

n=5
不匹配,导致计算不正确。

要在 Python 中使用高斯-拉盖尔求积精确计算伽玛函数,您可以使用 SciPy 库,它提供了数值积分函数,包括高斯-拉盖尔求积。

import scipy.integrate as spi
import numpy as np

# Define the function to be integrated (f(x) = x^(n-1) * e^(-x))
def integrand(x, n):
    return x**(n-1) * np.exp(-x)

# Set the value of n
n = 5

# Use SciPy to compute the gamma function using Gauss-Laguerre quadrature
gamma_value, _ = spi.quad(integrand, 0, np.inf, args=(n,))

# Display the result
print(f"Gamma({n}) calculated using SciPy Gauss-Laguerre quadrature:", gamma_value)

这里 SciPy 处理

n=5
的适当权重和节点的计算,确保结果准确。您可以将
n
替换为任何其他值,以计算不同阶数的伽玛函数。

建议使用 SciPy 进行此类数值积分任务,因为它可以简化流程并提供可靠的结果。

© www.soinside.com 2019 - 2024. All rights reserved.