gpt4 book ai didi

c++ - 为什么 std::uniform_real_distribution::max() 返回独占上限?

转载 作者:可可西里 更新时间:2023-11-01 16:23:47 26 4
gpt4 key购买 nike

我问的主要是出于学术兴趣。

documentation表示 std::uniform_real_distribution 生成 [a,b) 范围内的数字,其中 ab 是构造函数参数。

由于上限是独占的,我希望 .max() 返回小于 .b()最大可表示值。

但是我在 GCC、Clang 和 MSVC 上都得到了 .b() == .max()。 (对于 floatdoublelong double。)为什么?

#include <iostream>
#include <iomanip>
#include <random>

int main()
{
auto d = std::uniform_real_distribution<long double>(0, 1);
std::cout << std::setprecision(1000);
std::cout << d.min() << '\n'; // 0
std::cout << d.a() << '\n'; // 0
std::cout << d.max() << '\n'; // 1 <- Here I expect 0.99999...
std::cout << d.b() << '\n'; // 1
}

我找到了 this note说一些常见的实现仅将 [a,b] 范围用于 float。它可以为 float 解释 .b() == .max(),但不能为 doublelong double.


I think it might be educational to also print std::nextafter(d.b(), d.a()). – StoryTeller

对于 long double,它的计算结果为 0.9999999999999999999457898913757247782996273599565029144287109375,这是我期望从 .max() 得到的结果。

最佳答案

我不认为这个错误是关于 float 的,而是一般的 float 。

错误已经在 VS-Dev-Community关于 doubles 解决此问题的地方。但是,他们声称已在 2021 年 1 月 26 日之前修复它。

旁注:此外,我无法重现您为 long double 获得的 max() 值。与所有其他情况一样,我得到 1。如前所述,它只是随机噪声,因为 setprecision(n) 似乎会为 n > numeric_limits::max_digits10 产生噪声。

关于c++ - 为什么 std::uniform_real_distribution::max() 返回独占上限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52354921/

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