如何在c++中生成随机浮点数?
我想我可以用整数rand除以某个数,这足够了吗?
如何在c++中生成随机浮点数?
我想我可以用整数rand除以某个数,这足够了吗?
当前回答
drand48(3)是POSIX的标准方法。GLibC还提供了一个可重入版本drand48_r(3)。
该函数在SVID 3中被宣布过时,但没有提供足够的替代方案,因此IEEE Std 1003.1-2013仍然包含它,并且没有说明它将很快消失。
在Windows中,标准的方法是CryptGenRandom()。
其他回答
如果您使用的是c++而不是C,那么请记住,在技术报告1 (TR1)和c++ 0x草案中,他们在头文件中添加了用于随机数生成器的功能,我相信它与Boost是相同的。随机库和绝对更灵活和“现代”比C库函数,兰德。
该语法提供了选择生成器(如mersenne twister mt19937)然后选择分布(正态分布、伯努利分布、二项式分布等)的能力。
语法如下(无耻地借用本网站):
#include <iostream>
#include <random>
...
std::tr1::mt19937 eng; // a core engine class
std::tr1::normal_distribution<float> dist;
for (int i = 0; i < 10; ++i)
std::cout << dist(eng) << std::endl;
在现代c++中,你可以使用c++11附带的<random>头文件。 要获得随机浮点数,可以使用std::uniform_real_distribution<>。
你可以使用一个函数来生成数字,如果你不希望数字总是相同的,那就将引擎和分布设置为静态。 例子:
float get_random()
{
static std::default_random_engine e;
static std::uniform_real_distribution<> dis(0, 1); // rage 0 - 1
return dis(e);
}
理想的做法是将浮动对象放置在std::vector:这样的容器中:
int main()
{
std::vector<float> nums;
for (int i{}; i != 5; ++i) // Generate 5 random floats
nums.emplace_back(get_random());
for (const auto& i : nums) std::cout << i << " ";
}
示例输出:
0.0518757 0.969106 0.0985112 0.0895674 0.895542
以Boost.Random为例。你可以这样做:
float gen_random_float(float min, float max)
{
boost::mt19937 rng;
boost::uniform_real<float> u(min, max);
boost::variate_generator<boost::mt19937&, boost::uniform_real<float> > gen(rng, u);
return gen();
}
尝试一下,您可能会更好地传递相同的mt19937对象,而不是每次都构造一个新的对象,但希望您能理解。
rand()可用于在c++中生成伪随机数。结合RAND_MAX和一点数学运算,您可以在任意选择的间隔内生成随机数。这对于学习目的和玩具程序来说是足够的。如果需要真正具有正态分布的随机数,则需要使用更高级的方法。
这将生成一个从0.0到1.0的数字。
float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
这将生成一个从0.0到任意浮点数X的数字:
float r2 = static_cast <float> (rand()) / (static_cast <float> (RAND_MAX/X));
这将生成一个从任意LO到任意HI的数字:
float r3 = LO + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(HI-LO)));
注意,如果需要真正的随机数,rand()函数通常是不够的。
在调用rand()之前,必须首先通过调用srand()来“播种”随机数生成器。这应该在程序运行期间执行一次,而不是在每次调用rand()时执行一次。通常是这样做的:
srand (static_cast <unsigned> (time(0)));
为了调用rand或srand,你必须#include <cstdlib>。
为了调用time,你必须#include <ctime>。
#include <cstdint>
#include <cstdlib>
#include <ctime>
using namespace std;
/* single precision float offers 24bit worth of linear distance from 1.0f to 0.0f */
float getval() {
/* rand() has min 16bit, but we need a 24bit random number. */
uint_least32_t r = (rand() & 0xffff) + ((rand() & 0x00ff) << 16);
/* 5.9604645E-8 is (1f - 0.99999994f), 0.99999994f is the first value less than 1f. */
return (double)r * 5.9604645E-8;
}
int main()
{
srand(time(NULL));
...
我不能给出两个答案,所以这里是第二个答案。Log2随机数,很大程度上偏向于0.0f但它实际上是一个随机浮动1.0f到0.0f。
#include <cstdint>
#include <cstdlib>
#include <ctime>
using namespace std;
float getval () {
union UNION {
uint32_t i;
float f;
} r;
/* 3 because it's 0011, the first bit is the float's sign.
* Clearing the second bit eliminates values > 1.0f.
*/
r.i = (rand () & 0xffff) + ((rand () & 0x3fff) << 16);
return r.f;
}
int main ()
{
srand (time (NULL));
...