// PiMonte.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <time.h>
#include <stdlib.h>
double randomBetweenPlusMinusOne()
{
int k=rand()%200;//k:0~199
double m=k/100.0;//m:0~1.99
m-=1.0;//m:-1~0.99
return m;
}
struct Point
{
double x,
y;
bool isInCircle()
{
return (x*x+y*y)<=1.0;
}
void SetXY()
{
x=randomBetweenPlusMinusOne();
y=randomBetweenPlusMinusOne();
}
};
void TestPrint(double N)
{
double n=0;
Point pt;
for(int i=0;i<N;i++)
{
pt.SetXY();
if(pt.isInCircle())
n++;
}
double piByMonte=4.0*n/N;
printf("i=%d,N=%lf,piByMonte=%lf\n",i,N,piByMonte);
}
int main(int argc, char* argv[])
{
srand((unsigned)time( NULL ));
double N=1e5;
TestPrint(N);
N=1e6;
TestPrint(N);
N=1e7;
TestPrint(N);
N=1e8;
TestPrint(N);
return 0;
}
/*
i=100000,N=100000.000000,piByMonte=3.140840
i=1000000,N=1000000.000000,piByMonte=3.144908
i=10000000,N=10000000.000000,piByMonte=3.143233
i=100000000,N=100000000.000000,piByMonte=3.142954
Press any key to continue
*/