简体   繁体   English

如何从随机字节数组值中获取随机双值?

[英]How to get random double value out of random byte array values?

I would like to use RNGCryptoServiceProvider as my source of random numbers. 我想使用RNGCryptoServiceProvider作为随机数的来源。 As it only can output them as an array of byte values how can I convert them to 0 to 1 double value while preserving uniformity of results? 因为它只能将它们作为字节值数组输出,如何将它们转换为0到1的双精度值,同时保持结果的一致性?

byte[] result = new byte[8];
rng.GetBytes(result);
return (double)BitConverter.ToUInt64(result,0) / ulong.MaxValue;

This is how I would do this. 我就是这样做的。

private static readonly System.Security.Cryptography.RNGCryptoServiceProvider _secureRng;
public static double NextSecureDouble()
{
  var bytes = new byte[8];
  _secureRng.GetBytes(bytes);
  var v = BitConverter.ToUInt64(bytes, 0);
  // We only use the 53-bits of integer precision available in a IEEE 754 64-bit double.
  // The result is a fraction, 
  // r = (0, 9007199254740991) / 9007199254740992 where 0 <= r && r < 1.
  v &= ((1UL << 53) - 1);
  var r = (double)v / (double)(1UL << 53);
  return r;
}

Coincidentally 9007199254740991 / 9007199254740992 is ~= 0.99999999999999988897769753748436 which is what the Random.NextDouble method will return as it's maximum value (see https://msdn.microsoft.com/en-us/library/system.random.nextdouble(v=vs.110).aspx ). 巧合的是9007199254740991 / 9007199254740992 is ~= 0.99999999999999988897769753748436这是Random.NextDouble方法将返回的最大值(参见https://msdn.microsoft.com/en-us/library/system.random.nextdouble(v=vs。 110).aspx )。

In general, the standard deviation of a continuous uniform distribution is (max - min) / sqrt(12). 通常,连续均匀分布的标准偏差是(max-min)/ sqrt(12)。

With a sample size of 1000 I'm reliably getting within a 2% error margin. 样本大小为1000,我可以在2%的误差范围内可靠地获得。

With a sample size of 10000 I'm reliably getting within a 1% error margin. 样本大小为10000我可靠地获得1%的误差范围。

Here's how I verified these results. 以下是我验证这些结果的方法。

[Test]
public void Randomness_SecureDoubleTest()
{
  RunTrials(1000, 0.02);
  RunTrials(10000, 0.01);
}

private static void RunTrials(int sampleSize, double errorMargin)
{
  var q = new Queue<double>();

  while (q.Count < sampleSize)
  {
    q.Enqueue(Randomness.NextSecureDouble());
  }

  for (int k = 0; k < 1000; k++)
  {
    // rotate
    q.Dequeue();
    q.Enqueue(Randomness.NextSecureDouble());

    var avg = q.Average();

    // Dividing by n−1 gives a better estimate of the population standard
    // deviation for the larger parent population than dividing by n, 
    // which gives a result which is correct for the sample only.

    var actual = Math.Sqrt(q.Sum(x => (x - avg) * (x - avg)) / (q.Count - 1));

    // see http://stats.stackexchange.com/a/1014/4576

    var expected = (q.Max() - q.Min()) / Math.Sqrt(12);

    Assert.AreEqual(expected, actual, errorMargin);
  }
}

You can use the BitConverter.ToDouble(...) method. 您可以使用BitConverter.ToDouble(...)方法。 It takes in a byte array and will return a Double. 它接受一个字节数组并返回一个Double。 Thre are corresponding methods for most of the other primitive types, as well as a method to go from the primitives to a byte array. Thre是大多数其他原始类型的对应方法,以及从基元到字节数组的方法。

Use BitConverter to convert a sequence of random bytes to a Double: 使用BitConverter将随机字节序列转换为Double:

byte[] random_bytes = new byte[8];  // BitConverter will expect an 8-byte array
new RNGCryptoServiceProvider().GetBytes(random_bytes);

double my_random_double = BitConverter.ToDouble(random_bytes, 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM