生成具有给定概率的随机数matlab [英] Generate random number with given probability matlab

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

问题描述

我想以给定的概率生成一个随机数,但我不知道如何:

I want to generate a random number with a given probability but I'm not sure how to:

我需要一个介于 1 和 3 之间的数字

I need a number between 1 and 3

num = ceil(rand*3);

但我需要不同的值来产生不同的概率.

but I need different values to have different probabilities of generating eg.

0.5 chance of 1
0.1 chance of 2
0.4 chance of 3

我确定这很简单,但我想不出怎么做.

I'm sure this is straightforward but I can't think of how to do it.

推荐答案

简单的解决方案是生成一个均匀分布的数字(使用 rand),并稍微操作一下:

The simple solution is to generate a number with a uniform distribution (using rand), and manipulate it a bit:

r = rand;
prob = [0.5, 0.1, 0.4];
x = sum(r >= cumsum([0, prob]));

或单线:

x = sum(rand >= cumsum([0, 0.5, 0.1, 0.4]));

说明

这里r是0到1之间均匀分布的随机数.要生成1到3之间的整数,诀窍是将[0, 1]范围分成3段,其中每个段的长度与其对应的概率成正比.在您的情况下,您将:

Explanation

Here r is a uniformly distributed random number between 0 and 1. To generate an integer number between 1 and 3, the trick is to divide the [0, 1] range into 3 segments, where the length of each segment is proportional to its corresponding probability. In your case, you would have:

  • 段 [0, 0.5),对应于数字 1.
  • 段 [0.5, 0.6),对应于数字 2.
  • 段 [0.6, 1],对应于数字 3.

r 落入任何段的概率与您想要的每个数字的概率成正比.sum(r >= cumsum([0, prob])) 只是一种将整数映射到其中一个段的奇特方式.

The probability of r falling within any of the segments is proportional to the probabilities you want for each number. sum(r >= cumsum([0, prob])) is just a fancy way of mapping an integer number to one of the segments.

如果您对创建随机数的向量/矩阵感兴趣,可以使用循环或 arrayfun:

If you're interested in creating a vector/matrix of random numbers, you can use a loop or arrayfun:

r = rand(3); % # Any size you want
x = arrayfun(@(z)sum(z >= cumsum([0, prob])), r);

当然也有向量化的方案,就是懒得写了.

Of course, there's also a vectorized solution, I'm just too lazy to write it.

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

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