看来,为了生成给定的概率分布,我想要的是Quantile Function,它是
cumulative distribution function,正如@dmckee 所说。
问题变成了:生成和存储描述给定连续直方图的分位数函数的最佳方法是什么?我有一种感觉,答案将很大程度上取决于输入的形状——如果它遵循任何类型的模式,应该对最一般的情况进行简化。我会在这里更新。
编辑:
本周我的一次谈话让我想起了这个问题。如果我放弃将直方图描述为等式,而只存储表格,我可以在 O(1) 时间内进行选择吗?事实证明,您可以在不损失任何精度的情况下,以 O(N lgN) 的构建时间为代价。
创建一个包含 N 个项目的数组。对数组进行均匀随机选择将找到概率为 1/N 的项目。对于每个项目,存储实际应选择该项目的命中分数,以及如果该项目未选择则将选择的另一项目的索引。
加权随机抽样,C 实现:
//data structure
typedef struct wrs_data {
double share;
int pair;
int idx;
} wrs_t;
//sort helper
int wrs_sharecmp(const void* a, const void* b) {
double delta = ((wrs_t*)a)->share - ((wrs_t*)b)->share;
return (delta<0) ? -1 : (delta>0);
}
//Initialize the data structure
wrs_t* wrs_create(int* weights, size_t N) {
wrs_t* data = malloc(sizeof(wrs_t));
double sum = 0;
int i;
for (i=0;i<N;i++) { sum+=weights[i]; }
for (i=0;i<N;i++) {
//what percent of the ideal distribution is in this bucket?
data[i].share = weights[i]/(sum/N);
data[i].pair = N;
data[i].idx = i;
}
//sort ascending by size
qsort(data,N, sizeof(wrs_t),wrs_sharecmp);
int j=N-1; //the biggest bucket
for (i=0;i<j;i++) {
int check = i;
double excess = 1.0 - data[check].share;
while (excess>0 && i<j) {
//If this bucket has less samples than a flat distribution,
//it will be hit more frequently than it should be.
//So send excess hits to a bucket which has too many samples.
data[check].pair=j;
// Account for the fact that the paired bucket will be hit more often,
data[j].share -= excess;
excess = 1.0 - data[j].share;
// If paired bucket now has excess hits, send to new largest bucket at j-1
if (excess >= 0) { check=j--;}
}
}
return data;
}
int wrs_pick(wrs_t* collection, size_t N)
//O(1) weighted random sampling (after preparing the collection).
//Randomly select a bucket, and a percentage.
//If the percentage is greater than that bucket's share of hits,
// use it's paired bucket.
{
int idx = rand_in_range(0,N);
double pct = rand_percent();
if (pct > collection[idx].share) { idx = collection[idx].pair; }
return collection[idx].idx;
}
编辑 2:
经过一番研究,我发现甚至可以在 O(N) 时间内完成构建。通过仔细跟踪,您无需对数组进行排序即可找到大小箱。 Updated implementation here