拉格朗日插值


对于在离散给定数据点范围之内构造新的数据点,使用插值技术。拉格朗日插值技术就是其中之一。当给定数据点分布不均匀时,我们可以用此插值法找出解决方案。对于拉格朗日插值法,我们必须遵循此方程式。


输入和输出

Input:
List of x and f(x) values. find f(3.25)
x: {0,1,2,3,4,5,6}
f(x): {0,1,8,27,64,125,216}
Output:
Result after Lagrange interpolation f(3.25) = 34.3281

算法

largrangeInterpolation(x: array, fx: array, x1)

输入 − x 阵列和 fx 阵列,用于获取以前已知的数据,以及点 x1。

输出:f(x1) 的值。

Begin
   res := 0 and tempSum := 0
   for i := 1 to n, do
      tempProd := 1
      for j := 1 to n, do
         if i ≠ j, then
            tempProf := tempProd * (x1 – x[j])/(x[i] – x[j])
      done

      tempPord := tempProd * fx[i]
      res := res + tempProd
   done
   return res
End

示例

#include<iostream>
#define N 6
using namespace std;

double lagrange(double x[], double fx[], double x1) {
   double res = 0, tempSum = 0;

   for(int i = 1; i<=N; i++) {
      double tempProd = 1;         //for each iteration initialize temp product
      for(int j = 1; j<=N; j++) {
         if(i != j) {                 //if i = j, then denominator will be 0
            tempProd *= (x1 - x[j])/(x[i] - x[j]);     //multiply each term using formula
         }
      }
      tempProd *= fx[i];                //multiply f(xi)
      res += tempProd;
   }
   return res;
}

main() {
   double x[N+1] = {0,1,2,3,4,5,6};
   double y[N+1] = {0,1,8,27,64,125,216};
   double x1 = 3.25;
   cout << "Result after lagrange interpolation f("<<x1<<") = " << lagrange(x, y, x1);
}

输出

Result after lagrange interpolation f(3.25) = 34.3281

更新于:2020 年 6 月 17 日

988 次浏览

开启您的 职业生涯

完成课程认证

开始
广告
© . All rights reserved.