如何将FastRandom.NextDouble()转换为NextFloat()?

时间:2017-08-02 21:29:11

标签: c#

我在这里下载了一个FastRandom类: https://www.codeproject.com/Articles/9187/A-fast-equivalent-for-System-Random

该类有NextDouble(),但我也希望有一个NextFloat()方法。

// The +1 ensures NextDouble doesn't generate 1.0
const double REAL_UNIT_INT = 1.0 / ((double)int.MaxValue + 1.0);
const double REAL_UNIT_UINT = 1.0 / ((double)uint.MaxValue + 1.0);
const uint Y = 842502087, Z = 3579807591, W = 273326509;
uint x, y, z, w;

这是NextDouble()方法:

/// <summary>
/// Generates a random double. Values returned are from 0.0 up to but not including 1.0.
/// </summary>
/// <returns></returns>
public double NextDouble()
{
    uint t = (x ^ (x << 11));
    x = y; y = z; z = w;

    // Here we can gain a 2x speed improvement by generating a value that can be cast to 
    // an int instead of the more easily available uint. If we then explicitly cast to an 
    // int the compiler will then cast the int to a double to perform the multiplication, 
    // this final cast is a lot faster than casting from a uint to a double. The extra cast
    // to an int is very fast (the allocated bits remain the same) and so the overall effect 
    // of the extra cast is a significant performance improvement.
    //
    // Also note that the loss of one bit of precision is equivalent to what occurs within 
    // System.Random.
    return (REAL_UNIT_INT * (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)))));
}

所以,我想知道如何在不简单地将结果转换为float的情况下创建类似的函数。一个例子是赞赏的。

0 个答案:

没有答案