Namespaces
Variants
Views
Actions

Talk:c/numeric/random/rand

From cppreference.com

[edit] Possibly incorrect information, and other stuff

I am going to do a fairly comprehensive edit of the documentation for this function and its relatives, to correct some false, and some misleading information:

  • As far as I know, there is no guarantee that rand() will produce uniformly-distributed numbers. (C11 draft 7.22.2 says nothing about the distribution.)
  • srand() does not "initialize" the PRNG. It seeds the PRNG. There is a big difference. (For example, in the sample code given in the C11 draft, the PRNG is initialized automatically by the static instantiation of next.)
  • It is not true that srand() should be called before any calls to rand(). That's good practice in most situations, but hardly required.
  • There is no mention that if you don't call srand() before using rand(), it behaves as if you seeded with 1.
  • There seems to be no mention of the requirement that rand() always produce the same sequence of numbers for a given seed (which is pretty important).
  • I also think it's important to mention that rand()/srand() provides no guarantees of thread safety, because a) that's explicitly stated in the standard, and b) there's misleading information floating around about rand() using TLS (which may be true on some implementations, but is not required).
  • And because this is such a FAQ about rand()/srand(), I think there should be a mention of the fact that you shouldn't call srand() repeatedly.

To cover all this, the pages I'm going to touch are:

And for all those pages, on the talk pages, I'm going to refer back here, so everyone can easily find out what I'm changing and why from each page. -- Indi 11:02, 11 November 2012 (PST)

Looks good. The use of thread-local storage is specifically the Microsoft implementation [1], it could be helpful to mention as a note. --Cubbi 11:27, 11 November 2012 (PST)
Sure. Another thing I might do is change the examples in rand()/std::rand() to generate a random number between A and B, which is probably the most common use case by far, and almost always done wrong (because of modulo bias). -- Indi 11:41, 11 November 2012 (PST)
That's great. P12 11:52, 11 November 2012 (PST)

[edit] Types of srand()

The use of this reference results in warning messages:

my_rand.c:8:12: warning: conversion to ‘int’ from ‘time_t {aka long int}’ may alter its value [-Wconversion]

  int ti = time (NULL);

and

my_rand.c:9:19: warning: conversion to ‘unsigned int’ from ‘long int’ may alter its value [-Wconversion]

  srand (ti);

Why does the seed function ask for unsigned as the normal implementation takes the value from time() which is of type time_t ? And why is this not even mentioned in the reference? --Moritz12d (talk) 09:04, 13 January 2021 (PST)

the types are documented but feel free to add explicit casts to the examples that trip -Wconversion, though. --Cubbi (talk) 15:20, 14 January 2021 (PST)