#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define PI 3.14159265358979323846264
double Rand(void)
{
return (double)rand() / (RAND_MAX + 1);
}
/*
* ボックス=ミューラー法
*/
double NormalRandom(double mu, double sigma)
{
double t, u, r;
static int sw = 0;
static double rs;
if (sw == 0) {
t = sqrt(-2.0 * log(1.0 - Rand()));
u = 2.0 * PI * Rand();
r = t * cos(u);
rs = t * sin(u);
sw = 1;
} else {
r = rs;
sw = 0;
}
return sigma * r + mu;
}
int main(void)
{
int i, n, ix, *histo;
double mu, sigma, x, s1 = 0.0, s2 = 0.0;
srand((unsigned)time(NULL));
printf("個数 n = ");
scanf("%d", &n);
printf("平均 μ = ");
scanf("%lf", &mu);
printf("分散 σ = ");
scanf("%lf", &sigma);
if ((histo = (int *)malloc(sizeof(int) * n)) == NULL)
exit(1);
for (i = 0; i < n; i++) {
x = NormalRandom(mu, sigma);
ix = (int)floor(2.0 * x) + 10;
if (ix >= 0 && ix < 20)
histo[ix]++;
s1 += x;
s2 += x * x;
}
for (i = 0; i < 20; i++)
printf("%4.1f -- %4.1f: %5.1f%%\n", 0.5 * (i - 10), 0.5 * (i - 9), 100.0 * histo[i] / n);
s1 /= n;
s2 = sqrt((s2 - n * s1 * s1) / (n - 1));
printf("平均 %g 標準偏差 %g\n", s1, s2);
free(histo);
return 0;
}