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

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

问题描述

我想知道在特定范围内生成随机数的最佳方法是什么(例如在 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.

只是想:另一种可能是通过乘以一个常数乘数来去掉分数,然后用这个乘数的大小构建一个数组.乘以 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"的几率现在是 20 分之 2 —— 仍然是 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天全站免登陆