生成真正的随机数

编程入门 行业动态 更新时间:2024-10-25 04:18:59
本文介绍了生成真正的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: 有效生成随机数

我需要生成<$ c $应用程序中的随机数。我从阅读这两篇文章知道 -

I need to generate random numbers in my C++ application. I know from reading these two articles --

www.cprogramming/tutorial/random.html

write ac函数,用于生成一个随机数或一对随机数,或给定特定范围的三元组随机数

- 可以使用 srand() code>和 rand(),但在这两种情况下,根据系统时钟的当前时间用作a seed 。但我在第一篇文章中读到,如果种子是相同的, rand()将创建相同的随机数。因此,如果两个不同的用户在同一时间运行我的应用程序,那么他们将有相同的随机数。这将是无意义的,因为我需要随机数在大多数情况下是唯一的。 (我知道如果它们是随机产生的,它们不能真正100%独特)

-- that random numbers can be generated using srand() and rand() but in both cases the current time according to the system clock is used as a seed. But I read in the first article that rand() will create the same random numbers if the seed is the same. So if two different users ran my application at the same time then they would have the same random numbers. Which would be pointless because I need the random numbers to be unique for the most part. (I know they cant be truly 100% unique if they are generated randomly)

所以我的问题是我可以创建一个不是基于系统时间的随机种子,为什么 rand()产生相同的数字与相同的种子,并有一种方法使 rand()

So my question is can I create a random seed not based on system time and if so how, why does rand() produce the same numbers with the same seed and is there a way to make rand() produce different numbers with the same seed, or is there any other way to generate random numbers?

推荐答案

没有使用特殊的硬件(和即使那样,它是有争议的),没有这样的东西作为由计算机生成的真正的随机数。

Without using special hardware (and even then, it's debatable), there is no such thing as a truly random number generated by a computer.

这就是说;你唯一的问题是:你如何生成你的种子,使两个程序不会产生相同的数字。使用当前时间作为您的种子的部分是合理的,但是如你所理解,这还不够,因为两个程序可以同时生成他们的种子...所以你需要增加你的种子在程序之间将是唯一的。可能性包括进程ID(如果两个程序在同一台计算机上则不同),硬件MAC地址(如果两个程序在不同计算机上则不同),或者计时用户执行一些任务需要多长时间只要用户是人而不是自动化)。

That being said; your only problem is: how do you generate your seeds such that two programs will not generate the same number. Using the current time as part of your seed is reasonable, but as you understand, it's not enough because two programs could generate their seed at the same time... so you need to augment your seed based on something that will be unique between the programs. Possibilities include process ID (which will differ if both programs are on the same computer), hardware mac address (which will differ if both programs are on different computers), or timing how long it takes the user to perform some task (which will generally differ as long as the user is human, not automation).

更多推荐

生成真正的随机数

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

发布评论

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

>www.elefans.com

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