Skip to content

Latest commit

 

History

History
40 lines (38 loc) · 810 Bytes

拉格朗日插值.md

File metadata and controls

40 lines (38 loc) · 810 Bytes
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000;
float Lagrange(float *a, float *b, int n, float x){
    float yres = 0;
    float L[maxn];
    float temp1, temp2;
    //get L(x)
    for(int i = 0; i < n; i++){
        temp1 = 1.0;
        temp2 = 1.0;
        for(int j = 0; j < n; j++){
            if(i == j) continue;
            temp1 *= (x - a[j]);
            temp2 *= (a[i] - a[j]);
        }
        L[i] = temp1 / temp2;
    }
    //get Pn(x)
    for(int i = 0; i < n; i++){
        yres += b[i] * L[i];
    }
    return yres;
}

int main(){
    float a[maxn], b[maxn];
    a[0] = 11.0;
    b[0] = 0.190809;
    a[1] = 12.0;
    b[1] = 0.207912;
    a[3] = 13.0;
    b[3] = 0.224951;
    float ans = Lagrange(a, b, 3, 11.5);
    printf("%.5f\n", ans);
    return 0;
}