/**
* Gamma function
* https://en.wikipedia.org/wiki/Gamma_function
* https://en.wikipedia.org/wiki/Particular_values_of_the_Gamma_function
*
* For postive integers:
* Γ(n) = (n - 1)!
*
* For half integers:
*
* _ (2n)!
* Γ(½ + n) = √π -------
* 4ⁿ n!
*
* For real numbers: use Lanczos approximation
*
* @param number $n
*
* @return number
*/
public static function gamma($n)
{
// Basic integer/factorial cases
if ($n == 0) {
return \INF;
}
// Negative integer, or negative int as a float (Ex: from beta(-0.1, -0.9) since it will call Γ(x + y))
if ((is_int($n) || is_numeric($n) && abs($n - round($n)) < 1.0E-5) && $n < 0) {
return -\INF;
}
// Positive integer, or postive int as a float (Ex: from beta(0.1, 0.9) since it will call Γ(x + y))
if ((is_int($n) || is_numeric($n) && abs($n - round($n)) < 1.0E-5) && $n > 0) {
return Combinatorics::factorial(round($n) - 1);
}
// Half integer cases (determine if int + 0.5)
if (round($n * 2) / 2 / $n == 1) {
// Compute parts of equation
$π = \M_PI;
$x = round($n - 0.5, 0);
$√π = sqrt($π);
if ($x == 0) {
return $√π;
}
$⟮2n−1⟯‼︎ = Combinatorics::doubleFactorial(2 * $x - 1);
/**
* Put it all together
* _ (2n-1)!!
* √π ---------
* 2ⁿ
*/
return $√π * ($⟮2n−1⟯‼︎ / 2 ** $x);
}
// Generic real number case
return self::gammaLanczos($n);
}