蒙特卡洛算法

来源:互联网 发布:name.com 域名不能转出 编辑:程序博客网 时间:2024/04/29 04:25


个人理解:蒙特卡洛算法是一种随机化的模拟统计算法,运用广泛,具体可百度;

适用情况:要求精度不高,时间复杂度要求不高,但精确算法的实现较复杂时,蒙特卡洛算法是一个比较好的选择;


基本模板:


#include<iostream>#include<cstdio>#include<cmath>#include<ctime>#include<cstdlib>using namespace std;const int maxn=1000000;double Rand(const double &L, const double &R){    return L + (R - L) * rand()  / 32767;}int main(){    srand(time(NULL));    double l=1,r=10;    printf("%lf\n",Rand(l,r));//随机生成l~r的数    return 0;}





比较经典的算法有 用蒙特卡洛算法求圆周率


#include<iostream>#include<cstdio>#include<cmath>#include<ctime>#include<cstdlib>using namespace std;#define RANM RAND_MAXconst int maxn=1000000;//枚举次数越多越精确double Rand(const double &L, const double &R){    return L + (R - L) * rand() *1.0 / RANM;}int main(){    srand(time(NULL));    double x,y;    double  s=0;//在圆内的点的个数    for(int i=0; i<maxn; i++) //做一百万次投针试验    {        x=Rand(-100,100);        y=Rand(-100,100);        if(x*x+y*y< 10000) s++;    }    printf("PI=%lf\n",4*s/maxn);    return 0;}



1 0
原创粉丝点击