开发者

generate float random numbers

I want to generate float numbers between 0 and 1, here is my code

    struct generate_rand
    {
        generate_rand()
        {
            srand(time(NULL));
        }
        float operator()()
        {
            return (rand()%255)/255;
        }
    }generate_f;

    std::vector<float> color(200);
    s开发者_运维知识库td::generate(color.begin(), color.end(), generate_f);

but the vector contains all ZERO, and the compiler yield a warning: 'return' : conversion from 'int' to 'float', possible loss of data. If I modify the code like this, return rand()/255; the result are all int type. So what the reason?


as Naveen said, the integer arithmetics will make it an integer result. Also, you may want to consider using

(float) rand() / RAND_MAX

to get a number from 0 to 1 with better granularity.


Someone already answer your precise question. But maybe you would be interested by a different approach, using the boot libraries for it?

If interested, check out this linkboost and example below:

#include <iostream>
#include <boost/random.hpp>
#include <time.h>
using namespace std;
using namespace boost;

int main ( )  {

    uniform_real<> distribution(0, 1) ;
    mt19937 engine; 
    engine.seed(time(NULL));   
    variate_generator<mt19937, uniform_real<> > myrandom (engine, distribution);

    for (int i=0; i<3; ++i)
        cout << myrandom() << endl;

}


The problem is (rand()%255)/255 performs an integer division as all its operands are integers. So the result is always 0. You should change one of them to float. The simplest is to use 255.0 as the divisor.


Naveen answered correctly. Nonetheless, a better approach would be this one:

struct generate_rand
{
    generate_rand()
    {
        srand(time(NULL));
    }
    float operator()()
    {
        return rand()/(float)RAND_MAX;
    }
} generate_f;

because you get "better" random values.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜