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