产生范围内的随机数? [英] Generate a random number within range?

查看:131
本文介绍了产生范围内的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  生成随机数的Objective-C

我如何产生一个随机数这是一个范围之内?

How do I generate a random number which is within a range?

推荐答案

这其实是一个有点难以得到真正正确的比大多数人意识到:

This is actually a bit harder to get really correct than most people realize:

int rand_lim(int limit) {
/* return a random number between 0 and limit inclusive.
 */

    int divisor = RAND_MAX/(limit+1);
    int retval;

    do { 
        retval = rand() / divisor;
    } while (retval > limit);

    return retval;
}

这只是使用(或等价地, / ),以获得号码的范围几乎不可避免地尝试引入歪斜(即,将产生频率高于其他一些数字)。

Attempts that just use % (or, equivalently, /) to get the numbers in a range almost inevitably introduce skew (i.e., some numbers will be generated more often than others).

编辑:为何使用产生类似的结果:除非你想的范围是RAND_MAX的除数,倾斜是必然的。如果你开始小数字,这是pretty很容易明白为什么。考虑采取10块糖,并试图三个孩子之间平均分摊。显然,不能做 - 如果你交出了所有的糖果,你可以得到最接近的是两个孩子拿到三块糖,以及他们获得四位一体

as to why using % produces skewed results: unless the range you want is a divisor of RAND_MAX, skew is inevitable. If you start with small numbers, it's pretty easy to see why. Consider taking 10 pieces of candy and trying to divide it evenly between three children. Clearly it can't be done -- if you hand out all the candy, the closest you can get is for two kids to get three pieces of candy, and one of them getting four.

有对所有的孩子获得相同数量的糖果件只有一个办法:确保你不要用手出最后一块糖在所有

There's only one way for all the kids to get the same number of pieces of candy: make sure you don't hand out the last piece of candy at all.

要高于此相关的code,让我们通过编号从1到10的糖果和孩子们从1到3,初始师说,因为有三个孩子开始,我们的除数是三。然后,我们从桶拉一个随机的糖果,看它的数量除以三年交给那个孩子 - 但如果结果大于3(也就是,我们挑选出糖果10号),我们只是不递出在所有 - 我们抛弃它,并挑选出另一糖果

To relate this to the code above, let's start by numbering the candies from 1 to 10 and the kids from 1 to 3. The initial division says since there are three kids, our divisor is three. We then pull a random candy from the bucket, look at its number and divide by three and hand it to that kid -- but if the result is greater than 3 (i.e. we've picked out candy number 10) we just don't hand it out at all -- we discard it and pick out another candy.

编辑:虽然它在当时是不是广泛使用,如果您使用的是现代化实现的C ++(即一个支持C ++ 11),你应该使用一个标准库分布类。在code以上的std :: uniform_int_distribution ,但标准库还包括 uniform_real_distribution 最紧密对应,以及作为类的一些非均匀分布(伯努利,泊松,正常,也许一对夫妇别人我不记得的时刻)。

Though it wasn't as widely available at the time, if you're using a modern implementation of C++ (i.e., one that supports C++11), you should probably use one the distribution classes from the standard library. The code above corresponds most closely with std::uniform_int_distribution, but the standard library also includes uniform_real_distribution as well as classes for a number of non-uniform distributions (Bernoulli, Poisson, normal, maybe a couple others I don't remember at the moment).

这篇关于产生范围内的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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