gpt4 book ai didi

c++ - std::uniform_real_distribution 包含范围

转载 作者:可可西里 更新时间:2023-11-01 16:28:12 25 4
gpt4 key购买 nike

C++11 std::uniform_real_distribution( -1, 1 ) 给出 [-1,1] 范围内的数字。

如何获得 [-1,1] 范围内的均匀实数分布?

实际上这可能无关紧要,但从逻辑上讲,我正在尝试选择包含范围内的值。

最佳答案

如果您从查看整数开始,就更容易思考这一点。如果你传递 [-1, 1) 你会期望得到 -1, 0。由于您想要包含 1,因此您将传递 [-1, (1+1)), 或 [-1, 2)。现在你得到 -1, 0, 1

你想做同样的事情,但是用 double :

借自this answer :

#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;
}

(查看代码运行here)

也就是说,在你想要的值之后找到下一个最大的 double 值,并将其作为结束值传递。

关于c++ - std::uniform_real_distribution 包含范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16224446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com