Validate every rate before computing a harmonic mean
For two equal-distance legs, the overall speed comes from total distance divided by total time. A harmonic mean gives that result, but rate validation must cover the entire input before calculation.
Run the example
Tested on Linux with Python 3.12.14. No third-party packages are required. In one Bash session, create a disposable directory:
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Save this as demo_python_harmonic_mean_validate_rates.py. Use that filename to avoid shadowing a standard-library module.
from math import isfinite
from statistics import harmonic_mean, mean
def positive_rate_average(values):
rates = tuple(values)
if not rates or any(not isfinite(x) or x <= 0 for x in rates):
raise ValueError("rates must be finite, positive, and nonempty")
return harmonic_mean(rates)
rates = [30.0, 60.0]
print("equal-distance average:", positive_rate_average(rates))
print("arithmetic average:", mean(rates))
print("raw zero-first result:", harmonic_mean([0.0, -5.0]))
for values in ([0.0, -5.0], [30.0, float("inf")], []):
try:
positive_rate_average(values)
except ValueError as error:
print(error)Run it:
python3 demo_python_harmonic_mean_validate_rates.pyOutput:
equal-distance average: 40.0
arithmetic average: 45.0
raw zero-first result: 0
rates must be finite, positive, and nonempty
rates must be finite, positive, and nonempty
rates must be finite, positive, and nonemptyAt 30 and 60 distance units per hour, equal-distance legs average 40, not 45. The raw zero-first example demonstrates the documented early return: a zero can prevent later inputs from being checked. The wrapper validates all rates first and rejects zero because this application requires each leg to finish in finite time.
Input policy and limits
The wrapper assumes real numeric inputs and a bounded iterable. Equal-time observations call for an arithmetic average; unequal distances require weights or an explicit total-distance/total-time calculation. Decide those units and weights before choosing the function.
Clean up
In the same Bash session, remove the source file and the empty working directory:
rm -- demo_python_harmonic_mean_validate_rates.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirIf the directory is not empty, inspect its contents before deleting anything else.
References
Acknowledgements
This post was created with assistance from AI.