您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 项目/工程管理 > 蒙特卡洛方法计算圆周率(C语言实现)
C20183191121323.1............................................33.2............................................53.3............................................64813:143:141592654C2MonteCarlomethod11(a)n=100(b)n=800(c)n=20001:rSCSRNrNr+NbSCSR=r2(2r)2NrNr+NbNrNb4NrNr+Nb(1)2nn(1)n!+14NrNr+Nb!00:20:40:60:81104012345n2:n323.1pxyxyCrandstdlib.hintrand();0~RAND_MAX191#includestdio.h2#includestdlib.h3#includetime.h45intmain()6{7/*RAND_MAX*/8printf(valueofRAND_MAX:%d\n,RAND_MAX);910/**/11srand(time(0));1213/*10*/14for(inti=0;i10;++i){15printf(%d\n,rand());16}1718return0;19}srandrandtimesrandrandstdlibtimetime.h23RAND_MAXstdlib.h8RAND_MAXrand11srandrand1416forrand10valueofRAND_MAX:214748364718091255541374689606817374586673529929105812876135247103142031481267634257328811236754373071782srand11srandrand3 1:01:0 1:01:0Oxy3:3xy[ 1:0;1:0]rand[0;RAND_MAX]m= 1:0+2:0rRAND_MAXrrandrand[ 1:0;1:0]xy43.2nforn(1)ni=0,c=0in?pi=4*c/nx2[ 1:0;1:0]y2[ 1:0;1:0]++ix*x+y*y1.0?++c4:1#includestdio.h2#includestdlib.h3#includetime.h45intmain()6{7srand(time(0));89intn,c=0;10printf(pleaseinputn:);11scanf(%d,&n);51213for(inti=0;i=n;++i){14doublex=-1.0+2.0*rand()/RAND_MAX;15doubley=-1.0+2.0*rand()/RAND_MAX;16if(x*x+y*y1.0){17++c;18}19}2021doublepi=4.0*c/n;22printf(valueofpi:%lf\n,double);2324return0;25}pleaseinputn:100000valueofpi:3.1514803.31e 61#includestdio.h2#includestdlib.h3#includetime.h4#includemath.h56intmain()7{8srand(time(0));910doubleeps=1e-6,delta;11intr=0,c=0;12intn=0;13doublex,y,p1,p2;1415while(n++100){16x=-1.0+2.0*rand()/RAND_MAX;17y=-1.0+2.0*rand()/RAND_MAX;18if(x*x+y*y1.0){19++c;620}21else{22++r;23}24}25p1=4.0*c/(c+r);2627do{28x=-1.0+2.0*rand()/RAND_MAX;29y=-1.0+2.0*rand()/RAND_MAX;30if(x*x+y*y1.0){31++c;32}33else{34++r;35}36p2=4.0*c/(c+r);37++n;3839delta=fabs(p2-p1);40p1=p2;41}while(deltaeps);4243printf(iterations:%d\n,n-1);44printf(delta:%.7lf\n,delta);45printf(valueofpi:%lf\n,p2);4647return0;48}151710002741iterations:859661delta:0.0000010valueofpi:3.14034074CCCC8
本文标题:蒙特卡洛方法计算圆周率(C语言实现)
链接地址:https://www.777doc.com/doc-4803265 .html