Project

General

Profile

Actions

Bug #1858

closed

Random#int's Handling of Invalid Arguments Contradicts its Documentation

Added by runpaint (Run Paint Run Run) almost 15 years ago. Updated about 13 years ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 1.9.2dev (2009-08-01 trunk 24343) [i686-linux]
Backport:
[ruby-core:24677]

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

Actions #1

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

Actions #2

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

Actions

Also available in: Atom PDF

Like0
Like0Like0