lgamma() Function

The lgamma() function computes the natural logarithm of the absolute value of the gamma function of a given number. This function is particularly useful in scenarios where working directly with the gamma function might result in overflow, as it operates in the logarithmic domain to maintain numerical stability.


Syntax of lgamma()

</>
Copy
double lgamma(double x);
float lgammaf(float x);
long double lgammal(long double x);

Parameters

ParameterDescription
xThe input value for which the log-gamma function is computed.

Return Value

The function returns the natural logarithm of the absolute value of the gamma function for the provided input value.

Note: If the input value is too large, an overflow range error occurs; if the input is zero or a negative integer where the function is asymptotic, a pole error may occur. In these cases, depending on the math_errhandling settings, either the global variable errno is set to ERANGE or the floating-point exceptions FE_OVERFLOW or FE_DIVBYZERO are raised.


Examples for lgamma()

Example 1: Calculating the Log-Gamma of a Positive Number

This example demonstrates how to compute the log-gamma value for a positive number using lgamma().

Program

</>
Copy
#include <stdio.h>
#include <math.h>

int main() {
    double num = 5.0;
    double result = lgamma(num);

    printf("The log-gamma of %.2f is %.5f\n", num, result);
    return 0;
}

Explanation:

  1. The variable num is assigned the value 5.0.
  2. The lgamma() function computes the natural logarithm of the absolute value of the gamma function for num.
  3. The computed result is stored in result and printed.

Program Output:

The log-gamma of 5.00 is 3.17805

Example 2: Handling a Pole Error with a Non-positive Integer Input

This example shows what happens when lgamma() is called with a non-positive integer, which may lead to a pole error. Depending on the implementation and error handling settings, a runtime error may be raised.

Program

</>
Copy
#include <stdio.h>
#include <math.h>
#include <errno.h>

int main() {
    double num = -3.0;
    errno = 0;  // Reset errno before calling lgamma
    double result = lgamma(num);

    if(errno == ERANGE) {
        printf("Pole error: input %.2f caused ERANGE\n", num);
    } else {
        printf("The log-gamma of %.2f is %.5f\n", num, result);
    }
    return 0;
}

Explanation:

  1. The variable num is set to -3.0, a value that may lead to a pole error for the lgamma function.
  2. errno is reset to 0 before the function call to ensure any error can be detected.
  3. The lgamma() function is called with num and the result is stored in result.
  4. If a pole error occurs, errno is set to ERANGE and an error message is printed. Otherwise, the computed result is displayed.

Program Output:

Pole error: input -3.00 caused ERANGE