Python: Average multiplicative factors with geometric_mean
For positive scaling factors applied in sequence, statistics.geometric_mean() gives the constant factor that represents their average multiplicative effect. A doubling followed by a halving has a combined factor of one, even though the arithmetic mean of those two factors is 1.25.
Tested on Linux with Python 3.12.14. Use Python 3.12 for this example, including its zero-input behavior. The example uses only the standard library and requires no network access.
Run the example
Save this as factor_average.py in an empty working directory:
from math import prod
from statistics import StatisticsError, fmean, geometric_mean
factors = [2.0, 0.5]
print(f"Arithmetic mean: {fmean(factors):.2f}")
print(f"Geometric mean: {geometric_mean(factors):.2f}")
print(f"Combined factor: {prod(factors):.2f}")
try:
geometric_mean([1.0, 0.0])
except StatisticsError:
print("Zero factor: rejected")Run it without -O so any assertions remain enabled:
python3 factor_average.pyCaptured output:
Arithmetic mean: 1.25
Geometric mean: 1.00
Combined factor: 1.00
Zero factor: rejectedThe geometric mean is 1.00, consistent with two unchanged-size steps having the same combined factor as doubling and halving. In Python 3.12, the zero example is rejected: the function requires positive data and also rejects an empty input.
Limits and cleanup
The calculation converts inputs to floating point and is approximate. Use this model for multiplicative factors; it does not replace an arithmetic average of additive measurements. Validate your application’s permitted numeric values separately, including any policy on non-finite values.
After testing, remove the example script from its working directory:
rm -- factor_average.pyReference
Acknowledgements
This post was created with assistance from AI.