Hello, Random Float Numbers Problem!
#5

I suppose you could use something like this to generate normalized random floating point numbers (between 0 and 1):

pawn Код:
stock Float:frandnorm(const RAND_MAX = 32767)
{
    //Using C's RAND_MAX constant, make a random number up to RAND_MAX and
    //divide it by RAND_MAX, normalizing it (higher RAND_MAX = higher precision)
    return Float:random(RAND_MAX) / Float:RAND_MAX;
}
You could then multiply that normalized value by something to produce numbers specified by a maximum value (like random()):

pawn Код:
stock Float:frand(const Float:max)
{
    //Result will never exceed max, because we're multiplying a normalized (0 .. 1) value
    //by the max (which will only ever give max or less)
    return (frandnorm() * max);
}
Or even go as far to implement some form of range, like this:

pawn Код:
stock Float:frandrange(const Float:min, const Float:max)
{
    //Just offset range of random numbers by amount
    return min + frand(max-min);
}
Take for example, if I wanted to generate random numbers between 0 and 20, I might use something like:

pawn Код:
stock Float:frandnorm(const RAND_MAX = 32767)
{
    return Float:random(RAND_MAX) / Float:RAND_MAX;
}

stock Float:frand(const Float:max)
{
    return (frandnorm() * max);
}

main()
{
    //Print out header
    printf("0 to 20:\r\n-----");

    //Generate 5 random numbers between the interval 0 to 20, and print them out!
    for(new i = 0; i < 5; i++)
        printf("%f", frand(20));
}
Which gives me this output:

Код:
0 to 20:
-----
18.555864
11.637317
6.126285
10.887173
1.890316
Reply


Messages In This Thread
Hello, Random Float Numbers Problem! - by danish007 - 21.06.2014, 21:20
Re: Hello, Random Float Numbers Problem! - by Bek_Loking - 21.06.2014, 21:21
Re: Hello, Random Float Numbers Problem! - by GeekSiMo - 21.06.2014, 21:23
Re: Hello, Random Float Numbers Problem! - by danish007 - 21.06.2014, 21:31
Re: Hello, Random Float Numbers Problem! - by blewert - 21.06.2014, 22:14
Re: Hello, Random Float Numbers Problem! - by Threshold - 21.06.2014, 23:20
Re: Hello, Random Float Numbers Problem! - by danish007 - 22.06.2014, 00:53

Forum Jump:


Users browsing this thread: 1 Guest(s)