note 42003 modified in ref.math by felipe

From: Date: Mon, 04 Feb 2008 20:25:44 +0000
Subject: note 42003 modified in ref.math by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-135773@lists.php.net to get a copy of this message
Please note that shorter is not always better (meaning that really short faculty implementation above). In my opinion, a clearer way to code this is, including a check for negative or non-integer values. In order to calculate the faculty of a positive integer, an iterative way (which might be harder to understand) is usually a bit faster, but I am using it only for small values so it is not really important to me: <?php // Calculate the Faculty of a positive int-value function iFaculty($a_iFac) { if ($a_iFac > 0) { return $a_iFac * $this->iFaculty($a_iFac - 1); } elseif ($a_iFac == 0) { return 1; } else { return 0; // Wrong argument! } } ?> I've also written another function to calculate the binomial coefficient of 2 values, I didn't find it anywhere yet so I hope it might help someone (works fine with the above stated faculty-function and ready to be used inside of your own classes!) <?php // calculates the binomial coefficient "n over k" of 2 positive int values // for n >= k function iBinCoeff($a_iN, $a_iK) { // the binomial coefficient is defined as n! / [ (n-k)! * k! ] return $this->iFaculty($a_iN) / ($this->iFaculty($a_iN - $a_iK) * $this->iFaculty($a_iK)); } ?> --was-- Please note that shorter is not always better (meaning that really short faculty implementation above). In my opinion, a clearer way to code this is, including a check for negative or non-integer values. In order to calculate the faculty of a positive integer, an iterative way (which might be harder to understand) is usually a bit faster, but I am using it only for small values so it is not really important to me: <?php // Calculate the Faculty of a positive int-value function iFaculty($a_iFac) { if ($a_iFac > 0) { return $a_iFac * $this->iFaculty($a_iFac - 1); } elseif ($a_iFac == 0) { return 1; } else { return 0; // Wrong argument! } } ?> I've also written another function to calculate the binomial coefficient of 2 values, I didn't find it anywhere yet so I hope it might help someone (works fine with the above stated faculty-function and ready to be used inside of your own classes!) <?php // calculates the binomial coefficient "n over k" of 2 positive int values // für n >= k function iBinCoeff($a_iN, $a_iK) { // the binomial coefficient is defined as n! / [ (n-k)! * k! ] return $this->iFaculty($a_iN) / ($this->iFaculty($a_iN - $a_iK) * $this->iFaculty($a_iK)); } ?> http://php.net/manual/en/ref.math.php

« previous php.notes (#135773) next »