在一系列值之间生成随机双精度

Oli*_*ier 4 c++ random algorithm genetic prng

我目前无法在-32.768和32.768之间生成随机数.它不断给我相同的值,但十进制字段的变化很小.例如:27.xxx.

继承我的代码,任何帮助将不胜感激.

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main()
{
    srand( time(NULL) );
    double r = (68.556*rand()/RAND_MAX - 32.768);
    cout << r << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Car*_*arl 7

我应该提一下,如果你使用的是C++ 11编译器,你可以使用这样的东西,这实际上更容易阅读,更难搞乱:

#include <random>
#include <iostream>
#include <ctime>


int main()
{
    //Type of random number distribution
    std::uniform_real_distribution<double> dist(-32.768, 32.768);  //(min, max)

    //Mersenne Twister: Good quality random number generator
    std::mt19937 rng; 
    //Initialize with non-deterministic seeds
    rng.seed(std::random_device{}()); 

    // generate 10 random numbers.
    for (int i=0; i<10; i++)
    {
      std::cout << dist(rng) << std::endl;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

正如bames53所指出的,如果你充分利用c ++ 11,上面的代码可以更短:

#include <random>
#include <iostream>
#include <ctime>
#include <algorithm>
#include <iterator>

int main()
{
    std::mt19937 rng; 
    std::uniform_real_distribution<double> dist(-32.768, 32.768);  //(min, max)
    rng.seed(std::random_device{}()); //non-deterministic seed
    std::generate_n( 
         std::ostream_iterator<double>(std::cout, "\n"),
         10, 
         [&]{ return dist(rng);} ); 
    return 0;
}
Run Code Online (Sandbox Code Playgroud)