随机数概率 [英] Random numbers probability

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

问题描述


我有一个枚举,它由四个元素(上,下,左,右)组成.
我想随机选择一个元素.
当前的问题是,大多数运行的应用程序都使我无法正常运行.
如何给每个元素25%的概率?

我的代码很简单:

Hi
I have a enum which consists of four elements (Up, Down, Left, Right).
I want to select randomly an element.
Th current problem is that most of the applications run gives me Up/Down.
How do I give a 25% probability for each element?

My code is simple:

Random rnd = new Random(DateTime.Now.Millisecond);
int randomGenerated = 0;
for (int index = 0; index < 20; index++)
{
    randomGenerated = rnd.Next(1, 301) / 100;
    Move((Directions)randomGenerated);
}



如您所见,我尝试生成1到301之间的值,以便为每个元素的选择提供更好的机会,但这没有帮助.

谢谢
Shahar



As you can see I tried to generate between 1 and 301 to give better chances for each element to be selected but it didn''t help.

Thanks
Shahar

推荐答案

Don''t.只需执行以下操作即可:
Don''t. Just do this:
Random rnd = new Random();
int randomGenerated = 0;
for (int index = 0; index < 20; index++)
{
    randomGenerated = rnd.Next(4);
    Move((Directions)randomGenerated);
}


随机数就是这样.通过将数字空间限制为0-300,然后除以100,可以减少获得随机分布的机会:


Random numbers are just that. By restricting your number space to 0-300 and then dividing by a hundred , you are reducing the chances of getting a random distribution:

0 : 100 chances in 301
1 : 100 chances in 301
2 : 100 chances in 301
3 :   1 chance  in 301



[edit]错字:十"代表一百"-OriginalGriff [/edit]



[edit]Typo: "ten" for "a hundred" - OriginalGriff[/edit]


我不明白您的问题...

I didn''t understand your problem...

enum Direction
{
  Up = 0, Down, Left, Right
}

static Direction GetRandomDirection(Random random)
{
    return (Direction)random.Next((int)Direction.Up, (int)Direction.Right + 1);
}



这对我来说很好.

由于Random是正态分布,因此P(Up)= P(Down)= P(Left)= P(Right)= 1/4 = 25%.



This works fine for me.

As Random is normally distributed, P(Up) = P(Down) = P(Left) = P(Right) = 1/4 = 25%.


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

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