[Matlab] Monte Carlo method to simulate pi + corresponding analytical GIF generation [super detailed notes and explanations]

insert image description here


foreword

Because the blogger is going to prepare for the Mathematical Modeling Contest recently, in addition to learning matlab and python , the blogger will continue to output the blogger's study diary for everyone!
Today is a relatively simple and basic problem in mathematical modeling, the simulation of pi.
The simulation method we used is the Monte Carlo method.
The picture is taken from Baidu Encyclopedia:
insert image description here

  • To put it simply, it is to randomly generate a number of points on a plane, and calculate the number of points in the unit circle, thereby simulating the pi.

Then the bloggers here will first write some columns full of dry goods!

Data Structure Column: Data Structure This contains a lot of bloggers' summaries of data structure learning. Each article is written with great care. Interested partners can support it!
Algorithm Column: Algorithm This can be said to be the blogger's writing process. It summarizes some classic questions and the algorithm implementation, which is very helpful for exams and competitions!
Likou Brush Question Column: Leetcode wants to hit the partners of ACM, Blue Bridge Cup or college student programming competition. Here are the blogger's brush questions record, I hope it will help you!
C's deep anatomy column: C language deep anatomy For beginners who want to deeply learn the wisdom contained in C language and the underlying implementation of various functions, I believe this column will be helpful to you!


Simulation ideas

  • Randomly generate a number of points on a plane, and calculate the number of points in the unit circle to simulate the pi.
allPoints = 10000; % 我们设置生成的总点数越多,结果越逼近圆周率
cnt=0;
for i=1:allPoints
    if rand^2+rand^2<=1 % 这个点在四分之一圆内
        cnt=cnt+1; % 计数器加一
    end
end
res=cnt/allPoints*4; % 因为是四分之一圆,记得乘4
disp(res);

insert image description here

GIF simulation animation generation

In mathematical modeling competitions or in daily data analysis, the results are presented in the form of graphs, which often make complex problems more clearly displayed.

The basic idea of ​​GIF animation generation

  • Basic idea: Combining multiple pictures

Generation of a single static image

x1=linspace(0,1,10000); % 随机在[0,1]之间生成10000个点
y1=(1-x1.^2).^0.5;   % 这个其实就是四分之一圆的方程

x2=rand([1,500]);% 生成随机数的向量
y2=rand([1,500]);

% 先统计一下,有多少个点在四分之一圆里面 -- 因为我们要写标题
count=0;
for j=1:500
    % 注意:x2和y2都是一个数组
    if (x2(j)^2+y2(j)^2)<=1 % 点在四分之一圆里面的条件
        count=count+1;
    end
end
% plot(x1,y1,x2,y2);% 这样直接画其实不是散点的形式,所以要加一个参数'.'
plot(x1,y1,x2,y2,'.');
title(num2str(count)+"/"+num2str(500)+'*'+"4="+num2str(count/500*4));% 给图片设置标题
axis square; % 可以让横纵坐标长度相同

Image generation effect:
insert image description here

GIF generation

  • In fact, the idea is very simple. We directly use a loop to generate multiple pictures, and finally combine them.
    Code to generate GIF:
    % 这段代码稍微可以记一下,是用来生成gif的
    frame = getframe(gcf); %捕获坐标区或图窗作为影片帧
    I = frame2im(frame); %返回与影片帧关联的图像数据
    [I,map]=rgb2ind(I,256);%将 RGB 图像转换为索引图像I,关联颜色图为 map

    if i == 500
        imwrite(I,map,'test.gif','gif', 'Loopcount',inf,'DelayTime',0.2);% 这里的0.2指的是,每幅图切换时候的时间间隔
    else
        imwrite(I,map,'test.gif','gif','WriteMode','append','DelayTime',0.2);
                     %                              append表示是图像时不断追加进去的
                     % test.gif这个文件会被放到默认的当前目录下
    end

Monte Carlo simulation pi GIF generation total code:

% 我们来绘制模拟圆周率当时的那张gif
for i=[500,1000,2000,5000,10000]
    x1=linspace(0,1,10000);
    y1=(1-x1.^2).^0.5;

    x2=rand([1,i]);% 这些500都改成i
    y2=rand([1,i]);

    count=0;
    for j=1:i
        if (x2(j)^2+y2(j)^2)<=1
            count=count+1;
        end
    end
    plot(x1,y1,'black .',x2,y2,'.');
    title(num2str(count)+"/"+num2str(i)+'*'+"4="+num2str(count/i*4));
    axis square;

    % 这段代码稍微可以记一下,是用来生成gif的
    frame = getframe(gcf); %捕获坐标区或图窗作为影片帧
    I = frame2im(frame); %返回与影片帧关联的图像数据
    [I,map]=rgb2ind(I,256);%将 RGB 图像转换为索引图像I,关联颜色图为 map

    if i == 500
        imwrite(I,map,'test.gif','gif', 'Loopcount',inf,'DelayTime',0.2);
    else
        imwrite(I,map,'test.gif','gif','WriteMode','append','DelayTime',0.2);
                     %                              append表示是图像时不断追加进去的
                     % test.gif这个文件会被放到默认的当前目录下
    end
end

Generate effect:
insert image description here

end

Seeing this, I believe that we have learned the Monte Carlo method to simulate the process of pi. Of course, this is far from the requirements of mathematical modeling and our goal. In the process of continuous learning, bloggers also hope to share The way to learn diary drives everyone! If you find this article helpful, don't forget to like it! focus on! Favorite Oh!

Guess you like

Origin blog.csdn.net/Yu_Cblog/article/details/126132438