Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรมหาค่าเฉลี่ยแบบฮาร์มอนิก (Harmonic Mean) ใน C++

Harmonic Mean (HM) คือ ค่าผกผันของค่าเฉลี่ยเลขคณิตของค่าผกผัน

สูตร

HM = n / (Σ 1/xᵢ)

โดยที่:

  • n = จำนวนข้อมูล
  • xᵢ = ข้อมูลแต่ละตัว (ต้อง > 0)

ความสัมพันธ์ของ Means (สำหรับข้อมูลบวกทั้งหมด)

Harmonic Mean ≤ Geometric Mean ≤ Arithmetic Mean

ความเท่ากันเกิดก็ต่อเมื่อข้อมูลทุกตัวเท่ากัน

ตัวอย่าง

ตัวอย่างที่ 1

Input: {2.0, 3.4, 5.3, 2.1}

คำนวณ:

1/2.0   = 0.50000
1/3.4   = 0.29412
1/5.3   = 0.18868
1/2.1   = 0.47619
Sum     = 1.45899
HM = 4 / 1.45899 = 2.74163

Output: 2.74163

ตัวอย่างที่ 2

Input: {13.5, 14.5, 14.8, 15.2, 16.1}

Output: 14.7707

ตัวอย่างโค้ด

#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;

double harmonicMean(const vector<double>& arr) {
    double sumReciprocal = 0;
    for (double x : arr) {
        if (x <= 0) {
            throw invalid_argument("All values must be positive for harmonic mean");
        }
        sumReciprocal += 1.0 / x;
    }
    return arr.size() / sumReciprocal;
}

int main() {
    vector<double> arr1 = {2.0, 3.4, 5.3, 2.1};
    cout << fixed << setprecision(5);
    cout << "Harmonic Mean: " << harmonicMean(arr1) << endl;  // 2.74163
    
    vector<double> arr2 = {13.5, 14.5, 14.8, 15.2, 16.1};
    cout << "Harmonic Mean: " << harmonicMean(arr2) << endl;  // 14.7707
    
    return 0;
}

การประยุกต์ใช้งานจริง

ตัวอย่าง: ความเร็วเฉลี่ย

รถเดินทาง 60 km/h เป็นระยะ 60 km แล้ว 40 km/h เป็นระยะ 60 km

เวลารวม = 1 + 1.5 = 2.5 ชม. ระยะรวม = 120 km

ความเร็วเฉลี่ย = 120/2.5 = 48 km/h

HM ของ 60 และ 40 = 2/(1/60+1/40) = 48 ✓

ค่าเฉลี่ยเลขคณิต (50 km/h) จะผิด เพราะไม่คำนึงถึงเวลาที่ใช้ต่างกัน

ความซับซ้อน

  • เวลา: O(n)
  • พื้นที่: O(1)

ข้อควรระวัง

  • ข้อมูลต้องเป็น จำนวนบวกทั้งหมด (หารด้วย 0 ไม่ได้, ลบไม่ได้)
  • หากมีค่า 0 หรือลบ → HM ไม่ได้นิยาม (หรือถือเป็น 0)
  • ความแม่นยำ: ใช้ double หรือ long double สำหรับการหาร
สาขาการใช้งาน
Physicsความเร็วเฉลี่ย (Average speed) = ระยะทางรวม / เวลารวม = HM ของความเร็วแต่ละช่วง
FinancePrice-Earnings Ratio เฉลี่ยของพอร์ตโฟลิโอ
Electronicsความต้านทานขนาน (Parallel resistance): 1/R = Σ 1/Rᵢ
Computer ScienceF1 Score = 2 × Precision × Recall / (Precision + Recall) = HM ของ Precision และ Recall
Statisticsค่าเฉลี่ยของอัตรา (Rates) และอัตราส่วน (Ratios)