具有概率的随机数 [英] Random number with Probabilities

查看:136
本文介绍了具有概率的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在特定范围内生成随机数的最佳方法(例如在Java中),其中每个数字都有一定的概率发生?

I am wondering what would be the best way (e.g. in Java) to generate random numbers within a particular range where each number has a certain probability to occur or not?

例如

使用以下概率从[1; 3]内生成随机整数:

Generate random integers from within [1;3] with the following probabilities:

P( 1)= 0.2

P(2)= 0.3

P(3)= 0.5

P(1) = 0.2
P(2) = 0.3
P(3) = 0.5

现在我正在考虑在[0; 100]内生成随机整数的方法并执行以下操作:

Right now I am considering the approach to generate a random integer within [0;100] and do the following:

如果是在[0; 20] - >我得到了我的随机数1.

如果它在[21; 50] - >我得到了我的随机数2.

如果它在[51; 100] - >我得到了我的随机数3.



你会说什么?

If it is within [0;20] --> I got my random number 1.
If it is within [21;50] --> I got my random number 2.
If it is within [51;100] --> I got my random number 3.

What would you say?

推荐答案

你的方式已经很好了,适用于任何范围。

Yours is a pretty good way already and works well with any range.

想一想:另一种可能性就是摆脱通过乘以常数乘数得到分数,然后建立d具有此乘数的 size 的数组。乘以10即可获得

Just thinking: another possibility is to get rid of the fractions by multiplying with a constant multiplier, and then build an array with the size of this multiplier. Multiplying by 10 you get

P(1) = 2
P(2) = 3
P(3) = 5

然后你创建一个反向值的数组 - '1'进入元素1和2,'2'到3到6,依此类推:

Then you create an array with the inverse values -- '1' goes into elements 1 and 2, '2' into 3 to 6, and so on:

P =(1,1,2,2,2,3,3,3) ,3,3);

P = (1,1, 2,2,2, 3,3,3,3,3);

然后你可以从这个数组中选择一个随机元素。

and then you can pick a random element from this array instead.

(添加。)使用kiruwka评论中示例的概率:

(Add.) Using the probabilities from the example in kiruwka's comment:

int[] numsToGenerate           = new int[]    { 1,   2,    3,   4,    5   };
double[] discreteProbabilities = new double[] { 0.1, 0.25, 0.3, 0.25, 0.1 };

导致全整数的最小乘数为20,这样就可以得到

the smallest multiplier that leads to all-integers is 20, which gives you

2, 5, 6, 5, 2

因此 numsToGenerate 的长度为20,具有以下值:

and so the length of numsToGenerate would be 20, with the following values:

1 1
2 2 2 2 2
3 3 3 3 3 3
4 4 4 4 4
5 5

分布完全相同:例如,'1'的概率为2 20分之一 - 仍然是0.1。

The distribution is exactly the same: the chance of '1', for example, is now 2 out of 20 -- still 0.1.

这是基于你的原始概率加起来为1.如果他们不加,则将总数乘以同一因子(然后也将是你的数组长度。)

This is based on your original probabilities all adding up to 1. If they do not, multiply the total by this same factor (which is then going to be your array length as well).

这篇关于具有概率的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆