Permalink
Browse files

Fix JRUBY-5243: [RubySpec][1.9] Random#rand with Range considers Inte…

…gers as Floats if one end point is a float
  • Loading branch information...
1 parent 5f95929 commit ddc27915369ca0997fb43a9879a24798a8703cb8 @BanzaiMan BanzaiMan committed Dec 24, 2010
Showing with 19 additions and 6 deletions.
  1. +0 −1 spec/tags/1.9/ruby/core/random/rand_tags.txt
  2. +19 −5 src/org/jruby/RubyRandom.java
@@ -1 +0,0 @@
-fails(JRUBY-5243):Random#rand with Range considers Integers as Floats if one end point is a float
@@ -124,8 +124,15 @@ private static IRubyObject randCommon(ThreadContext context, IRubyObject arg, Ra
} else if (arg instanceof RubyRange) { // RANGE ARGUMENT
RubyRange range = (RubyRange) arg;
IRubyObject first = range.first();
- IRubyObject last = range.last();
- if (range.include_p19(context, last).isTrue()) {
+ IRubyObject last = range.last();
+
+ boolean returnFloat = first instanceof RubyFloat || last instanceof RubyFloat;
+ if (returnFloat) {
+ first = first.convertToFloat();
+ last = last.convertToFloat();
+ }
+
+ if (range.include_p19(context, last).isTrue() && (!returnFloat)) {
last = last.callMethod(context, "+", runtime.newFixnum(1));
}
@@ -135,11 +142,18 @@ private static IRubyObject randCommon(ThreadContext context, IRubyObject arg, Ra
}
IRubyObject difference = last.callMethod(context, "-", first);
- int max = (int) RubyNumeric.num2long(difference);
+ if (returnFloat) {
+ double max = (double) RubyNumeric.num2dbl(difference);
+ double rand = random.nextDouble() * ((RubyFloat) difference).getDoubleValue();
+ return RubyFloat.newFloat(runtime, ((RubyFloat) first).getDoubleValue() + rand);
+
+ } else {
+ int max = (int) RubyNumeric.num2long(difference);
- int rand = random.nextInt(max);
+ int rand = random.nextInt(max);
- return RubyNumeric.num2fix(first.callMethod(context, "+", runtime.newFixnum(rand)));
+ return RubyNumeric.num2fix(first.callMethod(context, "+", runtime.newFixnum(rand)));
+ }
} else if (arg instanceof RubyFloat) { // FLOAT ARGUMENT
double max = RubyNumeric.num2dbl(arg);
if (max <= 0 && raiseArgError) {

0 comments on commit ddc2791

Please sign in to comment.