![](/img/trans.png)
[英]How to generate a size 1000 random number list according to Poisson distribution and with a fixed mean(size)?
[英]Generate a random number according to a specific distribution with a function
我正在嘗試根據我用function f (theta) = 1 + alpha*cos(theta)²
定義的精確分布在 Python 中生成一個隨機數; 變量 alpha 是一個常數。
不幸的是我不知道該怎么做,因為不同的隨機函數都遵循預定義的分布(正態分布、均勻分布、二項分布...)
你有想法嗎?
假設f
與概率密度函數 (PDF) 成正比,您可以使用拒絕抽樣方法:在框中畫一個數字,直到框落在 PDF 內。 它適用於任何具有有限域的有界 PDF,只要您知道域和邊界是什么(邊界是域中f
的最大值)。 在這種情況下,邊界是1 + alpha
,算法的工作原理如下:
import math
import random
def sample(alpha):
mn=0 # Lowest value of domain
mx=math.pi # Highest value of domain
bound=1+alpha # Upper bound of PDF value
while True:
# Choose an X inside the desired sampling domain.
x=random.uniform(mn,mx)
# Choose a Y between 0 and the maximum PDF value.
y=random.uniform(0,bound)
# Calculate PDF
pdf=1+alpha*math.cos(x)**2
# Does (x,y) fall in the PDF?
if y<pdf:
# Yes, so return x
return x
# No, so loop
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.