MathPHP\Probability\Combinatorics::doubleFactorial PHP Метод

doubleFactorial() публичный статический Метод

The product of all the integers from 1 up to some non-negative integer n that have the same parity as n. Denoted by n!! n‼︎ = n(n - 2)(n - 4) ・・・ For even n: n/2 n‼︎ = ∏ (2k) = n(n - 2) ・・・ 2 k=1 For odd n: (n+1)/2 n‼︎ = ∏ (2k - 1) = n(n - 2) ・・・ 1 k=1 0‼︎ = 1
public static doubleFactorial ( integer $n ) : integer
$n integer
Результат integer
    public static function doubleFactorial(int $n)
    {
        if ($n < 0) {
            throw new Exception\OutOfBoundsException('Cannot compute double factorial of a negative number.');
        }
        // Zero base case
        if ($n === 0) {
            return 1;
        }
        // Even and odd initialization base cases: odd = 1, even = 2
        if ($n % 2 == 0) {
            $n‼︎ = 2;
        } else {
            $n‼︎ = 1;
        }
        while ($n > 2) {
            $n‼︎ *= $n;
            $n -= 2;
        }
        return $n‼︎;
    }

Usage Example

Пример #1
0
 /**
  * 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);
 }