简体   繁体   English

的std :: uniform_int_distribution <int> g ++和msvc的范围

[英]std::uniform_int_distribution<int> range in g++ and msvc

While doing a minor school project, I just noticed a difference in the range of std::uniform_int_distribution<int> : 在做一个小型学校项目时,我只注意到std::uniform_int_distribution<int>范围的差异:

When using g++ the range is [a, b], however when using msvc (Visual Studio 2010) the range is (a, b], so the output of the following program: 使用g ++时,范围是[a,b],但是使用msvc(Visual Studio 2010)时,范围是(a,b],因此以下程序的输出:

#include <iostream>
#include <random>

using std::cout;
using std::cin;

int main()
{
    std::mt19937 random;
    std::uniform_int_distribution<int> intDist(-1, 1);

    for(int i = 0; i < 100; i++)
    {
        cout << intDist(random) << "\n";
    }

    cin.get();
}

Will display -1 at some point when using g++, but it will never display -1 when using msvc. 使用g ++时将在某些时候显示-1,但是使用msvc时将永远不会显示-1。

I know is common that such differences exists between compilers, but booth the MSDN documentation and the standard mark that the range should be [a, b]. 我知道在编译器之间存在这种差异是很常见的,但是请参见MSDN文档和标准标记,该范围应为[a,b]。

What is the reason for this behavior? 这种行为的原因是什么?

It's a bug in the Visual Studio 2010 implementation of std::uniform_int_distribution . 这是Visual Studio 2010实现std::uniform_int_distribution

I reported it here in December 2011 and got confirmation from Stephan T. Lavavej that: 我在2011年12月在这里举报了此事,并得到了Stephan T. Lavavej的确认:

  1. It is indeed a bug. 确实是一个错误。
  2. It's been fixed in the next version of Visual Studio (including the current Developer Preview ). 下一版本的Visual Studio(包括当前的Developer Preview )已对其进行了修复。

The bug occurs when the first parameter to the std::uniform_int_distribution constructor is negative. std::uniform_int_distribution构造函数的第一个参数为负数时,会发生此错误。 To work around it in your example, construct the distribution like this: 要在您的示例中解决此问题,请按以下方式构建分布:

std::uniform_int_distribution<int> intDist(0, 2);

And then call it like this: 然后像这样调用它:

cout << intDist(random) - 1 << "\n";  

What is the reason for this behavior? 这种行为的原因是什么?

If true, it's a bug in MSVC implementation. 如果为true,则是MSVC实现中的错误。

MSDN says : MSDN说

The first member operator uses the engine eng as a source of uniformly distributed integral values and returns integral values with each value i in the closed range [min(), max()] occurring with equal probability and values outside that range occurring with probability 0. 第一个成员运算符使用引擎eng作为均匀分布的积分值的来源,并返回积分值,其中每个值i在闭合范围[min(),max()]中以相等的概率发生,并且在该范围之外的值以概率0发生。

This means that your observation is wrong, or there is abug in the implementation. 这意味着您的观察是错误的,或者实施中存在缺陷。 This should be easy to see in the source. 这应该很容易在源代码中看到。

I also suggest seeding the rng to a different value. 我还建议将rng播种到不同的值。 There is a very very very low possibility of the behaviour turning out better. 行为变得更好的可能性非常非常低。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM