美文网首页
pi蒙特卡洛模拟的Matlab实现

pi蒙特卡洛模拟的Matlab实现

作者: NILSTARK | 来源:发表于2016-06-01 10:30 被阅读621次
    function piva=PiMonterCarlo(n)
    x=0;y=0;d=0;
    m=length(n);
    pivalue=zeros(m,1);
    for i=1:m
        x=2*rand(n(i),1)-1;
        y=2*rand(n(i),1)-1;
        d=x.^2+y.^2;
        pivalue(i)=4*sum(d<=1)/n(i);
    end
    if nargout==0
        if m>1
            figure;
            plot(n,pivalue,'k.');
            h=refline(0,pi);
            set(h,'linewidth',2,'color','r');
            text(1.05*n(end),pi,'\pi','FontSize',15);
            xlabel('投点个数');
            ylabel('\pi的模拟值');
        else
            figure;
            plot(x,y,'r.');
            hold on;
            h=rectangle('Position',[-1 -1 2 2],'LineWidth',2);
            t=linspace(0,2*pi,100);
            plot(cos(t),sin(t),'k','LineWidth',2);
            xlabel('X');ylabel('Y');
    %         title('Pi的模拟值:'num2str(pivalue));
            axis([-1.1 1.1 -1.1 1.1]);axis equal;
        end
    else
        piva=pivalue;
    end
    
    pi.png

    相关文章

      网友评论

          本文标题:pi蒙特卡洛模拟的Matlab实现

          本文链接:https://www.haomeiwen.com/subject/ekdhdttx.html