- 構造体を使ってみる
- 値列の要素数・平均・標本分散・不偏分散を持つ構造体を作ってみる
- ヘッダファイルで構造体の作りを宣言("DescriptionStat.h"というファイル)
struct DescStat {
int n;
double m;
double sv;
double uv;
};
-
- DescStat構造体を使うstrprac.c。, "MT.h"と"DescriptionStat.h"をインクルードする
# include <stdio.h>
# include "DescriptionStat.h"
#include <time.h>
#include <math.h>
#include "MT.h"
main () {
int i,j;
int niter = 3;
int nr = 100;
struct DescStat A[niter];
for(i = 0; i < niter; i++){
double rtmp[nr];
for(j = 0; j < nr; j++){
rtmp[j] = genrand_real3();
}
double tmpm = 0;
for(j = 0; j < nr; j++){
tmpm += rtmp[j];
}
tmpm /= nr;
double tmpsv = 0;
for(j = 0; j < nr; j++){
tmpsv += pow((rtmp[j]-tmpm),2);
}
tmpsv /= nr;
struct DescStat tmpA = {nr,tmpm,tmpsv,tmpsv*nr/(nr-1)};
A[i] = tmpA;
}
printf("N.elements\tMean\tsample.variance\tunbiased.variance\n");
for(i = 0; i < niter; i++) {
printf("%d\t%f\t%f\t%f\n",A[i].n, A[i].m,A[i].sv,A[i].uv);
}
return 0;
}
ryamada@CFS10 ~
$ gcc -o strprac strprac.c
ryamada@CFS10 ~
$ ./strprac.exe
N.elements Mean sample.variance unbiased.variance
100 0.543772 0.097448 0.098432
100 0.523272 0.078582 0.079376
100 0.486063 0.085874 0.086742
ryamada@CFS10 ~
# include <stdio.h>
# include "DescriptionStat.h"
#include <time.h>
#include <math.h>
#include "MT.h"
main () {
int i,j;
int niter = 3;
int nr = 100;
struct DescStat A[niter];
for(i = 0; i < niter; i++){
double rtmp[nr];
for(j = 0; j < nr; j++){
rtmp[j] = genrand_real3();
}
double tmpm = 0;
for(j = 0; j < nr; j++){
tmpm += rtmp[j];
}
tmpm /= nr;
double tmpsv = 0;
for(j = 0; j < nr; j++){
tmpsv += pow((rtmp[j]-tmpm),2);
}
tmpsv /= nr;
struct DescStat tmpA = {nr,tmpm,tmpsv,tmpsv*nr/(nr-1)};
A[i] = tmpA;
}
A[2] = A[1];
printf("N.elements\tMean\tsample.variance\tunbiased.variance\n");
for(i = 0; i < niter; i++) {
printf("%d\t%f\t%f\t%f\n",A[i].n, A[i].m,A[i].sv,A[i].uv);
}
return 0;
}
ryamada@CFS10 ~
$ gcc -o strprac strprac.c
ryamada@CFS10 ~
$ ./strprac.exe
N.elements Mean sample.variance unbiased.variance
100 0.543772 0.097448 0.098432
100 0.523272 0.078582 0.079376
100 0.523272 0.078582 0.079376
ryamada@CFS10 ~