Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 0 additions & 23 deletions Maths/Mean.php

This file was deleted.

125 changes: 125 additions & 0 deletions Maths/MeasuresOfCentralTendency/Mean.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
<?php

declare(strict_types=1);

/** invidual mean
* This function calculates
* The mean value of
* numbers provided
*
* @param decimal $numbers A variable sized number input
* @return decimal $mean Mean of provided numbers
* @throws \Exception
*/
function mean(...$numbers): int|float
{
if ($numbers === []) {
throw new \Exception('Please pass values to find mean value');
}

$total = array_sum($numbers);

return $total / count($numbers);
}

/**
* Calculates the mean of a discrete series.
*
* Formula: Mean = Σ(x * f) / Σf
* Where 'x' is the value and 'f' is its corresponding frequency.
*
* @param array $values The discrete values (x)
* @param array $frequencies The frequencies of the values (f)
* @return int|float Mean of the discrete series
* @throws \Exception
*/
function mean_discrete(array $values, array $frequencies): int|float
{
if (count($values) !== count($frequencies)) {
throw new \Exception('Values and frequencies arrays must have the same length');
}

if (empty($values)) {
throw new \Exception('Please pass values to find mean value');
}

$values = array_values($values);
$frequencies = array_values($frequencies);

foreach ($values as $v) {
if (!is_numeric($v)) {
throw new \Exception('All values must be numeric');
}
}

foreach ($frequencies as $f) {
if (!is_numeric($f) || $f < 0) {
throw new \Exception('All frequencies must be non-negative numeric values');
}
}

$totalFrequency = array_sum($frequencies);

if ($totalFrequency == 0) {
throw new \Exception('Total frequency cannot be zero');
}

$sumProduct = 0;
for ($i = 0; $i < count($values); $i++) {
$sumProduct += $values[$i] * $frequencies[$i];
}

return $sumProduct / $totalFrequency;
}

/**
* Calculates the mean of a continuous series.
*
* Formula: Mean = Σ(m * f) / Σf
* Where 'm' is the midpoint of each class interval, and 'f' is the frequency.
*
* @param array $lower_bounds The lower bounds of the class intervals
* @param array $upper_bounds The upper bounds of the class intervals
* @param array $frequencies The frequencies of the class intervals
* @return int|float Mean of the continuous series
* @throws \Exception
*/
function mean_continuous(array $lower_bounds, array $upper_bounds, array $frequencies): int|float
{
if (count($lower_bounds) !== count($upper_bounds) || count($lower_bounds) !== count($frequencies)) {
throw new \Exception('Lower bounds, upper bounds, and frequencies arrays must have the same length');
}

if (empty($lower_bounds)) {
throw new \Exception('Please pass values to find mean value');
}

$lower_bounds = array_values($lower_bounds);
$upper_bounds = array_values($upper_bounds);
$frequencies = array_values($frequencies);

foreach ($lower_bounds as $lb) {
if (!is_numeric($lb)) {
throw new \Exception('All lower bounds must be numeric');
}
}

foreach ($upper_bounds as $ub) {
if (!is_numeric($ub)) {
throw new \Exception('All upper bounds must be numeric');
}
}

foreach ($frequencies as $f) {
if (!is_numeric($f) || $f < 0) {
throw new \Exception('All frequencies must be non-negative numeric values');
}
}

$midpoints = [];
for ($i = 0; $i < count($lower_bounds); $i++) {
$midpoints[] = ($lower_bounds[$i] + $upper_bounds[$i]) / 2;
}

return mean_discrete($midpoints, $frequencies);
}
195 changes: 195 additions & 0 deletions Maths/MeasuresOfCentralTendency/Median.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
<?php

declare(strict_types=1);

/** indivitaul median

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: typo, "indivitaul" should be "individual" (same in Mean.php line 5, "invidual"). Also, the message on line 158 says "non negative" while the other five say "non-negative".

* This function calculates
* The median value of
* numbers provided
*
* @param float|int $numbers A variable sized number input
* @return float|int $median Median of provided numbers
* @throws \Exception
*/
function median(...$numbers): float|int
{
if ($numbers === []) {
throw new \Exception('Please pass values to find median value');
}

foreach ($numbers as $number) {
if (!is_numeric($number)) {
throw new \Exception('Please pass numeric values to find median value');
}
}

sort($numbers);
$length = count($numbers);
$middle = intdiv($length, 2);

if ($length % 2 == 0) {
return ($numbers[$middle] + $numbers[$middle - 1]) / 2;
}

return $numbers[$middle] + 0;
}

/**
* Calculates the median of a discrete series.
*
* Formula: The value corresponding to the Cumulative Frequency (CF)
* that is just greater than or equal to N / 2, where N = Σf.
*
* @param array $values The discrete values (x)
* @param array $frequencies The frequencies of the values (f)
* @return int|float Median of the discrete series
* @throws \Exception
*/
function median_discrete(array $values, array $frequencies): int|float
{
if (count($values) !== count($frequencies)) {
throw new \Exception('Values and frequencies arrays must have the same length');
}

if (empty($values)) {
throw new \Exception('Please pass values to find median value');
}

$values = array_values($values);
$frequencies = array_values($frequencies);

foreach ($values as $v) {
if (!is_numeric($v)) {
throw new \Exception('All values must be numeric');
}
}

foreach ($frequencies as $f) {
if (!is_numeric($f) || $f < 0) {
throw new \Exception('All frequencies must be non-negative numeric values');
}
}

$totalFrequency = array_sum($frequencies);

if ($totalFrequency == 0) {
throw new \Exception('Total frequency cannot be zero');
}

$data = [];
for ($i = 0; $i < count($values); $i++) {
$data[] = ['value' => $values[$i], 'freq' => $frequencies[$i]];
}
usort($data, fn($a, $b) => $a['value'] <=> $b['value']);

$cumulativeFrequency = 0;
$targetCF = $totalFrequency / 2;
$isEven = $totalFrequency % 2 === 0;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With a fractional total frequency (for example, frequencies [0.5, 1]), % converts the float to an int and PHP 8.1+ reports Implicit conversion from float 1.5 to int loses precision. Frequencies in a discrete series are counts, so please require whole numbers in the frequency validation above, for example by also rejecting values where fmod((float) $f, 1) != 0. A test for that case would be good too.

$prevValue = null;

foreach ($data as $item) {
$cumulativeFrequency += $item['freq'];

if ($isEven) {
if ($cumulativeFrequency > $targetCF) {
if ($cumulativeFrequency - $item['freq'] == $targetCF) {
return ($prevValue + $item['value']) / 2;
}
return $item['value'];
}
if ($cumulativeFrequency == $targetCF && $item['freq'] > 0) {
$prevValue = $item['value'];
}
} else {
if ($cumulativeFrequency >= $targetCF) {
return $item['value'];
}
}
}

throw new \Exception('Could not determine median value');
}

/**
* Calculates the median of a continuous series.
*
* Formula: Median = L + (((N/2) - CF_prev) / f) * h
* Where:
* L = Lower bound of the median class
* N = Total frequency (Σf)
* CF_prev = Cumulative frequency of the class before the median class
* f = Frequency of the median class
* h = Class width (Upper bound - Lower bound)
*
* @param array $lower_bounds The lower bounds of the class intervals
* @param array $upper_bounds The upper bounds of the class intervals
* @param array $frequencies The frequencies of the class intervals
* @return int|float Median of the continuous series
* @throws \Exception
*/
function median_continuous(array $lower_bounds, array $upper_bounds, array $frequencies): int|float
{
if (count($lower_bounds) !== count($upper_bounds) || count($lower_bounds) !== count($frequencies)) {
throw new \Exception('Lower bounds, upper bounds, and frequencies arrays must have the same length');
}

if (empty($lower_bounds)) {
throw new \Exception('Please pass values to find median value');
}

$lower_bounds = array_values($lower_bounds);
$upper_bounds = array_values($upper_bounds);
$frequencies = array_values($frequencies);

foreach ($lower_bounds as $lb) {
if (!is_numeric($lb)) {
throw new \Exception('All lower bounds must be numeric');
}
}

foreach ($upper_bounds as $ub) {
if (!is_numeric($ub)) {
throw new \Exception('All upper bounds must be numeric');
}
}

foreach ($frequencies as $f) {
if (!is_numeric($f) || $f < 0) {
throw new \Exception('All frequencies must be non negative numeric values');
}
}

$totalFrequency = array_sum($frequencies);

if ($totalFrequency == 0) {
throw new \Exception('Total frequency cannot be zero');
}

$data = [];
for ($i = 0; $i < count($lower_bounds); $i++) {
$data[] = [
'L' => $lower_bounds[$i],
'U' => $upper_bounds[$i],
'f' => $frequencies[$i]
];
}
usort($data, fn($a, $b) => $a['L'] <=> $b['L']);

$targetCF = $totalFrequency / 2;
$cumulativeFrequency = 0;
$prevCF = 0;

foreach ($data as $item) {
$cumulativeFrequency += $item['f'];
if ($cumulativeFrequency >= $targetCF) {
$L = $item['L'];
$f = $item['f'];
$h = $item['U'] - $item['L'];

return $L + (($targetCF - $prevCF) / $f) * $h;
}
$prevCF = $cumulativeFrequency;
}

throw new \Exception('Could not determine median value');
}
Loading