蒙特卡洛法求圆周率pi

思路:产生[-1,1]之间的随机点,计算随机点落到半径为1的圆内的个数与所有随机点个数之比,再乘以4就是圆周率
xy=rand(2,1000000)*2-1;
sqr=xy(1,:).^2+xy(2,:).^2;
incircle=find(sqr<=1);
outcircle=find(sqr>1);
length(find(sqr<=1))/1000000*4
xy(incircle);
hold on
plot(xy(1,incircle),xy(2,incircle),'.r');
plot(xy(1,outcircle),xy(2,outcircle),'.b');


你可能感兴趣的:(源码,matlab,蒙特卡洛,圆周率)