展开随机范围从1-5到1-7 [英] Expand a random range from 1–5 to 1–7

查看:219
本文介绍了展开随机范围从1-5到1-7的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个产生一个随机整数范围为1至5个功能,写一个产生范围为1的随机整数7的功能。

  1. 什么是简单的解决方案
  2. 什么是有效的解决方案,以减少内存使用或运行在较慢的CPU?
解决方案

  rand7()=(rand5()+ rand5()+ rand5()+ rand5()+ rand5() + rand5()+ rand5())%7 + 1
 

编辑:这完全不是那么回事。它在1000约2份(假设一个完美的rand5)的关闭。该桶得到:

 值计数误差%
1 11158 -0.0035
2 11144 -0.0214
3 11144 -0.0214
4 11158 -0.0035
5 11172 0.0144
6 11177 0.0208
7 11172 0.0144
 

通过切换到一笔

  n错误%
10 +/- 1E-3,
为12 +/- 1E-4,
14 +/- 1E-5,
16±1E-6,
...
28 +/- 3E-11
 

似乎增益幅度为每2添加了一个订单

顺便说一句:上述未通过采样产生,但是由下面的递推关系错误的表

  

P [X,N] 是数字方式输出= X 可能发生给 N 调用 rand5

  P [1,1] ... P [5,1] = 1
  ρ[6,1] ... P [7,1] = 0

  P [1,n]的= P [7中,n-1] + P [6中,n-1] + P [5中,n-1] + P [4中,n-1] + P [3,n-1个]
  P [2中,n] = P [1中,n-1] + P [7中,n-1] + P [6中,n-1] + P [5中,n-1] + P [4,n-1个]
  P [3中,n] = P [2中,n-1] + P [1中,n-1] + P [7中,n-1] + P [6中,n-1] + P [5中,n-1 ]
  P [4中,n] = P [3中,n-1] + P [2中,n-1] + P [1中,n-1] + P [7中,n-1] + P [6,n-1个]
  P [5中,n] = P [4中,n-1] + P [3中,n-1] + P [2中,n-1] + P [1中,n-1] + P [7,n-1个]
  P [6中,n] = P [5中,n-1] + P [4中,n-1] + P [3中,n-1] + P [2中,n-1] + P [1,n-1个]
  P [7中,n] = P [6中,n-1] + P [5中,n-1] + P [4中,n-1] + P [3中,n-1] + P [2,n-1个]
 

Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.

  1. What is a simple solution?
  2. What is an effective solution to reduce memory usage or run on a slower CPU?

解决方案

rand7() = (rand5()+rand5()+rand5()+rand5()+rand5()+rand5()+rand5())%7+1

Edit: That doesn't quite work. It's off by about 2 parts in 1000 (assuming a perfect rand5). The buckets get:

value   Count  Error%
1       11158  -0.0035
2       11144  -0.0214
3       11144  -0.0214
4       11158  -0.0035
5       11172  +0.0144
6       11177  +0.0208
7       11172  +0.0144

By switching to a sum of

n   Error%
10  +/- 1e-3,
12  +/- 1e-4,
14  +/- 1e-5,
16  +/- 1e-6,
...
28  +/- 3e-11

seems to gain an order of magnitude for every 2 added

BTW: the table of errors above was not generated via sampling but by the following recurrence relation:

p[x,n] is the number ways output=x can happen given n calls to rand5.

  p[1,1] ... p[5,1] = 1
  p[6,1] ... p[7,1] = 0

  p[1,n] = p[7,n-1] + p[6,n-1] + p[5,n-1] + p[4,n-1] + p[3,n-1]
  p[2,n] = p[1,n-1] + p[7,n-1] + p[6,n-1] + p[5,n-1] + p[4,n-1]
  p[3,n] = p[2,n-1] + p[1,n-1] + p[7,n-1] + p[6,n-1] + p[5,n-1]
  p[4,n] = p[3,n-1] + p[2,n-1] + p[1,n-1] + p[7,n-1] + p[6,n-1]
  p[5,n] = p[4,n-1] + p[3,n-1] + p[2,n-1] + p[1,n-1] + p[7,n-1]
  p[6,n] = p[5,n-1] + p[4,n-1] + p[3,n-1] + p[2,n-1] + p[1,n-1]
  p[7,n] = p[6,n-1] + p[5,n-1] + p[4,n-1] + p[3,n-1] + p[2,n-1]

这篇关于展开随机范围从1-5到1-7的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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