在一系列值之间生成随机双精度 [英] Generating a random double between a range of values

查看:113
本文介绍了在一系列值之间生成随机双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im currently having trouble generating random numbers between -32.768 and 32.768. It keeps giving me the same values but with a small change in the decimal field. ex : 27.xxx.

在这里,我的代码将不胜感激。

Heres my code, any help would be appreciated.

#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;
}


推荐答案

我应该提一下重新使用C ++ 11编译器,您可以使用类似这样的东西,它实际上更易于阅读,更难弄乱:

I should mention if you're using a C++11 compiler, you can use something like this, which is actually easier to read and harder to mess up:

#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;
}

正如bames53所指出的,如果您将充分使用c ++ 11:

As bames53 pointed out, the above code can be made even shorter if you make full use of 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;
}

这篇关于在一系列值之间生成随机双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆