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

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

问题描述

可能的重复:
c# - 重复获取相同的随机数
随机数生成器没有按照我计划的方式工作(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.

推荐答案

您需要保持相同的 Random 对象.把它作为静态成员放在你的静态方法之外

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;
}

编辑
原因是用于初始化Random 的时钟分辨率有限.Random 的后续初始化将在随机序列中获得相同的起始位置.当重用相同的 Random 时,总是生成随机序列中的下一个值.

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天全站免登陆