圆上的随机点

问题描述

有没有办法在圆上随机散布预定数量的点?下面的示例在正方形上随机散布点,但我需要该区域为圆形。

clear
set seed 101010
set obs 225           // There should be 225 dots on the circle. 
gen x1 = runiform()
gen y1 = runiform()

twoway  (scatter x1 y1 ///,graphregion(color(white)) xtitle("") ytitle("") ///
        yscale(lstyle(none)) xscale(lstyle(none)) ///
        ylabel(none,nolabels noticks nogrid) xlabel(none,nolabels noticks nogrid))

编辑 下面的代码概述了一个可能的解决方案,但点没有分布 均匀地穿过该区域。由于这在有大量点时最为明显,因此下面的代码生成了 10000 个观察值。

知道如何使点均匀分布在整个区域吗?

clear 
set obs 10000
gen obs = _n
gen N = _N
gen y = runiform()
gen angle = obs * 2 * _pi / N

gen obsx = y * cos(angle)
gen obsy = y * sin(angle)

twoway scatter obsx obsy,msize(tiny) graphregion(color(white)) xtitle("") ytitle("") ///
            yscale(lstyle(none)) xscale(lstyle(none)) ysize(1) xsize(1) ///
            ylabel(none,nolabels noticks nogrid)  

解决方法

clear
set seed 101010
set obs 225
gen x1 = 2 * (runiform() - 0.5) 
gen y1 = 2 * (runiform() - 0.5)

twoway  (scatter x1 y1 if (x1^2 + y1^2 < 1) ///,graphregion(color(white)) xtitle("") ytitle("") ///
        yscale(lstyle(none)) xscale(lstyle(none)) aspect(1)  ///
        ylabel(none,nolabels noticks nogrid) xlabel(none,nolabels noticks nogrid))
,

根据 Nick Cox 在评论中的建议,这里是生成的代码 圆上随机指定数量的点。

clear 
set seed 1010101
set obs 10000
gen obs = _n
gen N = _N
gen y = sqrt(runiform())
gen angle = obs * 2 * _pi / N

gen obsx = (y * cos(angle))
gen obsy = (y * sin(angle))

* Keep required number of dots
generate random = runiform()
sort random
keep if _n <= 250

twoway scatter obsx obsy,graphregion(color(white)) xtitle("") ytitle("") ///
            yscale(lstyle(none)) xscale(lstyle(none)) ysize(1) xsize(1) ///
            ylabel(none,nolabels noticks nogrid)  

enter image description here

,

这是一个答案,1) 对任何边界半径进行概括(这可能对您没有用);和 2) 从显式使用 N 中抽象出来。


clear 
set seed 101010
set obs 250
gen obs = _n
scalar R = 1 // set the  bounding radius
gen y = R * sqrt(runiform()) // random "sub" radius
gen angle = runiform() * 2 * _pi

gen obsx = y * cos(angle)
gen obsy = y * sin(angle)

twoway scatter obsx obsy,msize(tiny) graphregion(color(white)) xtitle("") ytitle("") ///
            yscale(lstyle(none)) xscale(lstyle(none)) ysize(1) xsize(1) ///
            ylabel(none,nolabels noticks nogrid)