开发者

Generate random float between two floats

I know this is a rather simple question, but I'm just not too good at maths.

I know how to generate a random float between 0 and 1:

float random = ((flo开发者_如何学Goat) rand()) / (float) RAND_MAX;
  • But what, if I want a function that given a range of two floats, returns a pseudorandom float in that range?

Example:

RandomFloat( 0.78, 4.5 ); //Could return 2.4124, 0.99, 4.1, etc.


float RandomFloat(float a, float b) {
    float random = ((float) rand()) / (float) RAND_MAX;
    float diff = b - a;
    float r = random * diff;
    return a + r;
}

This works by returning a plus something, where something is between 0 and b-a which makes the end result lie in between a and b.


float RandomFloat(float min, float max)
{
    // this  function assumes max > min, you may want 
    // more robust error checking for a non-debug build
    assert(max > min); 
    float random = ((float) rand()) / (float) RAND_MAX;

    // generate (in your case) a float between 0 and (4.5-.78)
    // then add .78, giving you a float between .78 and 4.5
    float range = max - min;  
    return (random*range) + min;
}


Random between 2 float :

float    random_between_two_int(float min, float max)    
{    
    return (min + 1) + (((float) rand()) / (float) RAND_MAX) * (max - (min + 1));    
}

Random between 2 int :

int    random_between_two_int(float min, float max)    
{    
    return rand() % (max - min) + min + 1;     
}


Suppose, you have MIN_RAND and MAX_RAND defining the ranges, then you can have the following:

const float MIN_RAND = 2.0, MAX_RAND = 6.0;
const float range = MAX_RAND - MIN_RAND;
float random = range * ((((float) rand()) / (float) RAND_MAX)) + MIN_RAND ;

This will provide you the number scaled to your preferred range. MIN_RAND, MAX_RAND can be any value, like say 2.5, 6.6 So, the function could be as:

float RandomFloat(float min, float max) {
    return  (max - min) * ((((float) rand()) / (float) RAND_MAX)) + min ;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜