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

การประมาณค่าด้วย Bessel's Interpolation ใน C++


Interpolation (การประมาณค่าระหว่างจุด) เป็นเทคนิคประมาณค่าที่ไม่ทราบซึ่งอยู่ระหว่างค่าที่รู้จัก กระบวนการสร้างจุดข้อมูลใหม่ระหว่างช่วงของชุดข้อมูลที่รู้จักและเป็น дискрет

เหตุผลในการใช้ Interpolation: อาจลดต้นทุนการคำนวณ เมื่อสูตร (ฟังก์ชัน) สำหรับคำนวณค่าบางอย่างซับซ้อนหรือค่าใช้จ่ายสูง เราจะคำนวณจุดข้อมูลบางจุดด้วยฟังก์ชันจริง ส่วนที่เหลือประมาณด้วย Interpolation ผลลัพธ์อาจไม่แม่นยำ 100% แต่เพียงพอและเร็วกว่า

สูตร Bessel's Interpolation

f(u) = {(f(0)+f(1))/2} + {u - ½}Δf(0) + {u(u-1)/2!}{(Δ²f(-1) + Δ²f(0))/2} + {u(u-1)(u-½)/3!}Δ³f(-1) + {u(u+1)(u-1)(u-2)/4!}{(Δ⁴f(-2) + Δ⁴f(-1))/2} + ...

โดยที่:

  • f(0) คือจุดกำเนิด (origin) ซึ่งมักเป็นจุดกลาง
  • u = (x - f(0)) / h, โดย h คือช่วงห่างของความต่าง

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

#include <iostream>
using namespace std;

float calU(float u, int n) {
    if (n == 0) return 1;
    float result = u;
    for (int i = 1; i <= n / 2; i++)
        result = result * (u - i);
    for (int i = 1; i < n / 2; i++)
        result = result * (u + i);
    return result;
}

int factorial(int n) {
    if (n == 1) return 1;
    return n * factorial(n - 1);
}

int main() {
    int n = 6;
    float x[] = { 50, 51, 52, 53, 54, 55 };
    float y[n][n];
    
    y[0][0] = 8.000;
    y[1][0] = 7.746;
    y[2][0] = 7.674;
    y[3][0] = 7.571;
    y[4][0] = 7.469;
    y[5][0] = 7.231;
    
    // สร้างตารางความต่าง (difference table)
    for (int i = 1; i < n; i++)
        for (int j = 0; j < n - i; j++)
            y[j][i] = y[j + 1][i - 1] - y[j][i - 1];
    
    float value = 53.2;
    float sum = (y[2][0] + y[3][0]) / 2;
    
    int index = (n % 2) ? n/2 : n/2 - 1;
    float u = (value - x[index]) / (x[1] - x[0]);
    
    for (int i = 1; i < n; i++) {
        if (i % 2)
            sum += (((u - 0.5) * calU(u, i - 1) * y[index][i]) / factorial(i));
        else
            sum += ((calU(u, i) * (y[index][i] + y[--index][i]) / (factorial(i) * 2)));
    }
    
    cout << "Value at " << value << " found using Bessel's interpolation is " << sum;
    return 0;
}

ผลลัพธ์

Value at 53.2 found using Bessel's interpolation is 7.54985