1

The thing is this code produces same values every time I run it. But the exact same code produces different values on my friend's PC. What might be the reason, or what did I do wrong?

#define SIZE 100

int main(void) {

    srand(14012021);
    for (int i = 0; i < SIZE; ++i) {
        if (i && i % 10 == 0)
            printf("\n");
        printf("%d, ", (rand() % 2 ? 1 : -1) * (rand() % 1000));
    }
}
Jens
  • 69,818
  • 15
  • 125
  • 179
adnanaydin
  • 21
  • 2
  • 1
    Do you want it to be random or not? Possibly different implementation on different platforms, or some well-thought about quirk of the algorithm so it is _random_. – Paul Ogilvie Jan 31 '21 at 14:46
  • The implementation of `rand()` uses different algorithms on the different computers. If you want consistency, include a specific PRNG. I like [pcg](https://www.pcg-random.org/) but there's tons of other good ones. – Shawn Jan 31 '21 at 15:07
  • 3
    @ close-votes: This question may lack research effort (which is a potential downvote reason), and/or may have been answered before, but it is *not* unclear, in the sense that it is very obvious what OP wants to know. The explanation given in the comments above may also be helpful to others. – dialer Jan 31 '21 at 15:21
  • @Shawn Good point! However, I looked through the C11 (Draft) Standard and could find nothing *explicit* in there saying that different implementations can produce different sequences for the **same seed**. An authoritative answer to this question would, IMO, be very useful. – Adrian Mole Jan 31 '21 at 15:47
  • A *possible* duplicate: https://stackoverflow.com/q/23690226/10871073 ?? – Adrian Mole Jan 31 '21 at 15:50
  • 2
    @AdrianMole: C 2018 7.22.2.1 4 says “There are no guarantees as to the quality of the random sequence produced and some implementations are known to produce sequences with distressingly non-random low-order bits.” That sentence makes sense only if different implementations produce difference sequences. – Eric Postpischil Jan 31 '21 at 16:19

1 Answers1

2

Same srand seeds produces different values on different computers

Yes. The particular pseudo random number algorithm is a quality-of-implementation issue. They might be simple, they might be sophisticated. If you need consistent behavior across implementations, you need to bring your own.

Fun fact: the ISO C99 Standard contains the howto for this:

The following functions define a portable implementation of rand and srand

static unsigned long int next = 1;

int rand(void)   // RAND_MAX assumed to be 32767
{
    next = next * 1103515245 + 12345;
    return (unsigned int)(next/65536) % 32768;
}

void srand(unsigned int seed) {
    next = seed;
}
Jens
  • 69,818
  • 15
  • 125
  • 179