简体   繁体   English

c 中的种子随机数

[英]seed random numbers in c

I am currently trying to teach myself c programming.我目前正在尝试自学 c 编程。 I am stuck on learning random numbers.我一直在学习随机数。 Many of the websites I visit use the time() function as a method of seeding the random number generator.我访问的许多网站都使用 time() function 作为播种随机数生成器的方法。 But many posts and websites I have read say that using the system clock as a method of producing random numbers is flawed.但是我读过的许多帖子和网站都说使用系统时钟作为产生随机数的方法是有缺陷的。 My question is "what exactly should I be using to generate truly random numbers? Should I just manipulate the numbers with arithmetic or is there something else? To be specific, I'm looking for the "best practices" that programmers follow to generate random numbers in the c programming language.我的问题是“我究竟应该使用什么来生成真正的随机数?我应该只用算术来操作数字还是有别的东西?具体来说,我正在寻找程序员遵循以生成随机数的“最佳实践” c 编程语言中的数字。

Here is an example of a website I am talking about:这是我正在谈论的网站的示例:

http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1042005782&id=1043284385 http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1042005782&id=1043284385

srand(time(NULL)) is good enough for general basic use. srand(time(NULL))足以满足一般的基本用途。 Its shortcomings are: 它的缺点是:

  • It's not suitable for cryptography, since it's possible for an attacker to predict the pseudo-random sequence. 它不适合密码术,因为攻击者有可能预测伪随机序列。 Random numbers used in cryptography need to be really unpredictable. 密码术中使用的随机数必须确实不可预测。
  • If you run the program several times in quick succession, the RNG will be seeded with the same or similar values (since the current time hasn't changed much), so you're likely to get similar pseudo-random sequences each time. 如果快速连续运行几次该程序,则RNG的种子将具有相同或相似的值(因为当前时间变化不大),因此您很可能每次都会获得相似的伪随机序列。
  • If you generate very many random numbers with rand , you're likely to find that they're not well-distributed statistically. 如果您使用rand生成了很多随机数,则很可能会发现它们在统计上分布不均。 This can be important if you're doing something like Monte Carlo simulations. 如果您要进行蒙特卡洛模拟之类的操作,这可能很重要。

There are more sophisticated RNG libraries available for cryptographic and statistical use. 有更多复杂的RNG库可供加密和统计使用。

In case if you want a random number, use: 如果需要随机数,请使用:

randomize () ; 

m = random(your limit); 
printf("%d", m);// dont forget to include stdlib

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM