本文介绍了Prolog:如何从列表中非均匀地随机选择一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人有任何 Prolog 代码可以从列表中非均匀地选择一个随机元素?

Does anyone have any Prolog code to non-uniformly select a random element from a list?

我想复制 numpy.random.choice 当给定与输入列表中的每个条目相关联的概率时.

I want to replicate the functionality of numpy.random.choice when given the probabilities associated with each entry in the input list.

推荐答案

我在 library(random) 中没有发现任何有用的东西.

I found nothing useful in library(random).

这是我的实现choice(Xs, Ps, Y):

choice([X|_], [P|_], Cumul, Rand, X) :-
    Rand < Cumul + P.
choice([_|Xs], [P|Ps], Cumul, Rand, Y) :-
    Cumul1 is Cumul + P,
    Rand >= Cumul1,
    choice(Xs, Ps, Cumul1, Rand, Y).
choice([X], [P], Cumul, Rand, X) :-
    Rand < Cumul + P.

choice(Xs, Ps, Y) :- random(R), choice(Xs, Ps, 0, R, Y).

它的工作原理是根据 中给出的概率递归构建 累积概率分布Ps,并检查随机数 R 是否低于该值.

It works by recursively building the cumulative probability distribution from the probabilities given in Ps, and checking if the random number R is below that.

注意:要正确运行,概率 Ps 的总和必须为 1,如果情况并非如此,则不会进行检查以警告您.

Note: to function correctly the probabilities Ps must sum to 1, no check is made to warn you if that is not the case.

示例:

?- choice([1,2,3], [0.1,0.2,0.7], Y).
Y = 3 .

?- choice([1,2,3], [0.1,0.2,0.7], Y).
Y = 1 .

?- choice([1,2,3], [0.1,0.2,0.7], Y).
Y = 2 .

?- choice([1,2,3], [0.1,0.2,0.7], Y).
Y = 3 .

?- choice([1,2,3], [0.1,0.2,0.7], Y).
Y = 2 .

?- choice([1,2,3], [0.1,0.2,0.7], Y).
Y = 3 .

?- choice([1,2,3], [0.1,0.2,0.7], Y).
Y = 3 .

?- choice([1,2,3], [0.1,0.2,0.7], Y).
Y = 3 .

?- choice([1,2,3], [0.1,0.2,0.7], Y).
Y = 3 .

?- choice([1,2,3], [0.1,0.2,0.7], Y).
Y = 3 .

?- choice([1,2,3], [0.1,0.2,0.7], Y).
Y = 3 .

...

这篇关于Prolog:如何从列表中非均匀地随机选择一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 16:39