const unsigned long multiplier = 1194211693L;
const unsigned long adder = 12345L;
class RandomNumber{
private:
// 當前種子
unsigned long randSeed;
public:
// 構造函數,默認值0表示由系統自動產生種子
RandomNumber(unsigned long s = 0);
// 產生0 ~ n-1之間的隨機整數
unsigned short Random(unsigned long n);
// 產生[0, 1) 之間的隨機實數
double fRandom();
};
// 產生種子
RandomNumber::RandomNumber(unsigned long s)
{
if(s == 0)
randSeed = time(0); //用系統時間產生種子
else
randSeed = s;
}
// 產生0 ~ n-1 之間的隨機整數
unsigned short RandomNumber::Random(unsigned long n)
{
randSeed = multiplier * randSeed + adder;
return (unsigned short)((randSeed >> 16) % n);
}
// 產生[0, 1)之間的隨機實數
double RandomNumber::fRandom()
{
return Random(maxshort) / double(maxshort);
}
/*
* Author: Tanky woo
* Blog: www.WuTianQi.com
* Date: 2010.12.8
* 用隨機投點法計算Pi值
* 代碼來至王曉東《計算機算法設計與分析》
*/
#include "RandomNumber.h"
#include <iostream>
#include <iomanip>
#include <time.h>
using namespace std;
double Darts(long n)
{
// 用隨機投點法計算Pi值
static RandomNumber dart;
long k = 0;
for(long i=1; i<=n; ++i)
{
double x = dart.fRandom();
double y = dart.fRandom();
// 在圓內
if((x*x+y*y) <= 1)
++k;
}
return 4 * k / double(n);
}
int main()
{
// 當進行1,000次投點時
cout << Darts(1000) << endl;
// 當進行10,000次投點時
cout << Darts(10000) << endl;
// 當進行100,000次投點時
cout << Darts(100000) << endl;
// 當進行1,000,000次投點時
cout << Darts(1000000) << endl;
// 當進行10,000,000次投點時
cout << Darts(10000000) << endl;
// 當進行100,000,000次投點時
cout << Darts(100000000) << endl;
return 0;
}