std::uniform_int_distribution produces incorrect results when min0 is negative - by Spire

Status : 

  Fixed<br /><br />
		This item has been fixed in the current or upcoming version of this product.<br /><br />
		A more detailed explanation for the resolution of this particular item may have been provided in the comments section.


3
0
Sign in
to vote
ID 712984 Comments
Status Closed Workarounds
Type Bug Repros 1
Opened 12/10/2011 1:01:15 PM
Access Restriction Public
Moderator Decision Sent to Engineering Team for consideration

Description

The std::uniform_int_distribution class template produces incorrect results when the min0 parameter passed to its constructor is negative.

Consider the following code snippet, which is supposed to generate a million random integers in the range -2 through 2:

	std::uniform_int_distribution<int> dist(-2, 2);
	std::default_random_engine rng;

	int n[5] = { 0 };

	for (int i = 1000000; i > 0; --i)
	{
		++n[dist(rng) + 2];
	}

	std::cout << n[0] << ", " << n[1] << ", " << n[2] << ", " << n[3] << ", " << n[4] << std::endl;

The expected output of this code would be something like:

	199098, 200508, 200762, 199867, 199765

Note the roughly uniform distribution among the valid output values.

Under Visual Studio 2010 SP1, we get this instead:

	0, 199098, 401270, 199867, 199765

This appears to be caused by a rounding error in line 2788 of random.h, which does a simple cast of the internal floating-point result to the specified result type. Consequently, all of the -1 values are returned as 0, and all of the -2 values are returned as -1. Observe that 0 is returned twice as many times as expected, and -2 is not returned at all.

In the above example, the problem can be worked around by specifying 0 and 4 as min0 and max0, respectively, and then subtracting 2 from the return value. This is ugly, however, and shouldn't be necessary.
Sign in to post a comment.
Posted by Stephan [MSFT] on 12/12/2011 at 9:59 AM
Hi,

Thanks for reporting this bug. We've already fixed it, and the fix is available in the VC11 Developer Preview.

(I rewrote uniform_int_distribution to use bitwise operations instead of floating-point arithmetic; it now produces perfectly uniform results for arbitrary input ranges and arbitrary output ranges.)

If you have any further questions, feel free to E-mail me at stl@microsoft.com .

Stephan T. Lavavej
Visual C++ Libraries Developer
Posted by MS-Moderator10 [Feedback Moderator] on 12/11/2011 at 10:18 PM
Thank you for submitting feedback on Visual Studio 2010 and .NET Framework. Your issue has been routed to the appropriate VS development team for investigation. We will contact you if we require any additional information.
Posted by MS-Moderator01 on 12/10/2011 at 1:42 PM
Thank you for your feedback, we are currently reviewing the issue you have submitted. If this issue is urgent, please contact support directly(http://support.microsoft.com)