如何使用 C# 生成真正(非伪)随机数?

编程入门 行业动态 更新时间:2024-10-25 08:23:03
本文介绍了如何使用 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,它生成具有非常高随机性/熵的数字(基于大气噪声).数据可免费下载.尽管如此,这对于您的情况可能会不必要地复杂化,尽管它确实为您提供了适合科学研究之类的数据.

Now, note that if you really do require truly random numbers, you could use a service such as Random, 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# 生成真正(非伪)随机数?

本文发布于:2023-11-30 21:11:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651484.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机数   如何使用

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!