What is the most random function in C++? [closed]

2019-02-23 03:45发布

I've used

#include<stdlib>
#include<time>
using namespace std;
srand((unsigned)time(0));
int n=(rand()>>8)%4;

but what other random functions are there, or what other function could be used as random number generators?

EDIT: I don't really have a particular reason for asking this question, I just wanted to know if C++ had any other random functions.

标签: c++ random
9条回答
地球回转人心会变
2楼-- · 2019-02-23 04:28

Bruce Schneier and John Kelsey wrote a random number generator you may be interested in. Rather, it's a seed generator. Even though Yarrow is no longer supported, you may be interested in how it gathers entropy.

OpenSSL has an API that is relatively easy to access and pretty portable. And Mozilla comes with a decent API that wraps whatever the OS offers.

Personally, though, I generally use Boost.Random, which was already suggested.

查看更多
Juvenile、少年°
3楼-- · 2019-02-23 04:33

The rand() and srand() functions are all the C++ Standard specifies. And if it comes to writing your own, be aware of what John von Neumann said:

"Anyone who considers arithmetical methods of producing random digits is of course in a state of sin"

查看更多
Lonely孤独者°
4楼-- · 2019-02-23 04:34

(Cross-posting from an answer I just wrote to a similar question)

Have a look at ISAAC (Indirection, Shift, Accumulate, Add, and Count). Its uniformly distributed and has an average cycle length of 2^8295.

It's fast too, since it doesnt involve multiplication or modulus.

查看更多
Animai°情兽
5楼-- · 2019-02-23 04:35

Not strictly C++, but Windows specific:

CryptGenRandom

I'm sure all operating systems have their equivalent cryptographically secure random generator functions.

查看更多
Anthone
6楼-- · 2019-02-23 04:38

This code is pretty efficient. Although users may begin to notice a pattern after a few iterations.

int FastRandom()
{
  return 10;
}
查看更多
相关推荐>>
7楼-- · 2019-02-23 04:44

Random gives you a good random number at uniform distribution and does a pretty good job at that.

Anything else would mean that you want to actually skew the distribution.

For example, using Microsoft's GUIDs generator would give you a random id that is less likely to be repeated and takes into account things like time and computer.

查看更多
登录 后发表回答