🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Harmonic Mean — When Average Rate Requires Harmonic Mean

Foundations of StatisticsDescriptive Statistics🟢 Free Lesson

Harmonic Mean

Descriptive Statistics

When Average Rate Requires a Different Kind of Mean

The harmonic mean is the reciprocal of the arithmetic mean of reciprocals. It is the appropriate average when combining rates, speeds, or ratios where the denominator is the common reference.

  • Average speed — Driving equal distances at different speeds? The harmonic mean gives the true average
  • Portfolio analysis — Equal-dollar averaging produces harmonic, not arithmetic, returns
  • Rate problems — When the denominator is fixed, the harmonic mean is the correct center
  • Relationship to other means — Always less than or equal to the geometric and arithmetic means

The harmonic mean is the mean you never learned in school — and the one you need for rates.


What is the Harmonic Mean?

Definition

The harmonic mean is the reciprocal of the arithmetic mean of reciprocals. It is the appropriate average when combining rates, speeds, or ratios where the denominator is the common reference.

The Classic Speed Problem

python
import numpy as np
from scipy.stats import hmean
import pandas as pd

# ==========================================
# Example 1: Average speed
# ==========================================
speeds = [60, 40]  # km/h for equal distances

# Arithmetic mean (wrong!)
arith_speed = np.mean(speeds)

# Harmonic mean (correct for equal distances)
harm_speed = hmean(speeds)

# Verify directly
time_leg1 = 100 / 60  # hours
time_leg2 = 100 / 40  # hours
total_distance = 200   # km
total_time = time_leg1 + time_leg2
actual_avg_speed = total_distance / total_time

print(f"Speed leg 1: {speeds[0]} km/h, Speed leg 2: {speeds[1]} km/h")
print(f"Arithmetic mean: {arith_speed:.4f} km/h <- WRONG")
print(f"Harmonic mean:   {harm_speed:.4f} km/h <- CORRECT")
print(f"Calculated directly: {actual_avg_speed:.4f} km/h ✓")

# ==========================================
# Example 2: P/E Ratios in Finance
# ==========================================
# For equal-dollar investments, harmonic mean of P/E ratios
pe_ratios = [20, 25, 15, 30, 10]
portfolio_pe_harm = hmean(pe_ratios)
portfolio_pe_arith = np.mean(pe_ratios)

print(f"\nP/E Ratios: {pe_ratios}")
print(f"Arithmetic mean P/E: {portfolio_pe_arith:.2f}")
print(f"Harmonic mean P/E:   {portfolio_pe_harm:.2f}")
print("(Harmonic mean is correct for equal-dollar portfolio weighting)")

# ==========================================
# Example 3: F1-Score in Machine Learning
# ==========================================
# F1 = harmonic mean of Precision and Recall
precision = 0.80
recall = 0.60

f1_hmean = hmean([precision, recall])
f1_formula = 2 * precision * recall / (precision + recall)
arith_mean = np.mean([precision, recall])

print(f"\nPrecision: {precision:.2f}, Recall: {recall:.2f}")
print(f"Arithmetic mean: {arith_mean:.4f}")
print(f"F1 Score (harmonic mean): {f1_hmean:.4f}")
print(f"F1 via standard formula:  {f1_formula:.4f}")
print("F1 score punishes large imbalances between P and R!")

Relationship: AM ≥ GM ≥ HM

with equality only when all values are identical.

python
np.random.seed(42)
for trial in range(5):
    x = np.random.uniform(1, 50, 8)
    am = np.mean(x)
    gm = np.exp(np.log(x).mean())
    hm = hmean(x)
    print(f"AM={am:.3f} ≥ GM={gm:.3f} ≥ HM={hm:.3f}: {am >= gm >= hm}")

When Each Mean Is Appropriate

MeanFormulaUse When
ArithmeticΣxᵢ/nAdditive quantities (prices, temperatures)
Geometric(∏xᵢ)^(1/n)Multiplicative quantities (growth rates, ratios)
Harmonicn/Σ(1/xᵢ)Rates when denominator is fixed (speed, price per unit)

Harmonic Mean in Machine Learning

ML ApplicationWhy Harmonic MeanHow
F1 ScoreBalances precision and recallF1 = 2 × (P × R) / (P + R)
Token throughputRate with fixed denominatorTokens per second across models
Batch processingRate per batchImages per second (fixed batch size)
Cross-entropyNegative log — harmonic structure-log(p) has harmonic-like properties
python
import numpy as np
from scipy.stats import hmean

# F1 score IS the harmonic mean of precision and recall
precision, recall = 0.8, 0.6
f1 = 2 * (precision * recall) / (precision + recall)
f1_hmean = hmean([precision, recall])
print(f"Precision: {precision}")
print(f"Recall:    {recall}")
print(f"F1 (manual): {f1:.4f}")
print(f"F1 (hmean):  {f1_hmean:.4f}")
print(f"F1 is the harmonic mean of precision and recall!\n")

# Why harmonic mean? Because P and R have same "denominator" (total samples)
# Arithmetic mean would overestimate: (0.8+0.6)/2 = 0.7
# Harmonic mean is conservative: 2(0.8)(0.6)/(0.8+0.6) = 0.6857
print(f"Arithmetic mean of P and R: {(precision+recall)/2:.4f} (overestimates)")
print(f"Harmonic mean of P and R:   {f1:.4f} (conservative, correct)")

# Token throughput example
model_a_tokens = np.array([120, 150, 130])  # tokens/sec for 3 batches
model_b_tokens = np.array([200, 50, 180])
print(f"\nModel A: {model_a_tokens}")
print(f"  Arithmetic mean: {np.mean(model_a_tokens):.1f} tokens/sec")
print(f"  Harmonic mean:   {hmean(model_a_tokens):.1f} tokens/sec (better for rates)")

Key Takeaways


Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Statistics Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement