【问题标题】:Does Ruby Have a Random Number Generator Class? [duplicate]Ruby 有随机数生成器类吗? [复制]
【发布时间】:2011-04-12 15:07:12
【问题描述】:

可能重复:
How to get a random number in Ruby?

我只是好奇,但是 Ruby 是否有一个专门用于生成随机数的类,比如 Java 的 java.util.Random 类,或者是 Ruby 的所有 rand 方法?

【问题讨论】:

标签: ruby random


【解决方案1】:

内核中有一个rand方法:)

API Docs

rand(max=0) => number
Converts max to an integer using max1 = max.to_i.abs. If the result is zero, returns a pseudorandom floating point number greater than or equal to 0.0 and less than 1.0. Otherwise, returns a pseudorandom integer greater than or equal to zero and less than max1. Kernel::srand may be used to ensure repeatable sequences of random numbers between different runs of the program. Ruby currently uses a modified Mersenne Twister with a period of 2**19937-1.

   srand 1234                 #=> 0
   [ rand,  rand ]            #=> [0.191519450163469, 0.49766366626136]
   [ rand(10), rand(1000) ]   #=> [6, 817]
   srand 1234                 #=> 1234
   [ rand,  rand ]            #=> [0.191519450163469, 0.49766366626136]

【讨论】:

    猜你喜欢
    • 2014-07-16
    • 2015-02-16
    • 2020-07-24
    • 1970-01-01
    • 2011-11-28
    • 2016-08-08
    • 2021-06-01
    相关资源
    最近更新 更多