1 回答
TA贡献1804条经验 获得超8个赞
您应该使用累积百分比。示例设置:
create table weights(label text, weight int, cumulative_percentage float);
insert into weights (label, weight) values
('A', 2),
('B', 3),
('C', 5);
update weights w
set cumulative_percentage = cumulative_sum::float/ total
from (
select
label,
sum(weight) over (order by label) as cumulative_sum,
sum(weight) over () as total
from weights
) s
where s.label = w.label;
所以表格看起来像这样:
select *
from weights
label | weight | cumulative_percentage
-------+--------+-----------------------
A | 2 | 0.2
B | 3 | 0.5
C | 5 | 1
(3 rows)
使用公用表表达式在循环中获取单个随机数:
with seed(r) as (select random())
select min(label)
from weights, seed
where r <= cumulative_percentage
或创建一个函数:
create or replace function get_percentageed_reward(r float)
returns text language sql as $$
select min(label)
from weights
where r <= cumulative_percentage
$$;
检查算法的结果:
select get_percentageed_reward(random()), count(*)
from generate_series(1, 100000)
group by 1
order by 1
get_percentageed_reward | count
-------------------------+-------
A | 20008
B | 30165
C | 49827
(3 rows)
添加回答
举报
