Matlab--Monte Carlo method for finding pi

Matlab--Monte Carlo method for finding pi

Monte Carlo method (Monte Carlo method), also known as statistical simulation method, was proposed in the mid-1940s due to the development of science and technology and the invention of electronic computers, a method guided by probability and statistics theory. Class is very important numerical calculation method. Refers to the use of random numbers (or more commonly pseudo-random numbers) to solve many computational problems. Corresponding to it is the deterministic algorithm. Monte Carlo method is widely used in financial engineering, macroeconomics, computational physics (such as particle transport calculation, quantum thermodynamic calculation, aerodynamic calculation) and other fields. Monte Carlo

The Monte Carlo method is a method of collecting a large number of samples and then gradually approaching the optimal solution, as long as the method is to generate random numbers. It has many applications and contributions in finance, mathematics, etc. The principle of the option pricing model is this.

Realization ideas and methods: The author uses Monte Carlo's ideas to approximate the classical number pi. We calculate the number of points that fall on the quarter circle and the rest, and calculate the proportion of points that fall within the circle, and finally get the value of pi. The radius of the circle is 1, and the radius of the square is 1.
Insert picture description here

Look belowMatlabCode:

% 蒙特卡洛求pi的值
gen = 1000;
count = 0;
r=1;
theta=0:pi/100:2*pi;
x=r*cos(theta);                              
y=r*sin(theta);                              
plot(x,y)
xlim([0,1])
ylim([0,1])
title('蒙特卡洛方法求pi值')
hold on
for i = 1:gen
    a = rand;
    b = rand;
    plot(a,b,'.')
    pause(0.00001)
    if a^2 + b^2 < 1
        count = count + 1;
    end
end
p = count/gen*4;
disp(['pi的估计值为',num2str(p)])

The result shows that
Insert picture description here
because the number of dots here is only 1000, the reader can adjust the parameters, increase the value of gen, and finally it will be infinitely close to the value of pi 3.1415926...

Guess you like

Origin blog.csdn.net/wlfyok/article/details/107991424