[前][次][番号順一覧][スレッド一覧]

ruby-changes:12935

From: nobu <ko1@a...>
Date: Wed, 26 Aug 2009 23:59:00 +0900 (JST)
Subject: [ruby-changes:12935] Ruby:r24674 (trunk): * random.c (random_rand): fixed for edge cases of ranges.

nobu	2009-08-26 23:58:44 +0900 (Wed, 26 Aug 2009)

  New Revision: 24674

  http://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=rev&revision=24674

  Log:
    * random.c (random_rand): fixed for edge cases of ranges.
      [ruby-dev:39166]

  Modified files:
    trunk/ChangeLog
    trunk/random.c
    trunk/test/ruby/test_rand.rb

Index: ChangeLog
===================================================================
--- ChangeLog	(revision 24673)
+++ ChangeLog	(revision 24674)
@@ -1,3 +1,8 @@
+Wed Aug 26 23:58:39 2009  Nobuyoshi Nakada  <nobu@r...>
+
+	* random.c (random_rand): fixed for edge cases of ranges.
+	  [ruby-dev:39166]
+
 Wed Aug 26 21:49:23 2009  NARUSE, Yui  <naruse@r...>
 
 	* lib/tempfile.rb: add documents from Hongli Lai's fork.
Index: test/ruby/test_rand.rb
===================================================================
--- test/ruby/test_rand.rb	(revision 24673)
+++ test/ruby/test_rand.rb	(revision 24674)
@@ -199,6 +199,14 @@
     assert_raise(ArgumentError, '[ruby-core:24677]') { r.rand(-1) }
     assert_raise(ArgumentError, '[ruby-core:24677]') { r.rand(-1.0) }
     assert_raise(ArgumentError, '[ruby-core:24677]') { r.rand(0) }
+    assert_equal(0, r.rand(1), '[ruby-dev:39166]')
+    assert_equal(0, r.rand(0...1), '[ruby-dev:39166]')
+    assert_equal(0, r.rand(0..0), '[ruby-dev:39166]')
+    assert_equal(0.0, r.rand(0.0..0.0), '[ruby-dev:39166]')
+    assert_raise(ArgumentError, '[ruby-dev:39166]') { r.rand(0...0) }
+    assert_raise(ArgumentError, '[ruby-dev:39166]') { r.rand(0..-1) }
+    assert_raise(ArgumentError, '[ruby-dev:39166]') { r.rand(0.0...0.0) }
+    assert_raise(ArgumentError, '[ruby-dev:39166]') { r.rand(0.0...-0.1) }
   end
 
   def test_random_seed
Index: random.c
===================================================================
--- random.c	(revision 24673)
+++ random.c	(revision 24674)
@@ -760,10 +760,11 @@
 static unsigned long
 limited_rand(struct MT *mt, unsigned long limit)
 {
-    unsigned long mask = make_mask(limit);
     int i;
-    unsigned long val;
+    unsigned long val, mask;
 
+    if (!limit) return 0;
+    mask = make_mask(limit);
   retry:
     val = 0;
     for (i = SIZEOF_LONG/SIZEOF_INT32-1; 0 <= i; i--) {
@@ -1016,7 +1017,7 @@
 	    v = Qnil;
 	    if (FIXNUM_P(vmax)) {
 	      fixnum:
-		if ((max = FIX2LONG(vmax) - excl) > 0) {
+		if ((max = FIX2LONG(vmax) - excl) >= 0) {
 		    unsigned long r = limited_rand(&rnd->mt, (unsigned long)max);
 		    v = ULONG2NUM(r);
 		}
@@ -1042,6 +1043,9 @@
 		}
 		v = rb_float_new(r * max);
 	    }
+	    else if (max == 0.0 && !excl) {
+		v = rb_float_new(0.0);
+	    }
 	}
     }
     else {

--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]