Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Ruby中生成a和b之间的随机数?_Ruby_Random_Range - Fatal编程技术网

如何在Ruby中生成a和b之间的随机数?

如何在Ruby中生成a和b之间的随机数?,ruby,random,range,Ruby,Random,Range,例如,为了生成3到10之间的随机数,我使用:rand(8)+3 有没有更好的方法(比如rand(3,10))呢?参见答案:Ruby 1.9.2中有,但在早期版本中没有。我个人认为rand(8)+3很好,但是如果您有兴趣,请查看链接中描述的Random类。更新:Ruby 1.9.3内核#rand也接受范围 rand(a..b) 转换为数组可能太贵,而且没有必要 或 Ruby 1.8.7+标准版。 注:在1.8.7中命名为#choice,并在更高版本中重命名 但无论如何,生成阵列需要资源,

例如,为了生成3到10之间的随机数,我使用:
rand(8)+3


有没有更好的方法(比如
rand(3,10)
)呢?

参见答案:Ruby 1.9.2中有,但在早期版本中没有。我个人认为rand(8)+3很好,但是如果您有兴趣,请查看链接中描述的Random类。

更新:Ruby 1.9.3
内核#rand
也接受范围

rand(a..b)

转换为数组可能太贵,而且没有必要



Ruby 1.8.7+标准版。
注:在1.8.7中命名为#choice,并在更高版本中重命名

但无论如何,生成阵列需要资源,您已经编写的解决方案是最好的,您可以做到。

对于10和10**24

rand(10**24-10)+10
其中,
a
是您的最低值,
b
是您的最高值

def random_int(min, max)
    rand(max - min) + min
end

当max是一个范围时,rand返回一个随机数,其中Range.member?(number)=true


只需注意范围运算符之间的差异:

3..10  # includes 10
3...10 # doesn't include 10

这里是一个针对
#sample
#rand
的快速基准:

irb(main):014:0* Benchmark.bm do |x|
irb(main):015:1*   x.report('sample') { 1_000_000.times { (1..100).to_a.sample } }
irb(main):016:1>   x.report('rand') { 1_000_000.times { rand(1..100) } }
irb(main):017:1> end
       user     system      total        real
sample  3.870000   0.020000   3.890000 (  3.888147)
rand  0.150000   0.000000   0.150000 (  0.153557)

因此,做
rand(a..b)
是正确的

def my_rand(x,y);兰德(y-x)+x;结束
@Theo,
y-x+1
,顺便说一句。在10和10**24上尝试你的正确答案,因为限制:0将等待很长时间:)这有效:
rand(3..10)
谢谢!我想我会继续使用旧的好方法:)这是一个非常糟糕的主意,尤其是如果你的a和b的尺寸未知。试试(1000000000000000..1000000000000)。要想了解我的意思:)@pixelearth,如果你有更好的想法,这符合问题,欢迎你发布。
rand(a..b)
不起作用,它分裂:
TypeError:无法将范围转换为整数
。它在@fguillen中甚至不受支持,在1.9.3中它对我有效,我不知道为什么它对你无效。需要注意的重要区别是,如果你只调用
rand()
,你调用的是
Kernel#rand
,它只支持
max
参数。如果要通过一个范围,必须使用
Random#rand
,这意味着必须以这种方式实现+1应补充上述内容适用于1.9.2是否包括a和b?还是仅
rand(10..10**24)
def random_int(min, max)
    rand(max - min) + min
end
rand(3..10)
3..10  # includes 10
3...10 # doesn't include 10
irb(main):014:0* Benchmark.bm do |x|
irb(main):015:1*   x.report('sample') { 1_000_000.times { (1..100).to_a.sample } }
irb(main):016:1>   x.report('rand') { 1_000_000.times { rand(1..100) } }
irb(main):017:1> end
       user     system      total        real
sample  3.870000   0.020000   3.890000 (  3.888147)
rand  0.150000   0.000000   0.150000 (  0.153557)