PDA

View Full Version : Seeded Random



Sculley
01-01-2012, 09:09 AM
Anyone know any good implementations for LScript returning -1 to 1 or 0 to 1 random values based on a seed?

Help is appreciated.

Stephen

Kryslin
01-14-2012, 11:00 PM
You could set up a simple linear-congruential generator in lscript...


__x0 = 0; //This is where your seed goes, and it gets cycled by the random function...

randomize: q
{
//Set your seed number
__x0 = q;
}

random:q
{
//q does nothing.
a = 214013; //Big Prime Number
c = 2531011; //Bigger Prime Number
x1 = ( x0 * a + c ) % 2^^24;
__x0 = x1;
//Return a floating point value between 0...1
//Just like ol' BASIC's RND function...
x1 /= 2^^24;
return(x1);
}

Call randomize to seed it, then use random to get your numbers. Cycle it a couple hundred - couple thousand times to get a really random number.


For a range of -1 to 1, multiply by 2, subtract 1.

Sculley
03-28-2012, 03:50 PM
Many thanx, its the same code I ended up working with as well.


// RANDOM

_randomseed = 0; // n Seed

randomseed: seed
{
_randomseed = seed;
}

random
{
n = (_randomseed * 214013 + 2531011) % 2^^24;
_randomseed = n;
n /= 2^^24; // 0..1
return(n);
}

Alexx
03-27-2013, 03:56 PM
Hi,

Simpler solution :

initialize your seed with :
randu(seed);

then always use randu() to generate your random numbers:



custom_random: mi, ma
{
var value = mi + randu() * (ma - mi);
if (mi.isInt())
{
return round( value, 0 );
}
else
{
return value;
}
}

// bonus function : this one will return a random number which will tend towards "mi" or "ma" according to "bia",
// with bia=-1 you'll get more random values near "mi" and with bia = 1 you'll get more random values near "ma",
// with bia = 0, you'll get the default balanced andom results.
// of course you can use any float value between -1 and 1 for the bias.
random_bias: mi, ma, bia
{
var maxval = 1000.0;
var maxilog = log( maxval );
if (bia < -1)
{
bia = -1;
}
if (bia > 1)
{
bia = 1;
}
var r = custom_random( 1, maxval );
var lval;
if (bia > 0)
{
lval = log( r ) / maxilog * maxval;
r = lval * bia + r * (1 - bia);
}
if (bia < 0)
{
lval = log( r ) / maxilog * maxval;
r = maxval - 1 + lval * bia - r * (1 + bia);
}
r = mi + (ma - mi) * r / maxval;
return r;
}