Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created November 30, 2017 02:01
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/0df54a194be19cfbf8a1d52e69f53d7a to your computer and use it in GitHub Desktop.
Save komasaru/0df54a194be19cfbf8a1d52e69f53d7a to your computer and use it in GitHub Desktop.
C++ source code to compute Taylor expansion (cos(x)).
/*********************************************
* テイラー展開 ( cos(x)) )
*********************************************/
#include <iostream> // for cout
#include <math.h> // for cos()
#include <stdio.h> // for printf()
using namespace std;
/*
* 計算クラス
*/
class Calc
{
// 各種定数
static const double eps = 1e-08; // 精度
static const double pi = 3.1415926535; // 円周率
// 各種変数
double x; // X 値
double rd; // ラジアン値
double e; // e 値
double d; // d 和
double s; // s 和
int k; // LOOP インデックス
public:
// テイラー展開
void calcTaylor();
// Cos 計算
double calcCos(double x);
};
/*
* テイラー展開
*/
void Calc::calcTaylor()
{
// ラジアン値計算
rd = pi / 180;
// x = 0 から 180 を 10 刻みで計算
printf(" x mycos(x) cos(x)\n");
for (x = 0; x <= 180; x += 10)
printf("%5.1f%14.6f%14.6f\n", x, calcCos(x * rd), cos(x * rd));
}
/*
* Cos 計算
*/
double Calc::calcCos(double x)
{
// 変数初期化
d = 1.0;
s = 1.0;
e = 1.0;
// x の値が 0 から 2π の範囲外の場合、0 から 2π に収める
x = fmod(x, 2 * pi);
// 最大200回ループ処理
// ( ただし、偶数項は 0 なので除外 )
for(k = 1; k <= 200; k = k + 2) {
d = s; // d 和
e = -e * x * x / (k * (k + 1)); // 各項の値
s += e; // s 和
// 打ち切り誤差
if (fabs(s - d) / fabs(d) < eps)
return(s);
}
// 収束しない時
return(9999.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