21.06.2014, 22:14
(
Последний раз редактировалось blewert; 17.09.2014 в 11:13.
)
I suppose you could use something like this to generate normalized random floating point numbers (between 0 and 1):
You could then multiply that normalized value by something to produce numbers specified by a maximum value (like random()):
Or even go as far to implement some form of range, like this:
Take for example, if I wanted to generate random numbers between 0 and 20, I might use something like:
Which gives me this output:
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;
}
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);
}
pawn Код:
stock Float:frandrange(const Float:min, const Float:max)
{
//Just offset range of random numbers by amount
return min + frand(max-min);
}
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));
}
Код:
0 to 20: ----- 18.555864 11.637317 6.126285 10.887173 1.890316