从C#中的0到1之间的随机字节数组中获取随机双精度(浮点)值? [英] Get random double (floating point) value from random byte array between 0 and 1 in C#?

查看:59
本文介绍了从C#中的0到1之间的随机字节数组中获取随机双精度(浮点)值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字节数组,这些字节是真正随机的(例如从熵源捕获).

Assume I have an array of bytes which are truly random (e.g. captured from an entropy source).

byte[] myTrulyRandomBytes = MyEntropyHardwareEngine.GetBytes(8);

现在,我想获得一个随机的双精度浮点值,但是在0和正1之间的值(例如 Random.NextDouble()函数执行).

Now, I want to get a random double precision floating point value, but between the values of 0 and positive 1 (like the Random.NextDouble() function performs).

仅将8个随机字节的数组传递给 BitConverter.ToDouble()会产生奇怪的结果,但最重要的是,结果几乎永远不会小于1.

Simply passing an array of 8 random bytes into BitConverter.ToDouble() can yield strange results, but most importantly, the results will almost never be less than 1.

我对位操作没问题,但是浮点数的格式对我来说一直很神秘.我尝试了多种位组合以应用随机性,并最终发现数字要么刚好超过1,始终非常接近0,要么就非常大.

I am fine with bit-manipulation, but the formatting of floating point numbers has always been mysterious to me. I tried many combinations of bits to apply randomness to and always ended up finding the numbers were either just over 1, always VERY close to 0, or very large.

有人可以解释在 double 中应该随机设置哪些位,以使其在0到1的范围内随机化吗?

Can someone explain which bits should be made random in a double in order to make it random within the range 0 and 1?

推荐答案

这比您想象的要容易.一切都与缩放有关(从0-1范围变为其他范围时也是如此).

This is easier than you think; its all about scaling (also true when going from a 0-1 range to some other range).

基本上,如果您知道自己有64个真正的随机位(8个字节),则只需执行以下操作:

Basically, if you know that you have 64 truly random bits (8 bytes) then just do this:

double zeroToOneDouble = (double)(BitConverter.ToUInt64(bytes) / (decimal)ulong.MaxValue);

当您的随机"比特实际上不是均匀地随机分布时,这种算法就会出现麻烦.那时,您需要一种特殊的算法,例如 Merenne Twister .

The trouble with this kind of algorithm comes when your "random" bits aren't actually uniformally random. That's when you need a specialized algorithm, such as a Mersenne Twister.

这篇关于从C#中的0到1之间的随机字节数组中获取随机双精度(浮点)值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆