Random floating point numbers.

Started by ., Mar 02, 2016, 03:13 AM

Previous topic - Next topic

.

Self explanatory. True random floating point numbers with actual fractional part that is also random. Not integers converted to floating points without a fractional part.

const INT32_MAX = 0x7FFFFFFF;
const INT32_MIN = 0x80000000;
FLOAT32_MAX <- INT32_MAX.tofloat();
FLOAT32_MIN <- INT32_MIN.tofloat();

srand((GetTickCount() % time()) / 3);

function RandomFloat()
{
    return (FLOAT32_MAX - FLOAT32_MIN) *
            ((rand() % 0x7FFF).tofloat() / (RAND_MAX).tofloat()) + FLOAT32_MIN;
}

function RandomFloatUpto(n)
{
    n = n.tofloat();
    return (rand() % 0x7FFF).tofloat() / (RAND_MAX / n).tofloat();
}

function RandomFloatBetween(m, n)
{
    m = m.tofloat(), n = n.tofloat();
    return (n - m) * ((rand() % 0x7FFF).tofloat() / (RAND_MAX).tofloat()) + m;
}

Example:

print( RandomFloat() );
print( RandomFloatUpto(7.4) );
print( RandomFloatBetween(3.2, 5.9) );
.