Pi Monte

// 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
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值