jeudi 7 septembre 2023

How to generate random double with RandomNumberGenerator in .NET 6

In .NET 6, as RNGCryptoServiceProvider has been marked as obsolete in .NET, I'm trying to find an alternative to generate evenly distributed random doubles (between 0 inclusive and 1 exclusive). I need something reliable both running on Windows or Linux.

I've found this online and I'd like to know if it reliable and how can I test the distribution.

        // Step 1: fill an array with 8 random bytes
        byte[] bytes = RandomNumberGenerator.GetBytes(8);

        // Step 2: bit-shift 11 and 53 based on double's mantissa bits
        ulong ul = BitConverter.ToUInt64(bytes, 0) / (1 << 11);
        return ul / (double)(1UL << 53);



Aucun commentaire:

Enregistrer un commentaire