0

I am developing an application in PHP and C but the result of rand is different between the two languages, even though I am using the same seed:

PHP:

srand(1);
$random = rand(); // returns 32422

C:

srand(1);
int random = rand(); // returns 41

Why is this happening?

NullUserException
  • 83,810
  • 28
  • 209
  • 234
  • 7
    So they use different generators. That's not very surprising. – chris Jan 28 '13 at 20:07
  • 2
    Wow! Fascinating! Pseudo-random number generators return different results! (Nothing in the PHP documents states that `rand()` (PHP) uses `rand()` (C). Even then, you don't know whether both use the same seed). – Zeta Jan 28 '13 at 20:07
  • thats why they are called random. Both might be using different pseudo random algos – Deepankar Bajpeyi Jan 28 '13 at 20:07
  • Yes it is. Why do you expect them to be the same? Is there anywhere in the PHP specs that PHP's `rand()` should behave exactly the same way as C's one? –  Jan 28 '13 at 20:07
  • who told you they should generate same output? – Vahid Farahmand Jan 28 '13 at 20:07
  • 1
    my apple is not like my orange, why? –  Jan 28 '13 at 20:09
  • 7
    The question isn't as bad as it looks like at first glance, but it's still pretty bad. It still boils down to the basic answer that PHP and C use a different PRNG. You could have them return the same thing if you made them use the same PRNG. One possible way to do that would be to use a common library, like OpenSSL. – NullUserException Jan 28 '13 at 20:12
  • 5
    @NullUserException: Wy is "it pretty bad" !!! If it boils down to a single answer then it is a perfect question for SO (there is no ambiguity) and thus a real question. I just voted to re-open. This happens a lot. Having an answer here on SO would definitely be us-full to other people (as the frequency this happens is high). Though we should edit it to be more language agnostic (so people can find it easily). – Martin York Jan 28 '13 at 20:23
  • Just as a further data point, you can also get different results for different C implementations. – Daniel Fischer Jan 28 '13 at 22:19

1 Answers1

3

There is more than one way to implement a pseudo-random number generator.

Every programming language is free to specify its own rand implementation, or even to specify nothing. For example, the C specification only says that "The rand function computes a sequence of pseudo-random integers in the range 0 to RAND_MAX." There's no mention of how rand should work, so the compiler writers can implement rand however they like.

Many compilers use a linear congruential generator to implement rand. Even this simple algorithm has parameters that the compiler is free to specify, and which changes the sequence of numbers given by a particular seed.

LCG parameters

Look how Borland and glibc use different parameters. You can't even trust rand to work the same across all C programs, let alone all programs in general!

Kevin
  • 74,910
  • 12
  • 133
  • 166