Lagrange(拉格朗日插值)

#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
//拉格朗日插值(Lagrange)
//Ln(x)=l0(x)y0+l1(x)y1+l2(x)y2+...+ln(x)yn
long double Larange(double X[20],double Y[20],int n,double x) {
    long double F , l;
    F = 0;
    int i,j;//计数器
    for (i = 0; i < n; i++) {
        //求l(x)
        l = 1;
        for (j = 0; j < n; j++) {
            if (j != i) l = l * (x - X[j]) / (X[i] - X[j]);
        }
        F = F + l * Y[i];
    }
    return F;
}
int main() {
    cout << "*********************************" << endl;
    cout << "这是一个拉格朗日插值函数的代码~~~" << endl;
    cout << "*********************************" << endl;
    int n, i;
    double x;
    long double y;
    double X[20], Y[20];
    cout << "请输入已知的点的坐标的个数(最多20个):";
    cin >> n;
    cout << endl;
    if (n < 1) { cout << "坐标个数过少,算不出来啊!" << endl; return 0; }
    if (n > 20) {
        cout << "坐标个数太多啦,算不过来啊!" << endl;
        return 0;
    }
    cout << "请依次输入已知点的横纵坐标" << endl;
    for(i = 0; i < n; i++) {
        cout << "" << i+1 << "组   横坐标:";
        cin >> X[i];
        cout << "        纵坐标:";
        cin >> Y[i];
        cout << endl;
    }
    cout << "已知坐标输入完毕,现在请输入待求函数值对应的横坐标:";
    cin >> x;
    cout << "稍等一下,系统在飞速计算哦~" << endl;
    y = Larange(X, Y, n, x);
    cout << "结果计算出来啦:" << y << endl;
    cout << endl;
    cout << "******小王最棒!******" << endl;
    return 0;
}

程序调试结果

posted @ 2020-04-07 00:57  打不死的小王  阅读(929)  评论(0编辑  收藏  举报