tgamma, tgammaf, tgammal

< c‎ | numeric‎ | math
在标头 <math.h> 定义
float       tgammaf( float arg );
(1) (C99 起)
double      tgamma( double arg );
(2) (C99 起)
long double tgammal( long double arg );
(3) (C99 起)
在标头 <tgmath.h> 定义
#define tgamma( arg )
(4) (C99 起)
1-3) 计算 arg伽马函数
4) 泛型宏:若 arg 拥有 long double 类型,则调用 tgammal。否则,若 arg 拥有整数类型或 double 类型,则调用 tgamma。否则调用 tgammaf

参数

arg - 浮点值

返回值

若不出现错误,则返回 arg 的 Γ 函数值,即
0
targ-1
e-t dt

若出现定义域错误,则返回实现定义值(受支持平台上为 NaN)。

若出现极点错误,则返回 HUGE_VAL±HUGE_VALF±HUGE_VALL

若出现上溢所致的值域错误,则返回 ±HUGE_VAL±HUGE_VALF±HUGE_VALL

若出现下溢所致的值域错误,则返回(舍入后的)正确结果。

错误处理

报告 math_errhandling 中指定的错误

arg 为零或为小于零的整数,则可能出现极点或定义域错误。

若实现支持 IEEE 浮点算术(IEC 60559),则

  • 若参数为 ±0,则返回 ±∞ 并引发 FE_DIVBYZERO
  • 若参数为负整数,则返回 NaN 并引发 FE_INVALID
  • 若参数为 -∞,则返回 NaN 并引发 FE_INVALID
  • 若参数为 +∞,则返回 +∞
  • 若参数为 NaN,则返回 NaN

注解

arg 为自然数,则 tgamma(arg)arg-1 的阶乘。许多实现若参数是足够小的整数,则计算准确的整数域阶乘。

对于 IEEE 兼容的 double 类型,若 0 < x < 1/DBL_MAXx > 171.7 则发生上溢。

POSIX 要求若实参为零则出现极点错误,但在实参为负整数时出现定义域错误。它亦指定在将来,对于负整数,定义域错误可能被替换成浮点错误(这些情况下返回值将从 NaN 更改为 ±∞)。

多数实现中有名为 gamma 的非标准函数,但其定义不一致。例如,gamma 的 glibc 和 4.2BSD 版本执行 lgamma,但 gamma 的 4.4BSD 版本执行 tgamma

示例

#include <errno.h>
#include <fenv.h>
#include <float.h>
#include <math.h>
#include <stdio.h>
// #pragma STDC FENV_ACCESS ON
 
int main(void)
{
    printf("tgamma(10) = %f, 9!=%f\n", tgamma(10), 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9.0);
    printf("tgamma(0.5) = %f, sqrt(pi) = %f\n", sqrt(acos(-1)), tgamma(0.5));
 
    // 特殊值
    printf("tgamma(+Inf) = %f\n", tgamma(INFINITY));
 
    // 错误处理
    errno = 0; feclearexcept(FE_ALL_EXCEPT);
    printf("tgamma(-1) = %f\n", tgamma(-1));
    if (errno == ERANGE)
        perror("    errno == ERANGE");
    else
        if (errno == EDOM)   perror("    errno == EDOM");
    if (fetestexcept(FE_DIVBYZERO))
        puts("    FE_DIVBYZERO raised");
    else if (fetestexcept(FE_INVALID))
        puts("    FE_INVALID raised");
}

可能的输出:

tgamma(10) = 362880.000000, 9!=362880.000000
tgamma(0.5) = 1.772454, sqrt(pi) = 1.772454
tgamma(+Inf) = inf
tgamma(-1) = nan
    errno == EDOM: Numerical argument out of domain
    FE_INVALID raised

引用

  • C23 标准(ISO/IEC 9899:2024):
  • 7.12.8.4 The tgamma functions (第 250 页)
  • 7.25 Type-generic math <tgmath.h> (第 373-375 页)
  • F.10.5.4 The tgamma functions (第 525 页)
  • C17 标准(ISO/IEC 9899:2018):
  • 7.12.8.4 The tgamma functions (第 250 页)
  • 7.25 Type-generic math <tgmath.h> (第 373-375 页)
  • F.10.5.4 The tgamma functions (第 525 页)
  • C11 标准(ISO/IEC 9899:2011):
  • 7.12.8.4 The tgamma functions (第 250 页)
  • 7.25 Type-generic math <tgmath.h> (第 373-375 页)
  • F.10.5.4 The tgamma functions (第 525 页)
  • C99 标准(ISO/IEC 9899:1999):
  • 7.12.8.4 The tgamma functions (第 231 页)
  • 7.22 Type-generic math <tgmath.h> (第 335-337 页)
  • F.9.5.4 The tgamma functions (第 462 页)

参阅

(C99)(C99)(C99)
计算伽马函数的自然对数(底为 e
(函数)

外部链接

Weisstein, Eric W. “伽马函数”来自 MathWorld--A Wolfram Web Resource。