3

I'm trying to port some code over from UNIX to Windows, and I need an implementation of POSIX srandom(x) and random() functions that, for a given seed x, generate the same number sequence as the one that conforms to POSIX.1-2001. What are some of the available options on Windows?

JosephH
  • 8,465
  • 4
  • 34
  • 62

3 Answers3

5

srandom and family are members of glibc. You can probably copy the source code from glibc for srandom/random into your application, as long as it's license compatible. If you're looking for another implementation, any small amou

Bear in mind, POSIX is actually interface conformance, and not implementation conformance - it doesn't actually state what the mechanism is for generating it, nor what the resulting numbers should be.

if you're looking to guarantee the same number sequence across multiple platforms, then you should not rely on the standard library implementation of any of the random number generators, you should be making your own, or recycling a known implementation.

As mentioned in a comment by JWWalker, there's a pretty good boost random implementation, which provides a nice set of C++ classes for random numbers, but that's C++, not C - different language, so probably not directly suitable.

Anya Shenanigans
  • 91,618
  • 3
  • 107
  • 122
  • For open source random number generators, see the [Random library of Boost](http://www.boost.org/doc/libs/1_61_0/doc/html/boost_random/reference.html). – JWWalker Jun 08 '16 at 19:19
  • Links are dead. I got a file I need to compile, what should I do to replace srandom? – Tomáš Zato Jan 10 '17 at 02:27
  • @TomášZato I've updated the link to point to sourceware link for glibc random.c, which should remain alive for the forseeable future. It is glibc code and has a license associated with it which could make it unsuitable for use. – Anya Shenanigans Jan 10 '17 at 08:45
1

You can check rand_s and srand functions in Windows. But, I am not sure if they conform to POSIX standards.

EDIT

A better one seems to be CryptGenRandom. Check this link for details.

Jay
  • 24,173
  • 25
  • 93
  • 141
  • 1
    `rand_s` does not use the seed set by `srand`, and `rand` returns a 15-bit random number, unlike the 31-bit random number returned by `random`. – JWWalker Jun 08 '16 at 18:57
1

If you are looking for some simple pseudorandom generator you can use Linear congruence generator http://en.wikipedia.org/wiki/Linear_congruential_generator

eg. the first example:

unsigned int seed = 2;

unsigned int rand()
{
   seed = 1664525 * seed + 1013904223;
   return seed;
}

void srand(unsigned int new_seed)
{
   seed = new_seed;
}
V-X
  • 2,979
  • 18
  • 28