如何生成20位数的随机数?

时间:2017-09-19 07:57:33

标签: c# random numbers

我想在c#中使用SFMT prng库生成一个安全的随机数,但它不适用于long int(对于> = 19位数)。请给我一个关于如何在C#中使用SFMT PRNG(mersenne twister)进行长int的提示?

Randoms.next(int min,int max); 但是如何使用long int?

1 个答案:

答案 0 :(得分:1)

您可以按如下方式为Random编写扩展方法:

public static class RandomExt
{
    public static long NextLong(this Random self, long min, long max)
    {
        // Get a random 64 bit number.

        var buf = new byte[sizeof(ulong)];
        self.NextBytes(buf);
        ulong n = BitConverter.ToUInt64(buf, 0);

        // Scale to between 0 inclusive and 1 exclusive; i.e. [0,1).

        double normalised = n / (ulong.MaxValue + 1.0);

        // Determine result by scaling range and adding minimum.

        double range = (double)max - min;

        return (long)(normalised * range) + min;
    }

    public static ulong NextULong(this Random self, ulong min, ulong max)
    {
        // Get a random 64 bit number.

        var buf = new byte[sizeof(ulong)];
        self.NextBytes(buf);
        ulong n = BitConverter.ToUInt64(buf, 0);

        // Scale to between 0 inclusive and 1 exclusive; i.e. [0,1).

        double normalised = n / (ulong.MaxValue + 1.0);

        // Determine result by scaling range and adding minimum.

        double range = (double)max - min;

        return (ulong)(normalised * range) + min;
    }
}

(我用于在[0,1]范围内创建随机双精度的算法与Random类使用的算法相同,只不过我将其转换为使用ulong而不是{ {1}}。)

然后你可以这样做:

ushort

理想情况下,您可以使用周期较长的更好的随机数生成器(例如XOR-SHIFT),但这会为您提供指定范围内的随机数。