Selected Reading

C++ cmath lgamma() Function



The C++ cmath lgamma() function computes the natural logarithm of the absolute value of the gamma function for a given value. The gamma function is like an extended version of the factorial function that works for both real and complex numbers (except for non-positive integers). The lgamma() function is useful when dealing with large numbers where the direct computation of gamma may lead to overflow.

Syntax

Following is the syntax for C++ cmath lgamma() function.

double lgamma(double x);
or
float lgamma(float x);
or
long double lgamma(long double x);

Parameters

  • x - The value for which to calculate the log-gamma function.

Return Value

The function returns the natural logarithm of the absolute value of the gamma function for the specified value x.

Time Complexity

The time complexity of this function is constant, i.e.,O(1).

Example 1

The following example show's the basic usage of lgamma(), by calculating the lgamma (calculates the natural logarithm of (x-1)!) for a postive number.

#include <iostream>
#include <cmath>
int main() {
   double x = 5.0;
   std::cout << "lgamma(" << x << ") = " << std::lgamma(x) << std::endl;
   return 0;
}

Output

Output of the above code is as follows

lgamma(5) = 3.17805

Example 2

In this example std::lgamma() is used to calculate the logarithm of large factorials.

#include <iostream>
#include <cmath>
double log_factorial(int n) {
   if (n < 0) {
      std::cerr << "Error: Negative input for factorial." << std::endl;
      return -1; 
   }
   return std::lgamma(n + 1); 
}
int main() {
   int n = 20; 
   double log_fact = log_factorial(n);
   std::cout << "Logarithm of " << n << "! = " << log_fact << std::endl;
   return 0;
}

Output

Following is the output of the above code

Logarithm of 20! = 42.3356

Example 3

In this example, we'll use std::lgamma() to compute the logarithm of the gamma function in a statistical formula for the normal distribution's probability density function (PDF). This shows how lgamma() can be applied in statistical calculations.

#include <iostream>
#include <cmath>
double normal_pdf(double x, double mean, double stddev) {
   double variance = stddev * stddev;
   return (1.0 / (stddev * sqrt(2 * M_PI))) * exp(-((x - mean) * (x - mean)) / (2 * variance));
}
double log_normal_pdf(double x, double mean, double stddev) {
   double variance = stddev * stddev;
   return -0.5 * log(2 * M_PI) - log(stddev) - ((x - mean) * (x - mean)) / (2 * variance);
}
int main() {
   double x = 1.0;
   double mean = 0.0;
   double stddev = 1.0;
   std::cout << "Log-PDF of normal distribution at x = " << x << ": " << log_normal_pdf(x, mean, stddev) << std::endl;
   return 0;
}

Output

If we run the above code it will generate the following output

Log-PDF of normal distribution at x = 1: -1.41894
cpp_cmath.htm
Advertisements