Skip to content

feat(maths): implement discrete and continuous series for Mean and Median algorithms - #197

Open
mrfiiqane wants to merge 2 commits into
TheAlgorithms:masterfrom
mrfiiqane:master
Open

mrfiiqane wants to merge 2 commits into
TheAlgorithms:masterfrom
mrfiiqane:master

Conversation

@mrfiiqane

Copy link
Copy Markdown

This Pull Request expands the statistical algorithms in the repository by adding support for Discrete and Continuous series to both the Mean and Median calculations. Previously, only the Individual series were supported.

Changes included:

Added mean_discrete and mean_continuous functions to Mean.php
Added median_discrete and median_continuous functions to Median.php
Added mathematical formulas
Implemented unit tests
All code has been formatted according to PSR-12 and strict typing has been used throughout.

…dian

- Added mean_discrete and mean_continuous functions in Maths/Mean.php

- Added median_discrete and median_continuous functions in Maths/Median.php

- Included explicit inline documentation and mathematical formula comments for all new functions

- Implemented comprehensive PHPUnit test cases in tests/Maths/MathsTest.php to validate expected output and edge cases

@darwinz darwinz left a comment

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.

Thanks for the contribution, the formulas and docblocks are clear!

I merged this against current master locally. The tests pass, but vendor/bin/phpcs -n reports 7 errors (CI will fail), and median_discrete returns the wrong result when a value has frequency 0. The details are in the inline comments; the main items are the lint errors, the zero-frequency bug, input validation, and a few more tests.

You can check locally with composer test and vendor/bin/phpcs -n. Thanks!

Comment thread Maths/Median.php Resolved
Comment thread Maths/Median.php Resolved
Comment thread Maths/Median.php Resolved
Comment thread Maths/Mean.php Resolved
Comment thread tests/Maths/MathsTest.php Resolved

@darwinz darwinz left a comment

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.

Marking this as changes requested so it isn't merged before the items in my review above are addressed. Please see the inline comments there.

@mrfiiqane

Copy link
Copy Markdown
Author

Hi @darwinz, thank you for the detailed review

Bug fixes:

Fixed zero-frequency bug in median_discrete by adding $item['freq'] > 0 guard
Removed unreachable if ($f == 0) continue in median_continuous
Replaced return 0 fallback with throw new \Exception(...) in both median functions
Code quality:

Added array_values() to all four new functions to handle non-list keys
Added full input validation (numeric values, non-negative frequencies) to all new functions
Removed the misleading comment from median()
Fixed all 7 trailing-whitespace lint errors (vendor/bin/phpcbf)
Tests added:

Exception tests: mismatched arrays, empty input, zero total frequency — for all new functions
Zero-frequency edge case for median_discrete
Unsorted input cases for all functions
Added mode_discrete and mode_continuous to Mode.php (matching the pattern of Mean and Median)
Restructured files into Maths/MeasuresOfCentralTendency/ subfolder with real-world notebook examples included as reference images.

All tests pass (composer run-script test) and vendor/bin/phpcs -n reports 0 errors

                                                        Thanks

@darwinz darwinz left a comment

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.

Thanks for the quick follow-up! All eight points from the first review are addressed, and the zero-frequency case in median_discrete is fixed.

The second commit also added several things that weren't part of the review, so a few more changes are needed before this can be merged:

  • Please remove composer.phar and the images/ folder.
  • Please move the three files back to Maths/Mean.php, Maths/Median.php and Maths/Mode.php.
  • vendor/bin/phpcs -n still reports one error (trailing whitespace in tests/Maths/MathsTest.php).
  • The new mode_discrete and mode_continuous functions can stay in this PR. They need a couple of fixes, and please update the PR title and description to mention them.

The details are in the inline comments. You can check locally with composer test and vendor/bin/phpcs -n. Thanks!

Comment thread tests/Maths/MathsTest.php
Comment on lines +20 to +22
require_once __DIR__ . '/../../Maths/MeasuresOfCentralTendency/Mean.php';
require_once __DIR__ . '/../../Maths/MeasuresOfCentralTendency/Median.php';
require_once __DIR__ . '/../../Maths/MeasuresOfCentralTendency/Mode.php';

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.

Please revert the move into Maths/MeasuresOfCentralTendency/ and keep the files at Maths/Mean.php, Maths/Median.php and Maths/Mode.php. The move wasn't part of the review, it breaks the existing paths for anyone who requires these files, and it loses their git history. The new functions can go into the existing files.

Comment thread tests/Maths/MathsTest.php
mean_continuous([0, 5], [5, 10], [10, 20])
);

// Unsorted input

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.

Trailing whitespace on this line. It's the one error vendor/bin/phpcs -n still reports for the changed files, and the Code style check will fail on it.

Comment thread tests/Maths/MathsTest.php
Comment on lines +199 to +203
public function testMeanDiscreteExceptionZeroTotalFrequency()
{
$this->expectException(\Exception::class);
mean_discrete([1, 2], [0, 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.

The new validation isn't covered by tests yet. Could you add tests for a non-numeric value, a negative frequency, and non-list keys (for example, mean_discrete(['a' => 10, 'b' => 20], [1, 1]) should return 15)? A few representative cases are enough; they don't need to be repeated for every function.

Comment on lines +20 to +24
foreach ($numbers as $number) {
if (!is_numeric($number)) {
throw new \Exception('All values must be numeric');
}
}

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.

This changes the behaviour of the existing mode() function: on master, mode('a', 'b', 'a') returns ['a'], and with this check it throws. The mode is well defined for non-numeric data, so please leave mode() as it was.

Comment on lines +153 to +158
for ($i = 0; $i < count($data); $i++) {
if ($data[$i]['f'] == $maxFreq) {
$modalIndex = $i;
break;
}
}

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.

If several classes share the highest frequency, this silently uses the lowest one. Please document that in the docblock and add a test for it. For example, mode_continuous([0, 10, 20], [10, 20, 30], [5, 2, 5]) gives 6.25 with the current logic.

Comment on lines +166 to +170
$denominator = 2 * $f1 - $f0 - $f2;

if ($denominator == 0) {
throw new \Exception('Cannot determine mode: denominator is zero (ambiguous modal class)');
}

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.

This exception can never be thrown. $modalIndex is the first class with the highest frequency, so the class before it always has a strictly lower frequency (or there is no class before it and $f0 is 0). That means $f1 - $f0 > 0, and since $f1 >= $f2, the denominator is always positive. Please remove this check. The -1 start value of $modalIndex on line 151 is never used either.


$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.


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".

Comment thread composer.phar

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.

Please remove this file. It is the Composer 2.10.2 binary (3.6 MB), and it looks like it was committed by accident. Composer should be installed on the machine, not checked into the repo.

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.

Please remove the images/ folder (this applies to all eight files). Thank you for sharing the worked examples, but photos of notes don't belong in the repo, and nothing references them. The examples you turned into test cases are the right way to keep them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants