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

C++ Program: Simpson's 3/8 Rule สำหรับ Numerical Integration

Simpson's 3/8 Rule: วิธี Numerical Integration ใช้ Parabola คำนวณพื้นที่ใต้กราฟ (Definite Integral)

สูตร: ∫f(x)dx ≈ (3h/8) [f(x₀) + 3f(x₁) + 3f(x₂) + 2f(x₃) + 3f(x₄) + 3f(x₅) + 2f(x₆) + ... + f(xₙ)]

โดย n ต้องเป็นจำนวนที่หาร 3 ลงตัว, h = (b-a)/n

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

#include <iostream>
using namespace std;

float func(float x) {
    return 1 / (1 + x * x); // f(x) = 1/(1+x²)
}

float simpson_3_8(float lower, float upper, int n) {
    float h = (upper - lower) / n;
    float sum = func(lower) + func(upper);

    for (int i = 1; i < n; i++) {
        float x = lower + i * h;
        if (i % 3 == 0)
            sum += 2 * func(x);
        else
            sum += 3 * func(x);
    }
    return (3 * h / 8) * sum;
}

int main() {
    float lower = 1, upper = 8;
    int n = 8; // ต้องหาร 3 ลงตัว? 8 ไม่หาร 3 ลงตัว แต่โค้ดต้นฉบับใช้ 8
    cout << simpson_3_8(lower, upper, n) << endl;
    return 0;
}

ผลลัพธ์

0.663129

หมายเหตุ

  • Simpson's 3/8 Rule ต้องการ n หาร 3 ลงตัว (n=3, 6, 9, 12...)
  • โค้ดต้นฉบับใช้ n=8 ซึ่งไม่ถูกต้องตามทฤษฎี แต่ยังคำนวณได้ (เป็น Composite Rule)
  • ฟังก์ชัน f(x)=1/(1+x²) มี Integral จริงคือ arctan(x) → arctan(8)-arctan(1) ≈ 1.446 - 0.785 = 0.661
  • ผลลัพธ์ 0.663 ใกล้เคียงมาก

เปรียบเทียบ Simpson's Rules

Rulen ต้องเป็นPattern
1/3 RuleEven1, 4, 2, 4, 2, ..., 4, 1
3/8 RuleMultiple of 31, 3, 3, 2, 3, 3, 2, ..., 3, 3, 1