A journey with two equal-distance legs at 30 and 60 kilometres per hour does not have an overall speed of 45 kilometres per hour. The slower leg takes more time. Calculate total distance divided by total time, which gives the harmonic mean when every leg covers the same distance.
This tutorial makes that assumption explicit and checks the result against an exact distance-and-time calculation. It also validates every input before calling the statistics function, so an invalid later value cannot be overlooked.
Prerequisites
Use Python 3.12 or later. Save the following program as rates.py. All speeds must use the same unit, and every leg must have the same distance. No scientific packages are required.
Complete example
from fractions import Fraction
from math import isfinite
from statistics import harmonic_mean
def equal_distance_speed(speeds):
if not speeds or any(type(x) not in (int, float) or not isfinite(x) or x <= 0 for x in speeds):
raise ValueError("positive finite speeds required")
return harmonic_mean(speeds)
speeds = [30, 60]
result = equal_distance_speed(speeds)
# Each leg is 60 km: 120 km divided by 3 hours.
physical = Fraction(120, 1) / (Fraction(60, 30) + Fraction(60, 60))
assert result == float(physical) == 40
assert equal_distance_speed([25]) == 25
assert equal_distance_speed([50, 50]) == 50
for bad in [[], [0, -1], [0], [-1], [float('nan')], [float('inf')], [True], ['30']]:
try:
equal_distance_speed(bad)
except ValueError:
pass
else:
raise AssertionError("invalid speed accepted")
print(f"equal-distance speed={result:.2f} km/h")
print("arithmetic mean=45.00 km/h (equal-time interpretation)")
print("physical identity and eight rejection fixtures passed")
Run and expected output
python3 rates.py
equal-distance speed=40.00 km/h
arithmetic mean=45.00 km/h (equal-time interpretation)
physical identity and eight rejection fixtures passed
Derive the result
Choose 60 kilometres for each leg. At 30 kilometres per hour, the first takes two hours. At 60 kilometres per hour, the second takes one hour. The complete journey covers 120 kilometres in three hours, giving 40 kilometres per hour.
The chosen leg distance cancels when distances are equal. For n speeds, the result is n divided by the sum of their reciprocals. The independent Fraction calculation checks the physical identity without repeating the implementation’s call to harmonic_mean.
An arithmetic mean would answer a different question: what is the overall speed when the same amount of time is spent at each speed? Always state which quantity is held equal before selecting an average. The formula alone cannot establish whether the dataset meets its assumptions.
Edge cases and troubleshooting
The helper requires a nonempty list of ordinary integer or floating-point speeds. Boolean values are rejected despite Python’s integer relationship. NaN, infinity, zero, negative values and numeric strings also fail. Convert trusted input formats deliberately before calling the helper; silently coercing arbitrary strings would obscure ingestion errors.
The zero policy is intentionally strict. A zero speed does not describe a completed positive-distance leg in finite time. If your dataset includes stopped time, record elapsed time and distance directly rather than trying to represent every stop as another equal-distance speed.
Python documents an early-zero behavior in harmonic_mean that can affect validation of later values. Validating the entire sequence first makes this application’s policy independent of that behavior. The combined zero-and-negative fixture ensures the invalid sequence is rejected.
For unequal distances, calculate the sum of distances divided by the sum of distance/speed terms, or use an appropriately weighted formulation. For real telemetry, include stopped periods and missing observations according to an explicit measurement policy. This example checks small finite fixtures; extreme floating-point magnitudes and noisy sensor data were not tested.
References and related tutorials
See the official Python statistics documentation for harmonic_mean and its input behavior. Browse data-science tutorials and Python tutorials.