From dc7f73f4ebf231111ed40c25ce49251ef9d9d8a6 Mon Sep 17 00:00:00 2001 From: AkrAm Date: Sat, 2 Dec 2023 00:40:52 +0600 Subject: [PATCH] Add Harmonic Mean Calculation Method --- Number.php | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Number.php b/Number.php index 47d218ff..296191f6 100644 --- a/Number.php +++ b/Number.php @@ -183,6 +183,30 @@ public static function withLocale(string $locale, callable $callback) return tap($callback(), fn () => static::useLocale($previousLocale)); } + /** + * Calculate the harmonic mean of a set of numbers. + * + * @param int|float ...$numbers An indefinite number of numeric arguments + * @return float Harmonic mean of the numbers + * @throws InvalidArgumentException If the arguments are empty, non-numeric, or contain zero values. + */ + public static function harmonize(int|float ...$numbers): float + { + if (empty($numbers)) { + throw new InvalidArgumentException("Arguments cannot be empty"); + } + + $sumOfReciprocals = 0; + foreach ($numbers as $number) { + if (!is_numeric($number) || $number <= 0) { + throw new InvalidArgumentException("All elements must be positive numbers"); + } + $sumOfReciprocals += 1 / $number; + } + + return count($numbers) / $sumOfReciprocals; + } + /** * Set the default locale. *