简体   繁体   English

产生从负到正范围的随机浮动?

[英]Producing random float from negative to positive range?

I am trying to produce a random float within the range -50.0 and 50.0 inclusively, using rand(). 我试图使用rand()在-50.0和50.0范围内产生一个随机浮点数。 I've looked everywhere for an answer but it deals with ints and % operator. 我到处寻找答案,但它处理的是int和%运算符。

Try this: 试试这个:

float RandomNumber(float Min, float Max)
{
    return ((float(rand()) / float(RAND_MAX)) * (Max - Min)) + Min;
}

Try this: 试试这个:

  1. rand() gives you a number between 0 and RAND_MAX rand()为您提供0到RAND_MAX之间的数字
  2. so divide by RAND_MAX to get a number between 0 and 1 因此除以RAND_MAX以获得介于0和1之间的数字
  3. you desire a range of 100 from -50 to 50, so multiply by 100.0 你希望从-50到50的范围是100,所以乘以100.0
  4. finally shift the center from 50 (between 0 and 100 per point 3) to zero by subtracting 50.0 最后通过减去50.0将中心从50(每点3在0到100之间)移到零
((float)rand())/RAND_MAX * 100.0 - 50.0

Honestly, all present answers don't explain that there is a change in distribution in their solutions(I am assuming that rand() follows the uniform distribution! correct me if I am wrong please). 老实说,所有目前的答案都没有解释他们的解决方案中的分布发生了变化(我假设rand()遵循统一分布!如果我错了请纠正我)。 Use a library please, and my recommendation is using the new facilities in C++0x: 请使用库,我的建议是使用C ++ 0x中的新工具:

#include <random>
#include <functional>

int main()
{
    std::mt19937 generator;
    std::uniform_real_distribution<float> uniform_distribution(-50.0, 50.0);
    auto my_rand = std::bind(uniform_distribution, generator);
}

If you can't, Boost is a perfect choice. 如果你做不到,Boost是一个完美的选择。 That way, you can use my_rand() just like good ol' rand(): 这样,你可以使用my_rand()就像好的'rand():

std::vector<float> random_numbers(1000);
std::generate(random_numbers.begin(), random_numbers.end(), my_rand);

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

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