我把 Pi 當平均值 (0.5), 不過算起來好像怪怪的...
--
/*
Algorithms Programming Assignment #1
Random Number Generator
b5506054
*/
#include <iostream.h>
#define RAND_B 8421
#define RAND_MAX 65536
#define seed_length 55
int seed_table[seed_length];
double x_sqrt = 0;
// (1) pi
bool pi(double x, double y)
{
return (x * x + y * y <= 1) ? true : false;
}
// (2) integral x^2 dx from 0 to 1
bool sx(double x, double y)
{
return (y <= x * x) ? true : false;
}
// Linear Congruential method
void rand_init(int seed)
{
int i;
*seed_table = seed % RAND_MAX;
for (i = 1; i < seed_length; i++)
seed_table[i] = (seed_table[i - 1] * RAND_B + 1) % RAND_MAX;
}
// Additive Congruential method
int rand()
{
static int ptr = 0;
ptr = ptr % seed_length;
seed_table[ptr]
= (seed_table[ptr] + seed_table[(ptr + 31) % seed_length])
% RAND_MAX;
return seed_table[ptr++];
}
// transform from [0, RAND_MAX) to [0, 1)
double random()
{
double fi = (double) rand() / RAND_MAX;
x_sqrt += (fi - 0.5) * (fi - 0.5) / 0.5;
return fi;
}
double calculate(bool (*function) (double x, double y), int times)
{
int i, n;
for (i = 0, n = 0; i < times; i++)
if ((*function) (random(), random()))
n++;
return (double) n / times;
}
void main()
{
int seed;
cout << "Please input your seed: ";
cin >> seed;
rand_init(seed);
cout
<< "(1) pi = " << 4.0 * calculate(pi, 10000) << endl
<< "(2) sx = " << calculate(sx, 10000) << endl
<< endl;
cout
<< "x^2-test:" << endl
<< " x^2 = " << x_sqrt << endl;
}
--
※ 發信站: 批踢踢實業坊(ptt.m8.ntu.edu.tw)
◆ From: Action.m8.ntu.e