随机数生成 - 数相同返回 [英] Random Number Generation - Same Number returned

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

问题描述

可能显示的文件:结果
   C# - 得到相同的随机数反复结果
  <一href=\"http://stackoverflow.com/questions/767999/random-number-generator-not-working-the-way-i-had-planned-c\">Random数生成器不工作我已经计划的方式(C#)

我有一个建立整数的队列的方法:

I have a method that builds a queue of ints:

public Queue<int> generateTrainingInts(int count = 60)
    {
        Queue<int> retval = new Queue<int>();

        for (int i = 0; i < count; i++)
        {
            retval.Enqueue(JE_Rand.rInt(2001, 100));
        }

        return retval;
    }

JE_Rand.rInt()仅仅是一个函数委托给Random类的函数:

JE_Rand.rInt() is just a function that delegates to a function of the Random class:

public static int rInt(int exclUB, int incLB = 0)
    {
        Random rand = new Random(DateTime.Now.Millisecond);
        int t = rand.Next(incLB, exclUB);
        rand = null;            
        return t;
    }

但是,当我打电话generateTrainingInts,同样的号码,每次排队。但是,如果我改变RINT使用静态实例Random类的,而不是本地实例(带功能范围,因为它上面定义的),那么它似乎正常工作(排队随机整数)。是否有人知道为什么会这样?

But when I call generateTrainingInts, the same number is enqueued each time. However, if I change rInt to use a static instance of the Random class, instead of a local instance (with function scope as it is defined above), then it appears to work correctly (enqueue random integers). Does anybody know why this happens?

编辑:
亲爱的答复者谁没有仔细阅读我的问题,
    就像你们当中有些人指出的那样,我要寻找的,为什么出现这种情况了很好的解释。我不是在寻找一个解决方案,以相同的号码产生的问题,因为我已经解决了,像我上面所说的。感谢您的热情虽然:)我真的只是想了解这样的事情,因为我的第一个实现概念对我来说更有意义。

Dear Answerers who didn't read my question thoroughly, Like some of you pointed out, I am looking for a good explanation of why this happens. I am not looking for a solution to the same-number-generated problem, because I already fixed that like I said above. Thanks for your enthusiasm though :) I really just want to understand things like this, because my first implementation made more sense conceptually to me.

推荐答案

您需要保持同样的随机对象。把它放在你的静态方法以外的静态成员

You need to keep the same Random object. Put it outside your static method as a static member

private static Random rand = new Random();

public static int rInt(int exclUB, int incLB = 0)
{
    int t = rand.Next(incLB, exclUB);
    return t;
}

修改结果
究其原因是时钟的有限分辨率用来初始化随机。随机的后续初始化会以随机顺序相同的起始位置。当在随机序列重复使用相同的随机的下一个值始终产生

Edit
The reason is the finite resolution of the clock used to initialize Random. Subsequent initializations of Random will get the same starting position in the random sequence. When reusing the same Random the next value in the random sequence is always generated.

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

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