Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created December 16, 2017 01:51
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/461d1d4b59b168d8675c757c9f9c476d to your computer and use it in GitHub Desktop.
Save komasaru/461d1d4b59b168d8675c757c9f9c476d to your computer and use it in GitHub Desktop.
C++ source code to expand Fourier's series.
/*********************************************
* フーリエ級数展開 *
* f(t) = -1 (-pi < t <= 0 ) *
* 1 ( 0 < t <= pi) *
*********************************************/
#include <iostream> // for cout
#include <math.h> // for sin()
#include <stdio.h> // for printf()
#define N 3 // 計算項数
using namespace std;
/*
* 計算クラス
*/
class Calc
{
public:
void expandFourierSeries(); // フーリエ級数展開
private:
double calcTerm(int n, double x); //各項計算
};
/*
* フーリエ級数展開
*/
void Calc::expandFourierSeries()
{
int i; // LOOPインデックス
double t, y = 0; // 横軸、縦軸
FILE *pf; // ファイルポインタ
// 出力ファイルOPEN
pf = fopen("FourierSeriesExpansion.csv", "w");
// ヘッダ出力
fprintf(pf, "t,f(t)\n");
// 1 / 1000 刻みで計算
for (t = -M_PI; t < M_PI; t += 0.001) {
for (i = 1; i <= N; i++) y += calcTerm(i, t);
fprintf(pf, "%lf,%lf\n", t, 4 / M_PI * y);
y=0;
}
// 出力ファイルCLOSE
fclose(pf);
}
/*
* 各項計算
*/
double Calc::calcTerm(int n, double t)
{
return sin((2 * n - 1) * t) / (2 * n - 1);
}
/*
* メイン処理
*/
int main()
{
try
{
// 計算クラスインスタンス化
Calc objCalc;
// フーリエ級数展開
objCalc.expandFourierSeries();
}
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