蒙特卡洛算法应用 — 估算圆周率
写在前面
Monte Carlo method,也称为统计模拟方法,是一个针对计算机处理能力设计的利用概率统计理论解决一些较为复杂的计算问题的巧妙算法,是解决某些问题的唯一可行算法,下面将利用蒙特卡洛算法粗略计算圆周率的值。
问题模型
源代码
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iomanip>
using namespace std;
int main()
{
//初始化随机数生成器
unsigned seed;
seed = time(0);
srand(seed);
//初始化计数器
int i,counts = 0;
//定义随机次数、正方形边长
const int times = 100000;
const int lenth = 500;
for(i = 0;i < times;i ++){
int value1 = (rand()%(lenth))+1;
int value2 = (rand()%(lenth))+1;
if(abs(pow(pow((value1 - lenth / 2),2) + pow((value2 - lenth / 2),2) ,0.5)) <= (lenth / 2))
counts ++;
}
cout << ((long double)counts / times) * 4 << endl;
return 0;
}
运行结果
test1:
test2:
test3:
更多相关内容请参见
-end-