std :: uniform_real_distribution包含范围 [英] std::uniform_real_distribution inclusive range
问题描述
C ++ 11 std :: uniform_real_distribution(-1,1)提供范围[-1,1)中的数字。
C++11 std::uniform_real_distribution( -1, 1 ) gives numbers in the range [-1,1).
真实分布范围[-1,1]?
How would you get a uniform real distribution in the range [-1,1]?
实际上它可能没有关系,但在逻辑上,我试图选择一个包含范围内的值。 / p>
Practically it probably doesn't matter but logically I'm trying to select a value in the inclusive range.
推荐答案
如果你从整数开始,这更容易想。如果你传递[-1,1),你会得到 -1,0
。由于您想要包含 1
,您将传递[-1,(1 + 1))或[-1,2]。现在你得到 -1,0,1
。
This is easier to think about if you start by looking at integers. If you pass [-1, 1) you would expect to get -1, 0
. Since you want to include 1
, you would pass [-1, (1+1)), or [-1, 2). Now you get -1, 0, 1
.
你想做同样的事情,
借用此答案:
#include <cfloat> // DBL_MAX
#include <cmath> // std::nextafter
#include <random>
#include <iostream>
int main()
{
const double start = -1.0;
const double stop = 1.0;
std::random_device rd;
std::mt19937 gen(rd());
// Note: uniform_real_distribution does [start, stop),
// but we want to do [start, stop].
// Pass the next largest value instead.
std::uniform_real_distribution<> dis(start, std::nextafter(stop, DBL_MAX));
for (auto i = 0; i < 100; ++i)
{
std::cout << dis(gen) << "\n";
}
std::cout << std::endl;
}
(请参阅代码运行这里)
也就是说,找到下一个最大的double值,然后将其作为结束值。
That is, find the next largest double value after the one you want, and pass that as the end value instead.
这篇关于std :: uniform_real_distribution包含范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!