在 C++ 中生成随机数的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9471604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:52:35  来源:igfitidea点击:

What is the best way to generate random numbers in C++?

c++randomnumbers

提问by hamed

What is the best way to generate random numbers?

生成随机数的最佳方法是什么?

采纳答案by LihO

If and only if:

当且仅当:

  • you are not looking for "perfect uniformity" or

  • you have no C++11 support and not even TR1 (thus you don't have another choice)

  • 你不是在寻找“完美的均匀性”或

  • 你没有 C++11 支持,甚至没有 TR1(因此你别无选择)

thenyou might consider using the following C-style solution, which (for the sake of the reputation of this community ~ see rand() Considered Harmful) is written in strike-through font:

那么你可以考虑使用以下 C 风格的解决方案,它(为了这个社区的声誉~参见rand() 被认为是有害的)是用删除字体写的:

Here's the simple C-style function that generates random number from the interval from minto max, inclusive. Those numbers seem to be very close to being uniformly distributed.

下面是从间隔从产生随机数的简单的C风格的功能minmax,包容性。这些数字似乎非常接近均匀分布。

int irand(int min, int max) {
    return ((double)rand() / ((double)RAND_MAX + 1.0)) * (max - min + 1) + min;
}
int irand(int min, int max) {
    return ((double)rand() / ((double)RAND_MAX + 1.0)) * (max - min + 1) + min;
}

and don't forget to call srandbefore you use it:

并且srand在使用之前不要忘记调用:

int occurences[8] = {0};

srand(time(0));
for (int i = 0; i < 100000; ++i)
    ++occurences[irand(1,7)];

for (int i = 1; i <= 7; ++i)
    printf("%d ", occurences[i]);
int occurences[8] = {0};

srand(time(0));
for (int i = 0; i < 100000; ++i)
    ++occurences[irand(1,7)];

for (int i = 1; i <= 7; ++i)
    printf("%d ", occurences[i]);

output: 14253 14481 14210 14029 14289 14503 14235

输出: 14253 14481 14210 14029 14289 14503 14235

Also have a look at:
Generate a random number within range?
Generate random numbers uniformly over an entire range
and find some time and watch at least first 11 minutes of aforementioned video

也看看:
在范围内生成一个随机数?
在整个范围内均匀地生成随机数,
并花一些时间观看上述视频的至少前 11 分钟

Otherwise:

除此以外:

use <random>just like it was pointed out by Kerrek SBalready.

<random>就像Kerrek SB已经指出的那样使用。

回答by Kerrek SB

You should use <random>:

你应该使用<random>

#include <random>

typedef std::mt19937 rng_type;
std::uniform_int_distribution<rng_type::result_type> udist(0, 7);

rng_type rng;

int main()
{
  // seed rng first:
  rng_type::result_type const seedval = get_seed(); // get this from somewhere
  rng.seed(seedval);

  rng_type::result_type random_number = udist(rng);

  return random_number;
}

Pre C++11 you could find this either in TR1 (<tr1/random>, std::tr1::mt19937etc.), or in Boost.random, with essentially the same interface (though there are minor differences).

前C ++ 11,你可以在TR1(要么找到这个<tr1/random>std::tr1::mt19937等),或在Boost.random,以基本相同的接口(虽然有细微差别)。

回答by spencercw

Boost.Randomis an excellent library for producing pseudorandom numbers (or truly random, if the platform supports it).

Boost.Random是一个用于生成伪随机数(或真正随机,如果平台支持)的优秀库。

回答by stinky472

If you're talking standard C++ library pre C++11, rand and srand are your random number generators. There are ways to get more accuracy out of these functions than using modulus with integer arithmetic. You could use doubles, for example, if high speed isn't a concern and round the results to int.

如果您说的是 C++11 之前的标准 C++ 库,那么 rand 和 srand 是您的随机数生成器。与使用整数运算的模数相比,有一些方法可以从这些函数中获得更高的准确性。例如,如果不考虑高速并将结果四舍五入为整数,则可以使用双精度数。

As for custom libraries, if you really want good random distribution and speed, google Mersenne Twister. There are also options in boost.

至于自定义库,如果你真的想要好的随机分布和速度,谷歌 Mersenne Twister。boost中也有选项。

With C++11 you have <random>. http://en.cppreference.com/w/cpp/numeric/random

使用 C++11,你有<random>. http://en.cppreference.com/w/cpp/numeric/random

回答by Ilya Polishchuk

My 'random' library provide a high convenient wrapper around C++11 random classes. You can do almost all things with a simple 'get' method.

我的“随机”库为 C++11 随机类提供了一个非常方便的包装器。您可以使用简单的“get”方法完成几乎所有事情。

Examples:

例子:

  1. Random number in a range
  1. 范围内的随机数

auto val = Random::get(-10, 10); // Integer
auto val = Random::get(10.f, -10.f); // Float point

auto val = Random::get(-10, 10); // Integer
auto val = Random::get(10.f, -10.f); // Float point

  1. Random boolean
  1. 随机布尔值

auto val = Random::get<bool>( ) // 0.5% to generate true

auto val = Random::get<bool>( 0.7 ) // 0.7% to generate true

auto val = Random::get<bool>( ) // 0.5% to generate true

auto val = Random::get<bool>( 0.7 ) // 0.7% to generate true

  1. Random value from a std::initilizer_list
  1. 来自 std::initilizer_list 的随机值
auto val = Random::get( { 1, 3, 5, 7, 9 } ); // val = 1 or 3 or...
auto val = Random::get( { 1, 3, 5, 7, 9 } ); // val = 1 or 3 or...
  1. Random iterator from iterator range or all container
  1. 来自迭代器范围或所有容器的随机迭代器

auto it = Random::get( vec.begin(), vec.end() ); // it = random iterator

auto it = Random::get( vec ); // return random iterator

auto it = Random::get( vec.begin(), vec.end() ); // it = random iterator

auto it = Random::get( vec ); // return random iterator

And even more things ! Check out the github page:

甚至更多的东西!查看github页面:

https://github.com/effolkronium/random

https://github.com/effolkronium/random