C++中的拉格朗日插值


在這一教程中,我們將編寫一個程式,該程式找到拉格朗日插值法的結果。

你無需編寫任何程式邏輯。只需將公式轉換為程式碼即可。讓我們看看程式碼。

示例

 線上演示

#include<bits/stdc++.h>
using namespace std;
struct Data {
   int x, y;
};
double interpolate(Data function[], int xi, int n) {
   double result = 0;
   for (int i = 0; i < n; i++) {
      double term = function[i].y;
      for (int j = 0; j < n; j++) {
         if (j != i) {
            term = term * (xi - function[j].x) / double(function[i].x - function[j].x);
         }
      }
      result += term;
   }
   return result;
}
int main() {
   Data function[] = {{0,3}, {1,2}, {6,9}, {10,17}};
   cout << interpolate(function, 3, 5) << endl;
   return 0;
}

輸出

如果你執行以上程式碼,則將獲得以下結果。

3

結論

如果你在教程中有什麼疑問,請在評論部分中提出。

更新於: 09-04-2021

1千次以上瀏覽

開啟你的職業生涯

透過完成課程獲取認證

開始
廣告
© . All rights reserved.