近似の良さは,もとの関数と,フーリエ級数で作った関数が どのくらい類似しているか,距離を計ればわかる. ヒント: 「関数をベクトルとして見る」
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int N = 20; // どこまで足すか
int SHOW_EVERY_N_STEP = 5;
double start_t = -3.0*M_PI; // 横軸はじまり
double end_t = 3.0*M_PI; // 横軸おわり
double step = 0.01;
int main(int argc, char *argv[])
{
int i;
double pi = M_PI;
double t, y;
char filename[256] = "2010am2.dat";
FILE *fp;
if((fp = fopen(filename, "wt")) == NULL){
printf("NOT open file (%s)\n", filename);
exit(1);
}
for ( t = start_t; t < end_t; t=t+step ){
y = pi/2.0; // 平均値. a0/2 項
fprintf(fp, "%.2lf \t",t);
for ( i = 1; i <= N; i++ ){ // N 項まで足していく
y = y - 4.0/pi/(2.0*i-1.0)/(2.0*i-1.0)*cos( (2.0*i-1.0)*t );
if (i % SHOW_EVERY_N_STEP == 0){
fprintf(fp, "%.5lf ",y); // ある項数ごとに値をプリント
}
}
fprintf(fp, "\n");
}
fclose(fp);
}
% gcc fourier003.c -lm % a.out
% less 2010am2.dat | more -9.42 3.07814 3.10979 3.12038 3.12568 -9.41 3.07782 3.10915 3.11943 3.12441 -9.40 3.07687 3.10725 3.11660 3.12068 -9.39 3.07528 3.10412 3.11198 3.11467 -9.38 3.07307 3.09978 3.10569 3.10668 -9.37 3.07024 3.09430 3.09793 3.09712 -9.36 3.06679 3.08776 3.08890 3.08639 -9.35 3.06275 3.08022 3.07884 3.07494 -9.34 3.05812 3.07179 3.06799 3.06319 -9.33 3.05292 3.06256 3.05660 3.05147 -9.32 3.04717 3.05265 3.04491 3.04006 -9.31 3.04088 3.04215 3.03312 3.02912 -9.30 3.03407 3.03119 3.02142 3.01873 -9.29 3.02676 3.01986 3.00996 3.00886 -9.28 3.01899 3.00828 2.99883 2.99942 .....................
% gnuplot
G N U P L O T
Version 4.2 patchlevel 5
last modified Mar 2009
System: Linux 2.6.31-22-generic
Terminal type set to 'wxt'
gnuplot> plot "2010am2.dat" using 1:2 with lines 1, "2010am2.dat" using 1:3 with lines 2
で画面に表示される.
LaTeX でレポートを書く際には,グラフの eps ファイルを作成しておけばいい.
eps ファイルの作成の仕方は
gnuplot> set terminal postscript "Helvetica" 20 color eps enhanced gnuplot> set output "foo.eps" gnuplot> set xlabel "t" gnuplot> set ylabel "f(t)" gnuplot> plot "2010am2.dat" using 1:2 with lines 1, "2010am2.dat" using 1:3 with lines 2
set terminal postscript "Helvetica" 20 color eps enhanced set xlabel "t" set ylabel "f(t)" plot [:][:] "2010am2.dat" using 1:2 title "n=5" with lines 1,\ "2010am2.dat" using 1:2 title "n=10" with lines 2,\ "2010am2.dat" using 1:3 title "n=15" with lines 3,\ "2010am2.dat" using 1:3 title "n=20" with lines 4このファイルを用意し
% gnuplot gp-script > foo.epsとすると,eps ファイルが作成される.
% evince foo.eps # グラフを見る