【算法】均勻的生成圓內的隨機點


 

算法 1

設半徑為$R$。

$x = r \ast cos(\theta)$

$y = r \ast sin(\theta)$

其中 $0\leqslant r \leqslant R$,$t$為0-1均勻分布產生的隨機數,$r = sqrt(t) \ast R$,$\theta = 2\pi \ast t, t \sim U(0, 1)$ 證明:url

 1 import numpy as np
 2 import random
 3 import math
 4 import matplotlib.pyplot as plt
 5 import matplotlib as mpl
 6 mpl.rcParams['agg.path.chunksize'] = 10000 # the default is 0
 7 N = int(10000)
 8 x1 = 1.5
 9 x2 = 0.5
10 radius = 2
11 a = 2 * math.pi * np.array([random.random() for _ in range(N)])
12 r = np.array([random.random() for _ in range(N)])
13 x = radius*np.sqrt(r)*np.cos(a) + x1;
14 y = radius*np.sqrt(r)*np.sin(a) + x2;
15 plt.scatter(x, y, s=1)
16 plt.show()

 

下面的算法是錯誤的

原因在於對$R$求開方,導致$r = sqrt(R)*t$平方后不在滿足均勻分布。

 1 import numpy as np
 2 import random
 3 import math
 4 import matplotlib.pyplot as plt
 5 import matplotlib as mpl
 6 mpl.rcParams['agg.path.chunksize'] = 10000 # the default is 0
 7 N = int(10000)
 8 x1 = 1.5
 9 x2 = 0.5
10 radius = 2
11 a = 2 * math.pi * np.array([random.random() for _ in range(N)])
12 r = np.array([random.random() for _ in range(N)])
13 #x = radius*np.sqrt(r)*np.cos(a) + x1;
14 #y = radius*np.sqrt(r)*np.sin(a) + x2;
15 x = np.sqrt(radius)*r*np.cos(a) + x1;
16 y = np.sqrt(radius)*r*np.sin(a) + x2;
17 plt.scatter(x, y, s=1)
18 plt.show()

 參考鏈接:JustDoIT


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM