Matlab 在内接正方形的圆内生成随机点的算法不能正常工作

Matlab 在内接正方形的圆内生成随机点的算法不能正常工作,matlab,probability,Matlab,Probability,我试图确定一个点在一个正方形内的概率,这个正方形内接一个半径为1的圆。首先,我在我的圆内生成N个随机点,然后检查每个点的Ox和Oy坐标是否分别小于宽度和高度的一半。我知道答案接近2/Pi,但我得到的数字接近0,78。。这不好 `close all;clear all;clc; %length of width and height a=sqrt(2); %radius of circle (it is 1) raza=a*sqrt(2)/2; %total number of points N

我试图确定一个点在一个正方形内的概率,这个正方形内接一个半径为1的圆。首先,我在我的圆内生成N个随机点,然后检查每个点的Ox和Oy坐标是否分别小于宽度和高度的一半。我知道答案接近2/Pi,但我得到的数字接近0,78。。这不好

`close all;clear all;clc;
%length of width and height
a=sqrt(2);
%radius of circle (it is 1)
raza=a*sqrt(2)/2; 
%total number of points
N=1000;

%Here I generate my N random numbers inside the circle
theta = 2*pi*rand(1,N);
r = rand(1,N);
x = r.*cos(theta);
y = r.*sin(theta);

%here I count how many point are inside the square that is inscribed in the 
%circle
cont = 0;
for i=1:N
    if x(i) >= -a/2 && x(i) <= a/2 && y(i) >= -a/2 && y(i) <= a/2
        cont = cont + 1; 
    end
end
%Here i get sth closer to 0,78...not 2/Pi(0,63..)
cont/N
`全部关闭;清除所有;clc;
%宽度和高度的长度
a=sqrt(2);
%圆的半径(它是1)
raza=a*sqrt(2)/2;
%总分
N=1000;
%这里我在圆圈内生成我的N个随机数
θ=2*pi*rand(1,N);
r=rand(1,N);
x=r*cos(θ);
y=r*sin(θ);
%在这里,我计算有多少点是在广场内,这是刻在地图上
%圈
cont=0;
对于i=1:N

如果x(i)>=-a/2&&x(i)=-a/2&&y(i)我发现有一个简单的错误,请参见下面的公式

square_area/circle_area = number_of_total/number_of_inside_circle
所以

因此,如果您计算
cont/N
,那么您尝试根据上述公式计算
pi/4
,并且'pi/4
等于
0.7854',那么您的收盘价

注意:如果要计算
pi
,则可以编写
4*cont/N

但是如果你想总结一下你的程序,你可以像下面这样写

n=2000;
x=2*rand(1,n)-1;
y=2*rand(1,n)-1;
inside_index = find(sqrt(x.^2+y.^2)<1); % find index of those point that are inside the circle
PI = 4*numel(inside_index)/n

我看到有一个简单的错误,请看下面的公式

square_area/circle_area = number_of_total/number_of_inside_circle
所以

因此,如果您计算
cont/N
,那么您尝试根据上述公式计算
pi/4
,并且'pi/4
等于
0.7854',那么您的收盘价

注意:如果要计算
pi
,则可以编写
4*cont/N

但是如果你想总结一下你的程序,你可以像下面这样写

n=2000;
x=2*rand(1,n)-1;
y=2*rand(1,n)-1;
inside_index = find(sqrt(x.^2+y.^2)<1); % find index of those point that are inside the circle
PI = 4*numel(inside_index)/n

您的随机点分布不均匀。他们会朝着圆圈的中心更密集。谢谢!这就是问题所在。在我修改了半径以这种方式计算后:r=sqrt(rand(1,N)),它工作得非常好!您的随机点分布不均匀。他们会朝着圆圈的中心更密集。谢谢!这就是问题所在。在我修改了半径以这种方式计算后:r=sqrt(rand(1,N)),它工作得非常好!