Lagrange Interpolation

The main function takes as input two sequences of numbers and one single number. The first sequence represents [x1​,x2​,…,xi​] of some points, and the second sequence represents [y1​,y2​,…,yi​]. You need to find the Lagrange interpolating polynomial to pass through the points. The single number is the xn​ of an additional point to be interpolated.

First, implement your Lagrange Interpolation algorithm based on [x1​,x2​,…,xi​] and [y1​,y2​,…,yi​]. Then, use it to compute the value yn​at xn​.

Example

Input: 0.0 0.1 0.2 0.3 0.4 0.5 
       1.0 0.995 0.98 0.955 0.921 0.878
       0.7
Output: 0.748

Note

1. The output retains three decimal places (rounded)!

2. [x1​,x2​,…,xi​] and [y1​,y2​,…,yi​] are distinct and of equal length.

Reference Code

#include <iostream>
#include <vector>
#include <sstream>
#include <iomanip>
using namespace std;


// You can add additional standard libraries if necessary.
// Implement the Lagrange interpolation!
class Lagrange
{
public:
    Lagrange(vector<double> x, vector<double> y): X(x), Y(y){}

    double lagrange_interpolation(int len,double xn)
    {
        double yn=0;
        double P;

        for(int k=0;k<len;k++)
        {
            P=Y[k];
            for(int j=0;j<len;j++)
            {
                if(j!=k)
                {
                    P*=(xn-X[j])/(X[k]-X[j]);
                }
            }
            yn += P;
        }

        return yn;
    }

private:
    vector<double> X, Y;
};


// Test your implementation.
int main()
{
    //  Input preprocessing.
    string str;
    getline(cin, str);
    stringstream xstr(str);
    getline(cin, str);
    stringstream ystr(str);

    // X and Y are two vectors of equal length to be traversed.
    vector<double> X, Y;
    double a;
    while (xstr >> a)
    {
        X.push_back(a);
    }
    while (ystr >> a)
    {
        Y.push_back(a);
    }
    // interp_x is the point to be interpolated.
    double interp_x;
    cin >> interp_x;

    // Do Lagrange interpolation for interp_x using X and Y, and print your results
    // Note: The result retains three decimal places (rounded)!
    Lagrange Pn(X,Y);

    int len=X.size();

    cout<<setiosflags(ios::fixed)<<setprecision(3)<<Pn.lagrange_interpolation(len,interp_x);

    // End
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值