随机浮点数生成 [英] Random float number generation
问题描述
如何在C ++中生成随机浮点数?
How do I generate random floats in C++?
我以为我可以将整数兰特除以某物,这样就足够了吗?
I thought I could take the integer rand and divide it by something, would that be adequate enough?
推荐答案
rand()
可用于在C ++中生成伪随机数.结合RAND_MAX
和一些数学运算,您可以选择任意间隔生成随机数.这足以用于学习目的和玩具程序.如果您需要具有正态分布的真正随机数,则需要采用更高级的方法.
rand()
can be used to generate pseudo-random numbers in C++. In combination with RAND_MAX
and a little math, you can generate random numbers in any arbitrary interval you choose. This is sufficient for learning purposes and toy programs. If you need truly random numbers with normal distribution, you'll need to employ a more advanced method.
这将生成一个介于0.0到1.0之间的数字.
This will generate a number from 0.0 to 1.0, inclusive.
float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
这将生成一个从0.0到任意float
,X
的数字:
This will generate a number from 0.0 to some arbitrary float
, X
:
float r2 = static_cast <float> (rand()) / (static_cast <float> (RAND_MAX/X));
这将生成一个从任意LO
到任意HI
的数字:
This will generate a number from some arbitrary LO
to some arbitrary HI
:
float r3 = LO + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(HI-LO)));
请注意,如果您需要真正的随机数,rand()
函数通常是不够的.
Note that the rand()
function will often not be sufficient if you need truly random numbers.
在调用rand()
之前,您必须先通过调用srand()
播种"随机数生成器.这应该在程序运行期间执行一次,而不是每次调用rand()
一次.通常这样做是这样的:
Before calling rand()
, you must first "seed" the random number generator by calling srand()
. This should be done once during your program's run -- not once every time you call rand()
. This is often done like this:
srand (static_cast <unsigned> (time(0)));
要呼叫rand
或srand
,您必须#include <cstdlib>
.
要呼叫time
,您必须#include <ctime>
.
这篇关于随机浮点数生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!