Maths functions

Array sum – array_sum()

Adds together the elements in an array.  PHP already has a built-in function.

C

Input array followed by number of elements in array.

double array_sum(float array[], int amount)
{
	int i;
	double sum = 0;

	for(i = 0; i < (amount - 1); i++)
	{
		sum += array[i];
	}

	return sum;
}

Factorial – factorial()

The product of all positive integers less than or equal to n (n!).

C

double factorial(int number)
{
	int i;
	double factorial = 1;

	for(i = 1; i <= number; i++)
	{
		factorial *= i;
	}

	return factorial;
}

PHP

function factorial($number)
{
	$factorial = 1;

	for(i = 1; i <= number; i++)
	{
		$factorial *= $i++;
	}

	return $factorial;
}

Standard deviation – stndev()

A measure of diversity in a set of numbers.

C

This function uses the array_sum() function, so ensure that you include it (earlier on in this page)!  Additionally, you must also include the math.h header file.

double array_sum(float array[], int amount);

float stndev(float set[], int amount)
{
	int i;
	float mean = 0;
	float diff[amount];

	mean = array_sum(set, amount) / amount;

	for(i = 0; i < (amount - 1); i++)
	{
		diff[i] = pow(set[i] - mean, 2);
	}

	return pow(array_sum(diff, amount) / amount, 0.5);
}

PHP

function stndev($set)
{
	$amount = count($set);
	$mean = array_sum($set) / $amount;

	foreach($set as $value)
	{
		$difference[] = pow($value - $mean, 2);
	}

	return pow(array_sum($difference) / $amount, 0.5);
}

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>