如何使用 C# 生成真正(非伪)随机数? [英] How can I generate truly (not pseudo) random numbers with C#?

查看:29
本文介绍了如何使用 C# 生成真正(非伪)随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 Random 类可以生成伪随机数,但有没有办法生成真正的随机数?

I know that the Random class can generate pseudo-random numbers but is there a way to generate truly random numbers?

推荐答案

这里的答案有两个主要方面.有一些非常重要的微妙之处,您应该注意...

The answer here has two main sides to it. There are some quite important subtleties to which you should pay due attention...

RNGCryptoServiceProvider 是 BCL 中 Crypto API 的一部分,应该为您完成这项工作.从技术上讲,它仍然是生成的伪随机数,但随机性"的质量要高得多 - 顾名思义,适用于加密目的.

The RNGCryptoServiceProvider, which is part of the Crypto API in the BCL, should do the job for you. It's still technically a pseudo-random number generated, but the quality of "randomness" is much higher - suitable for cryptographic purposes, as the name might suggest.

还有其他具有高质量伪随机生成器的加密 API.Mersenne twiner等算法非常流行.

There are other crypographic APIs with high quality pseudo random generaters available too. Algorithms such as the Mersenne twister are quite popular.

与 BCL 中的 Random 类相比,它要好得多.例如,如果您在图表上绘制 Random 生成的数字,您应该能够识别模式,这是弱点的强烈迹象.这主要是因为该算法仅使用固定大小的种子查找表.

Comparing this to the Random class in the BCL, it is significantly better. If you plot the numbers generated by Random on a graph, for example, you should be able to recognise patterns, which is a strong sign of weakness. This is largely due to the fact that the algorithm simply uses a seeded lookup table of fixed size.

要生成真正的随机数,需要利用一些自然现象,例如核衰变、微观温度波动(CPU 温度是一个比较方便的来源)等等.然而,这当然要困难得多,并且需要额外的硬件.我怀疑实用的解决方案(RNGCryptoServiceProvider 或类似的)应该非常适合你.

To generate truly random numbers, you need to make use of some natural phenomenon, such as nuclear decay, microscopic temperature fluctuations (CPU temperature is a comparatively conveient source), to name a few. This however is much more difficult and requires additional hardware, of course. I suspect the practical solution (RNGCryptoServiceProvider or such) should do the job perfectly well for you.

现在,请注意,如果您确实需要真正的随机数,您可以使用诸如 Random.org,它生成具有非常高随机性/熵的数字(基于大气噪声).数据可免费下载.尽管如此,这对于您的情况可能会不必要地复杂化,尽管它确实为您提供了适合科学研究之类的数据.

Now, note that if you really do require truly random numbers, you could use a service such as Random.org, which generates numbers with very high randomness/entropy (based on atmospheric noise). Data is freely available for download. This may nonetheless be unnecessarily complicated for your situation, although it certainly gives you data suitable for scientific study and whatnot.

最终选择权在您手中,但至少您现在应该能够做出信息丰富的决定,了解 RNG 的各种类型和级别.

The choice is yours in the end, but at least you should now be able to make an informative decision, being aware of the various types and levels of RNGs.

这篇关于如何使用 C# 生成真正(非伪)随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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