diff --git a/src/Stat.php b/src/Stat.php index 214bec0..9178f1f 100644 --- a/src/Stat.php +++ b/src/Stat.php @@ -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.'); @@ -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.' diff --git a/tests/StatTest.php b/tests/StatTest.php index ec6b782..f1674db 100644 --- a/tests/StatTest.php +++ b/tests/StatTest.php @@ -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); @@ -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);