Created
December 3, 2017 04:25
-
-
Save komasaru/6a10c02cf3f5e5fe411d7fb3987b36dd to your computer and use it in GitHub Desktop.
C++ source code to interpolate with Newton method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/********************************************* | |
* ニュートン補間 | |
*********************************************/ | |
#include <iostream> // for cout | |
#include <stdio.h> // for printf() | |
using namespace std; | |
/* | |
* 計算クラス | |
*/ | |
class Calc | |
{ | |
// 各種変数 | |
int n; // あらかじめ与える点の数 | |
int i, j; // LOOP インデックス | |
double t; // LOOP インデックス | |
double c[100]; // 係数配列 | |
double w[100]; // 作業用配列 | |
double s; // 総和 | |
public: | |
// 計算 | |
void calc(); | |
// ニュートン補間 | |
double interpolateNewton(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, interpolateNewton(x, y, n, t)); | |
} | |
/* | |
* ニュートン補間 | |
*/ | |
double Calc::interpolateNewton(double x[], double y[], int n, double t) | |
{ | |
// 係数 | |
for (i = 0; i < n; i++) { | |
w[i] = y[i]; | |
for (j = i - 1; j >= 0; j--) | |
w[j] = (w[j+1] - w[j]) / (x[i] - x[j]); | |
c[i] = w[0]; | |
} | |
// 総和 | |
s = c[n-1]; | |
for (i = n - 2; i >= 0; i--) | |
s = s * (t - x[i]) + c[i]; | |
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