C++ random with seed

Hi! Good day,

Why is it random() returns different value on android and iOS with both same value of seed.

I made it in this way…

// set my seed value
srand(p_seed);

// then call random()
for( int i = 0; i < 10; i++ )
{
random()
}

The weird thing is… android returns same pattern. (which is correct). but on iOS, different patterns printed every run. O_O’ Do you guys have any idea? by the way Im running this on an iPhone5 and nexus7 device.

Thanks!

aries

Maybe the random algorithms are different. You can implement new one by yourself.


Hi!

you mean to say… different device platforms have different pseudo random implementation? D: and the link is kinda geek link O_O (The randomized_algorithm one).

Thanks BTW!

aries

Yes:)

FYI…

The purpose of random with seed for me is… for easy generating same random integers on different platforms.

You can try arc4random()

I’ve been using it on a game and it seems to work nicely.

Hi Lance,

arc4random() uses the current time as its seed (I think?). so maybe not applicable.

Thanks anyway :smiley:

or it seeds it self? please correct me if I sounds wrong. I am willing to learn things :smiley:

Hi, I’m using this class for generating random numbers since our app has multiplayer support on all platforms and consistent pseudo random numbers are very important:

Based on Java’s LinearRandom pseudo random number implementation

class Random
{
public:
    Random(void);
    Random( long seed);
    static void setSeed(long _seed);
    static int next();
public:
    static long seed;
    static long multiplier;
    static long addend;
    static long mask;
};

long Random::multiplier = 0x5DEECE6C;
long Random::addend = 0xB;
long Random::mask = (1L << 48) - 1;
long Random::seed= 0x2342dda;   

Random::Random(void)
{
    setSeed(time(NULL));
}

Random::Random( long seed) {
    setSeed(seed);
}

void Random::setSeed(long _seed) {
    seed = (unsigned)(_seed & 0x7fffffffU);
}

int Random::next() {
    seed = (seed * 1103515245U + 12345U) & 0x7fffffffU;
    return (int)(seed);
}

usage:

#define RANDOM(X) Random::next()%(int)X
#define RANDOM_SEED(X) Random::setSeed(X)


RANDOM(100); // random number between 0 and 99

Hope this helps

2 Likes

Oh wow! that is what Im absolutely looking for :smiley:

Thanks alot Cristian