开发者

Better random function for C#

开发者 https://www.devze.com 2023-02-05 19:21 出处:网络
I\'m generating many random numbers and I need a good function, since this doesn\'t help much: public static class Randomizer

I'm generating many random numbers and I need a good function, since this doesn't help much:

public static class Randomizer
{
    static Random random = new Random((int)DateTime.Now.Ticks);

    public stat开发者_开发知识库ic int RandomInteger(int minimum, int maximum)
    {
        return random.Next(minimum, maximum + 1);
    }

    public static double RandomDouble()
    {
        return random.NextDouble();
    }
}

When I use this class, my numbers are very often the same. Do you have any simple idea how I can improve performance of the randomizer?

Thanks, Ivan


See System.Security.Cryptography.RandomNumberGenerator


Take a look into MiscUtil from Jon Skeet.

There is a static random class, that works without any problems.

By the way, do you need random or unique numbers?


The reason your numbers are the same is that you are creating a new Random every call to the class which means it will seed using the same number from the DateTime.Now.Ticks

You should make this a non static class. Instantiate it once and then call repeatedly the same function from the object

0

精彩评论

暂无评论...
验证码 换一张
取 消