Last active
November 29, 2017 02:59
-
-
Save komasaru/d370029305ffb1d28d8b8cf60be576c1 to your computer and use it in GitHub Desktop.
C++ source code to compute Taylor expansion (exp(x)).
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
/********************************************* | |
* テイラー展開 ( exp(x) ) | |
*********************************************/ | |
#include <iostream> // for cout | |
#include <math.h> // for exp(), fabs() | |
#include <stdio.h> // for printf() | |
using namespace std; | |
/* | |
* 計算クラス | |
*/ | |
class Calc | |
{ | |
// 各種定数 | |
static const double eps = 1e-08; // 精度 | |
// 各種変数 | |
double x; // X 値 | |
double e; // e 値 | |
double d; // d 和 | |
double s; // s 和 | |
int k; // LOOP インデックス | |
public: | |
// テイラー展開 | |
void calcTaylor(); | |
// exp 計算 | |
double calcExp(double x); | |
}; | |
/* | |
* テイラー展開 | |
*/ | |
void Calc::calcTaylor() | |
{ | |
// x = -50 から 50 を 10 刻みで計算 | |
printf(" x myexp(x) exp(x)\n"); | |
for (x = -50; x <= 50; x += 10) | |
printf("%5.1f%14.6g%14.6g\n", x, calcExp(x), exp(x)); | |
} | |
/* | |
* Exp 計算 | |
*/ | |
double Calc::calcExp(double x) | |
{ | |
// 変数初期化 | |
d = 1.0; | |
s = 1.0; | |
e = 1.0; | |
// 最大200回ループ処理 | |
for(k = 1; k <= 200; k++) { | |
d = s; // d 和 | |
e = e * fabs(x) / k; // e 値 | |
s += e; // s 和 | |
// 打ち切り誤差 | |
if (fabs(s - d) / fabs(d) < eps) { | |
if (x > 0) | |
return s; | |
else | |
return 1.0 / s; | |
} | |
} | |
// 収束しない時 | |
return 0.0; | |
} | |
/* | |
* メイン処理 | |
*/ | |
int main() | |
{ | |
try | |
{ | |
// 計算クラスインスタンス化 | |
Calc objCalc; | |
// テイラー展開 | |
objCalc.calcTaylor(); | |
} | |
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