Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Harmonic Mean Calculation in Number Class #102

Closed
wants to merge 1 commit into from
Closed
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
24 changes: 24 additions & 0 deletions Number.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
Loading