I have extracted this piece of code from PHPExcel. The code is used to calculate the normal distribution and it consists of 4 functions (I think). I've put comments in the code, to make it clear.
Unfortunately for me, this code is written in a Class and I genuinely have no Idea how to use this. When I use this code in a browser I am inputting numbers in the $value, $mean, $stdDev, $cumulative variables but I don't know how to get them into the class, and afterwards return the result. Can you maybe help me? I've been reading a bit about classes but I keep getting errors.
The code alone does not throw any errors and I've been proof reading it, at least to the extend that I am capable of.
I hope this is understandable and I would be grateful if someone could help me making this work. Thanks.
Code: Select all
class Calculation_Function {
// I do not know what to call this first piece of code but it is used in the NORMDIST function further down the page
private static $_errorCodes = array(
'null' => '#NULL!',
'divisionbyzero' => '#DIV/0!',
'value' => '#VALUE!',
'reference' => '#REF!',
'name' => '#NAME?',
'num' => '#NUM!',
'na' => '#N/A',
'gettingdata' => '#GETTING_DATA'
);
// I think this is just statics used for calculating the following error function
private static $_two_sqrtpi = 1.128379167095512574;
private static $_rel_error = 1E-15;
//This is the error function used in the NORMDIST() function further down the page
private static function _erfVal($x) {
if (abs($x) > 2.2) {
return 1 - self::_erfcVal($x);
}
$sum = $term = $x;
$xsqr = pow($x,2);
$j = 1;
do {
$term *= $xsqr / $j;
$sum -= $term / (2 * $j + 1);
++$j;
$term *= $xsqr / $j;
$sum += $term / (2 * $j + 1);
++$j;
if ($sum == 0) {
break;
}
} while (abs($term / $sum) > self::$_rel_error);
return self::$_two_sqrtpi * $sum;
} // function _erfVal()
// I am not sure what this function does but it is used in the NORMDIST() function further down the page
public static function flattenSingleValue($value = '') {
if (is_array($value)) {
$value = self::flattenSingleValue(array_pop($value));
}
return $value;
} // function flattenSingleValue()
//Function used to calculate the normal distribution THIS IS WHERE THE MAGIC HAPPENS
public static function NORMDIST($value, $mean, $stdDev, $cumulative) {
$value = self::flattenSingleValue($value);
$mean = self::flattenSingleValue($mean);
$stdDev = self::flattenSingleValue($stdDev);
if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
if ($stdDev < 0) {
return self::$_errorCodes['num'];
}
if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
if ($cumulative) {
return 0.5 * (1 + self::_erfVal(($value - $mean) / ($stdDev * sqrt(2))));
} else {
return (1 / (SQRT2PI * $stdDev)) * exp(0 - (pow($value - $mean,2) / (2 * pow($stdDev,2))));
}
}
}
return self::$_errorCodes['value'];
} // function NORMDIST()
} // class Calculation_Function