Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created December 3, 2017 02:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/5bc411117bce362db121fb3c0cdca4d8 to your computer and use it in GitHub Desktop.
Save komasaru/5bc411117bce362db121fb3c0cdca4d8 to your computer and use it in GitHub Desktop.
C++ source code to interporate with Lagrange method.
/*********************************************
* ラグランジュ補間
*********************************************/
#include <iostream> // for cout
#include <stdio.h> // for printf()
using namespace std;
/*
* 計算クラス
*/
class Calc
{
// 各種変数
int n; // あらかじめ与える点の数
double s, p; // 総和, 総積
int i, j; // LOOP インデックス
double t; // LOOP インデックス
public:
// 計算
void calc();
// ラグランジュ補間
double interpolateLagrange(double x[], double y[], int n, double t);
};
/*
* 計算
*/
void Calc::calc()
{
// あらかじめ与える点
double x[] = {0.0, 2.0, 3.0, 5.0, 8.0};
double y[] = {0.8, 3.2, 2.8, 4.5, 1.9};
// 点の数
n = sizeof(x) / sizeof(x[0]);
// 結果出力
printf(" x y\n");
for (t = x[0]; t <= x[n - 1]; t += .5)
printf("%7.2f%7.2f\n", t, interpolateLagrange(x, y, n, t));
}
/*
* ラグランジュ補間
*/
double Calc::interpolateLagrange(double x[], double y[], int n, double t)
{
// 総和初期化
s = 0.0;
// 総和
for (i = 0; i < n; i++) {
p = y[i];
// 総積
for (j = 0; j < n; j++) {
if (i != j)
p *= (t - x[j]) / (x[i] - x[j]);
}
s += p;
}
return s;
}
/*
* メイン処理
*/
int main()
{
try
{
// 計算クラスインスタンス化
Calc objCalc;
// ラグランジュ補間計算
objCalc.calc();
}
catch (...) {
cout << "例外発生!" << endl;
return -1;
}
// 正常終了
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment