Windows-equivalent of POSIX srandom(…) and random() functions?

元气小坏坏 提交于 2019-12-12 14:21:17

问题


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?


回答1:


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.




回答2:


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.




回答3:


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;
}


来源:https://stackoverflow.com/questions/15173238/windows-equivalent-of-posix-srandom-and-random-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!