Skip to content

Commit

Permalink
Merge pull request #66 from keatis/main
Browse files Browse the repository at this point in the history
Fixed median() to handle unsorted data. Minor text changes for consistency
  • Loading branch information
roberto-butti authored Dec 26, 2023
2 parents 841a367 + 40291cf commit 813a9fa
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
3 changes: 2 additions & 1 deletion src/Stat.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ public static function mean(array $data): int|float|null
*/
public static function median(array $data, string $medianType = self::MEDIAN_TYPE_MIDDLE): mixed
{
sort($data);
$count = self::count($data);
if ($count === 0) {
throw new InvalidDataInputException('The data must not be empty.');
Expand Down Expand Up @@ -170,7 +171,7 @@ public static function multimode(array $data): array|null
*/
public static function quantiles(array $data, int $n = 4, ?int $round = null): array
{
$count = Stat::count($data);
$count = self::count($data);
if ($count < 2 || $n < 1) {
throw new InvalidDataInputException(
'The size of the data must be greater than 2 and the number of quantiles must be greater than 1.'
Expand Down
20 changes: 16 additions & 4 deletions tests/StatTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use HiFolks\Statistics\Exception\InvalidDataInputException;
use HiFolks\Statistics\Stat;

it('can calculate mean (static)', function () {
it('calculates mean (static)', function () {
expect(
Stat::mean([1, 2, 3, 4, 4])
)->toEqual(2.8);
Expand All @@ -15,35 +15,47 @@
)->toThrow(InvalidDataInputException::class);
});

it('can calculate median (static)', function () {
it('calculates median (static)', function () {
expect(
Stat::median([1, 3, 5])
)->toEqual(3);
expect(
Stat::median([1, 3, 5, 7])
)->toEqual(4);
expect(
Stat::median([1001, 999, 998, 1001, 1002])
)->toEqual(1001);
expect(
Stat::median([1001, 999, 998, 1003, 1002, 1003])
)->toEqual(1001.5);
expect(
fn() => Stat::median([])
)->toThrow(InvalidDataInputException::class);
});
it('can calculate median low (static)', function () {
it('calculates median low (static)', function () {
expect(
Stat::medianLow([1, 3, 5])
)->toEqual(3);
expect(
Stat::medianLow([1, 3, 5, 7])
)->toEqual(3);
expect(
Stat::medianLow([1001, 999, 998, 1003, 1002, 1003])
)->toEqual(1001);
expect(
fn() => Stat::medianLow([])
)->toThrow(InvalidDataInputException::class);
});
it('can calculate median high (static)', function () {
it('calculates median high (static)', function () {
expect(
Stat::medianHigh([1, 3, 5])
)->toEqual(3);
expect(
Stat::medianHigh([1, 3, 5, 7])
)->toEqual(5);
expect(
Stat::medianHigh([1001, 999, 998, 1003, 1002, 1003])
)->toEqual(1002);
expect(
fn() => Stat::medianHigh([])
)->toThrow(InvalidDataInputException::class);
Expand Down

0 comments on commit 813a9fa

Please sign in to comment.