Bug #1858
closedRandom#int's Handling of Invalid Arguments Contradicts its Documentation
Description
=begin
The documentation for Random#int claims that it will raise an ArgumentError when the argument is 0 or negative. In fact, 0 causes repeated generation of 0, and for negative numbers the sign appears to be ignored.
prng = Random.new(2)
=> #Random:0x96a4628
20.times.map { prng.int(0) }
=> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
prng = Random.new(2)
=> #Random:0x941888c
20.times.map { prng.int(-4) }
=> [0, 3, 1, 0, 2, 3, 2, 3, 0, 3, 2, 1, 3, 3, 1, 3, 3, 3, 2, 0]
Could this contradiction be addressed?
Further, I'd suggest that Random.new.int(1) also raises an ArgumentError as it's meaningless to generate a pseudo-random integer between 0 and 1.
=end
Updated by marcandre (Marc-Andre Lafortune) almost 15 years ago
=begin
The contradiction should be addressed, but it's important that Random.new.int(1) returns 0 for completeness' sake. For example, if someone has a good reason to use a specific random generator to pick an element in an array:
randgen = Random.new
#...
myarray[randgen.int(myarray.size)]
This should work even if the array contains only 1 element.
=end
Updated by nobu (Nobuyoshi Nakada) over 14 years ago
- Status changed from Open to Closed
- % Done changed from 0 to 100
=begin
Applied in changeset r24670.
=end