如何在给定间隔中以相等的概率生成随机数 [英] How to generate a random number with equal probability in a given interval

查看:109
本文介绍了如何在给定间隔中以相等的概率生成随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了很多尝试,但未能解决此问题

I tried a lot but could not get a solution for this problem


函数返回范围为的数字[ 1,6] 的概率相等。您可以使用库的 rand()函数,并假设实现 rand()返回范围内的数字 [0,RAND_MAX] 的概率均等。

Function returns numbers in range [1,6] with equal probability. You can use library's rand() function and you can assume implementation of rand() returns number in range number in range [0,RAND_MAX] with equal probability.


推荐答案

我们将分多个步骤进行。

We'll do this in multiple steps.

您需要生成一个范围为 [1、6] (含)。

You need to generate a number in the range [1, 6], inclusive.

您有一个随机数生成器,该生成器将生成范围 [0..RAND_MAX]

You have a random number generator that will generate numbers in the range [0..RAND_MAX].

假设您要生成 [0..5] 。您可以这样做:

Let's say you wanted to generate numbers in the range [0..5]. You can do this:

int r = rand();  // gives you a number from 0 to RAND_MAX
double d = r / RAND_MAX;  // gives you a number from 0 to 1
double val = d * 5; // gives you a number from 0 to 5
int result = round(d);  // rounds to an integer

您可以使用该技术对给定范围 [0,高] ,您可以生成一个随机数,除以 RAND_MAX ,再乘以 high ,然后对结果取整。

You can use that technique to So given a range of [0, high], you can generate a random number, divide by RAND_MAX, multiply by high, and round the result.

您的范围是 [1,6] ,因此您必须添加另一步骤。您要生成一个在 [0,5] 范围内的随机数,然后加1。或者,通常,要在给定范围内生成一个随机数, [低,高] ,您输入:

Your range is [1, 6], so you have to add another step. You want to generate a random number in the range [0, 5], and then add 1. Or, in general, to generate a random number in a given range, [low, high], you write:

int r = rand();
double d = r / RAND_MAX;
int range = high - low + 1;
double val = d * range;
result = round(val);

很明显,您可以合并其中的一些操作。我只是单独显示它们以进行说明。

Obviously you can combine some of those operations. I just showed them individually to illustrate.

这篇关于如何在给定间隔中以相等的概率生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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