Uniform_real不接受numeric_limits :: lowest() [英] Uniform_real does not accept numeric_limits::lowest()

查看:52
本文介绍了Uniform_real不接受numeric_limits :: lowest()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一行:

std::uniform_real_distribution<T> distribution(std::numeric_limits<T>::lowest(), 
                                               std::numeric_limits<T>::max());

它可以编译,但在Debug(VS 2017CE)上崩溃.我的猜测是,根据std::uniform_real_distribution的文档:

It compiles but crashes on Debug(VS 2017CE). My guess is that, according to documentation of std::uniform_real_distribution:

要求a ≤ bb-a ≤ std::numeric_limits<RealType>::max()

当我的b::max()a::lowest()时,条件:

when my b is ::max() and a is ::lowest(), condition:

b-a ≤ std::numeric_limits<RealType>::max()

未实现,因为b-a基本上将max的值加倍.有什么办法可以解决这个问题,以便我能保持如此广泛的范围吗? ::min()可以完美工作,但是忽略了负值.仅浮点数会出现问题.

is not fulfilled as b-a basically doubles the value of max. Is there any work around for this so that I will keep such a wide numbers range? ::min() works perfectly but omits negative values. Problem occurs for floating numbers only.

推荐答案

一种方法是使用范围[-1, 1],然后将其乘以std::numeric_limits<T>::max()以获得实际数字.这样可以满足b-a ≤ std::numeric_limits<RealType>::max()要求.

One way to do this is to use the range [-1, 1] and then multiply that by std::numeric_limits<T>::max() to get the actual number. This lets you satisfy the b-a ≤ std::numeric_limits<RealType>::max() requirement.

auto dis = std::uniform_real_distribution<T> dis(-1, std::nextafter(1, std::numeric_limits<T>::max()));
return dis(eng) * std::numeric_limits<T>::max();

这不会为您提供所有可能的浮点值,但可以像uniform_int_distribution那样为您提供大量的浮点值.

This won't give you all possible floating point values but it will give you a good number of them distributed like a uniform_int_distribution would.

这篇关于Uniform_real不接受numeric_limits :: lowest()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆