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

C++ Program: Inverse Interpolation ด้วย Lagrange Formula

Inverse Interpolation: หา x จาก y ที่กำหนด (กลับของ InterPolation ปกติ) ใช้ Lagrange Formula

สูตร Lagrange Inverse

x = Σ [ xᵢ × Π (y - yⱼ) / (yᵢ - yⱼ) ] สำหรับ j ≠ i

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

#include <bits/stdc++.h>
using namespace std;

struct Data { double x, y; };

double inverse_interpolation(Data d[], int n, double y) {
    double x = 0;
    for (int i = 0; i < n; i++) {
        double xi = d[i].x;
        for (int j = 0; j < n; j++) {
            if (j != i)
                xi *= (y - d[j].y) / (d[i].y - d[j].y);
        }
        x += xi;
    }
    return x;
}

int main() {
    Data d[] = {
        {1.27, 2.3},
        {2.25, 2.95},
        {2.5, 3.5},
        {3.6, 5.1}
    };
    int n = 4; // ต้นฉบับเขียน 6 ผิด (มีแค่ 4 จุด)
    double y = 4.5;
    cout << "Value of x (y = 4.5): " << inverse_interpolation(d, n, y) << endl;
    return 0;
}

ผลลัพธ์

Value of x (y = 4.5): 2.51602

หมายเหตุ

  • โค้ดต้นฉบับกำหนด n=6 แต่ข้อมูลมีแค่ 4 จุด เราแก้เป็น n=4
  • ต้องการให้ y อยู่ในช่วง [min(y), max(y)] มิฉะนั้นเป็น Extrapolation
  • Lagrange เหมาะกับข้อมูลไม่ได้กระจายสม่ำเสมอ (Unequally spaced)

การตรวจสอบ

จุดข้อมูล: (1.27,2.3), (2.25,2.95), (2.5,3.5), (3.6,5.1)
ประมาณ x เมื่อ y=4.5 → ประมาณ 2.516 (อยู่ระหว่าง 2.5 และ 3.6 สมเหตุสมผล)