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()
double lgamma(double x);
float lgammaf(float x);
long double lgammal(long double x);
Parameters
Parameter | Description |
---|---|
x | The 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
#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:
- The variable
num
is assigned the value 5.0. - The
lgamma()
function computes the natural logarithm of the absolute value of the gamma function fornum
. - 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
#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:
- The variable
num
is set to -3.0, a value that may lead to a pole error for the lgamma function. errno
is reset to 0 before the function call to ensure any error can be detected.- The
lgamma()
function is called withnum
and the result is stored inresult
. - If a pole error occurs,
errno
is set toERANGE
and an error message is printed. Otherwise, the computed result is displayed.
Program Output:
Pole error: input -3.00 caused ERANGE