如何生成0到1之间的加密安全Double? [英] How to generate a cryptographically secure Double between 0 and 1?

查看:92
本文介绍了如何生成0到1之间的加密安全Double?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何使用我知道如何使用加密安全的随机数生成器填充随机字节数组.

And I know how to fill a random byte array using the cryptographically secure random number generator.

Byte[] bytes = new Byte[8];
var rng2 = new System.Security.Cryptography.RNGCryptoServiceProvider();
rng2.GetBytes(bytes); // generates 8 random bytes

但是如何转换 RNGCryptoServiceProvider 变成均匀分布在0(含)和1(不含)之间的随机数?

But how can I convert the byte-array output of RNGCryptoServiceProvider into a random number uniformly distributed between 0 (inclusive) and 1 (exclusive)?

推荐答案

在我看来,到目前为止,由于采用逆运算,解决方案的分布将不均匀.对于平均分配,我认为您需要这样的东西.

It appears to me that the solutions so far will have uneven distribution due to taking the inverse. For an even distribution I'd think you want something like this.

// Step 1: fill an array with 8 random bytes
var rng = new RNGCryptoServiceProvider();
var bytes = new Byte[8];
rng.GetBytes(bytes);
// Step 2: bit-shift 11 and 53 based on double's mantissa bits
var ul = BitConverter.ToUInt64(bytes, 0) / (1 << 11);
Double d = ul / (Double)(1UL << 53);

请注意,您不能仅将UInt64划分为UInt64.MaxValue,因为双精度数位数不足,并且无法获取所有输入的唯一输出.因此,您可以/必须丢掉一些东西.

Note that you can't just divide the UInt64 into UInt64.MaxValue, because a double doesn't have enough bits, and there's no way to get unique outputs for all your inputs. So you can/must throw some bits away.

这篇关于如何生成0到1之间的加密安全Double?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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