【问题标题】:Algorithm to generate random points inside a circle which has a square inscribed in it not working as it should在一个圆圈内生成随机点的算法,该圆圈内有一个正方形,不能正常工作
【发布时间】:2018-05-01 14:54:09
【问题描述】:

我尝试确定点位于半径为 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

我是否以错误的方式生成点,或者我不正确地计算正方形内的点?

`

【问题讨论】:

  • 你的随机点分布不均匀。靠近圆心,它们会变得更密集。
  • 谢谢!这就是问题所在。在我修改了要以这种方式计算的半径后: r = sqrt(rand(1,N)) 它完美地工作!

标签: matlab probability


【解决方案1】:

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

square_area/circle_area = number_of_total/number_of_inside_circle

所以

(2*R)^2/(pi*R^2) = n_total/n_Indide  --> 4*R^2/pi*R^2=n/cont --> 4/pi = n/con 

所以如果你计算cont/N,那么你尝试根据上面的公式和'pi/4is equal to0.7854'计算pi/4,所以你关闭

注意:如果你想计算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

给了你

PI =

  3.1540

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-13
    • 2018-12-15
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多