将[0,1]间隔扩展为[a,b]的正确方法是什么?

编程入门 行业动态 更新时间:2024-10-24 12:33:02
本文介绍了将[0,1]间隔扩展为[a,b]的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

许多随机数生成器返回0到1之间的浮点数.

Many random-number generators return floating numbers between 0 and 1.

在 a 和 b 之间获得 integers 的最佳和正确方法是什么?

What's the best and correct way to get integers between a and b?

推荐答案

将间隔[0,1]划分为B-A + 1个单元格

Divide the interval [0,1] in B-A+1 bins

示例A = 2,B = 5

Example A=2, B=5

[----+----+----+----] 0 1/4 1/2 3/4 1 Maps to 2 3 4 5

公式问题

Int (Rnd() * (B-A+1)) + A

您的Rnd()生成间隔在两侧都是闭合的,因此0和1都是可能的输出,并且当Rnd()恰好为1时,公式给出6.

is that your Rnd() generation interval is closed on both sides, thus the 0 and the 1 are both possible outputs and the formula gives 6 when the Rnd() is exactly 1.

在实际的随机分布(不是伪)中,1的概率为零.我认为对类似这样的程序进行编程是足够安全的:

In a real random distribution (not pseudo), the 1 has probability zero. I think it is safe enough to program something like:

r=Rnd() if r equal 1 MyInt = B else MyInt = Int(r * (B-A+1)) + A endif

修改

在 Mathematica 中进行快速测试:

定义我们的功能:

f[a_, b_] := If[(r = RandomReal[]) == 1, b, IntegerPart[r (b - a + 1)] + a]

用[1,100]中的3个10 ^ 5数字构建表格:

Build a table with 3 10^5 numbers in [1,100]:

table = SortBy[Tally[Table[f[1, 100], {300000}]], First]

检查最小和最大:

In[137]:= {Max[First /@ table], Min[First /@ table]} Out[137]= {100, 1}

让我们看看分布:

BarChart[Last /@ SortBy[Tally[Table[f[1, 100], {300000}]], First], ChartStyle -> "DarkRainbow"]

更多推荐

将[0,1]间隔扩展为[a,b]的正确方法是什么?

本文发布于:2023-11-30 00:39:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648147.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:间隔   正确   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!