Why does the C++ stdlib rand() function give diffe

2020-04-02 01:24发布

I understand that the rand() function generates pseudo-random numbers based on the seed it is given, and that on a given platform it will always generate the same sequence of numbers from the same seed, what I want to know is why it gives a different sequence across platforms that use the same library? I.e. how is rand() implemented?

标签: c++ c random std
2条回答
够拽才男人
2楼-- · 2020-04-02 02:01

The rand() function shall compute a sequence of pseudo-random integers in the range [0, {RAND_MAX}] with a period of at least 2^32.

The rand_r() function shall compute a sequence of pseudo-random integers in the range [0, {RAND_MAX}]. (The value of the {RAND_MAX} macro shall be at least 32767.)

If rand_r() is called with the same initial value for the object pointed to by seed and that object is not modified between successive returns and calls to rand_r(), the same sequence shall be generated.

The srand() function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand(). If srand() is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. If rand() is called before any calls to srand() are made, the same sequence shall be generated as when srand() is first called with a seed value of 1.

The rand() function shall return the next pseudo-random number in the sequence.

This is what that IEEE Std 1003.1 C-standard says about how the rand() function should behave. It doesn't say anything about how the sequence should be calculated. In other words, each implementer is free to choose their own version of a pseudo random sequence generator.

Your observations shows that they have taken advantage of that freedom.

I might also point out that rand() is a part of the <cstdlib> which is more or less a copy of the C standard library , and the new library will provide you with more flexibility and standard sequence generators if you have a new enough C++ compiler and doesn't depend on C - C++ interoperability.

查看更多
Fickle 薄情
3楼-- · 2020-04-02 02:10

The C++ standard does not specify what algorithm is used for the rand() function.

The functionality is defined by whoever wrote the standard library on your system: Microsoft for the standard library included with Visual Studio, and the GNU guys for the standard library packaged with GCC.

Your compiler is making the choice of where it gets its library from, so you may have different versions of the standard library for different compilers on the same system. The point remains the same: the specification guarantees what functions are available and what they do; not how they do it.

查看更多
登录 后发表回答