简体   繁体   English

Float OR Int范围内的随机数

[英]Random number within range for Float OR Int

I'm making a templates function object that will generate a ranged random number. 我正在制作一个模板函数对象,它将生成一个有范围的随机数。 I know how to do that for either ints or floats. 我知道如何为整型或浮点型。 But my problem is that I want it to be able to generate a ranged random number of the type T. 但是我的问题是我希望它能够生成类型T的有范围随机数。

So, since I want it to be able to return both floats and integers I can't use the % operator. 因此,由于我希望它能够返回浮点数和整数,所以我不能使用%运算符。 This seem to work for float values. 这似乎适用于浮点值。 But if T is INT it will mess up the range. 但是,如果T为INT,它将使范围变大。

return (_minValue + (T)rand() / ((T)RAND_MAX / (_maxValue - _minValue)));

There must be some mistake in that algorithm that I just can't seem to find at this hour. 在该算法上肯定有一些错误,我似乎在这个时候找不到。

If the type T is an integer type, (T)rand() / (T)RAND_MAX will clearly be zero except for the rare case when rand() returns RAND_MAX (and T happens to be at least as int ) in which case it will be one. 如果类型T是整数类型,则(T)rand() / (T)RAND_MAX显然将为零,除非rand()返回RAND_MAX的极少数情况(并且T至少等于int ),在这种情况下将是一个。 Note that rand() is generally not a very good random number generator although the quality differs quite a bit between different implementations. 注意,尽管不同实现之间的质量差异很大,但rand()通常不是一个很好的随机数生成器。 You are probably best of to just use something from the <random> library (for my normal work I have very rarely a need for random numbers, ie, I don't know how to use the components in this library immediately). 您可能最好只使用<random>库中的内容(对于我的正常工作,我很少需要随机数,即,我不知道如何立即使用该库中的组件)。

If you insist in using rand() your best option is probably to determine random values different for integers and floating points, eg: 如果您坚持使用rand()最好的选择可能是确定整数和浮点数不同的随机值,例如:

template <typename T, bool = std::is_floating_point<T>::value>
struct random;
template <typename T>
struct random<T, true> {
    static T generate() { return /* floating point formula goes here */; }
};
template <typename T>
struct random<T, false> {
    static T generate() { return /* integer formula goes here */; }
};

template <typename T>
T random_range() { return random<T>::generate(); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM