Skip to content

Commit 559e8cd

Browse files
committed
Fix Random#rand when given a float range not returning random floats
1 parent f4ab861 commit 559e8cd

File tree

3 files changed

+7
-1
lines changed

3 files changed

+7
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ Bug fixes:
1414
* Fix `Integer#{<<,>>}` with RHS bignum and long (@eregon).
1515
* Fix a resource leak from allocators defined in C extensions (@aardvark179).
1616
* `SIGINT`/`Interrupt`/`Ctrl+C` now shows the backtrace and exits as signaled, like CRuby (@eregon).
17+
* Fix `Random#rand` not returning random floats when given float ranges (#2612, @bjfish).
1718

1819
Compatibility:
1920

spec/ruby/core/random/rand_spec.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,11 @@
205205
Random.new(42).rand(0..1.0).should be_kind_of(Float)
206206
end
207207

208+
it "returns a float within a given float range" do
209+
Random.new(42).rand(0.0...100.0).should == 37.454011884736246
210+
Random.new(42).rand(-100.0...0.0).should == -62.545988115263754
211+
end
212+
208213
it "raises an ArgumentError when the startpoint lacks #+ and #- methods" do
209214
-> do
210215
Random.new.rand(Object.new..67)

src/main/ruby/truffleruby/core/truffle/random_operations.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,8 @@ def self.rand_range(randomizer, range)
8989
end
9090

9191
if max > 0.0
92+
r = randomizer.random_float
9293
if scale > 1
93-
r = randomizer.random_float
9494
r *= 1.0000000000000002 unless exclude_end
9595
return +(+(+(r - 0.5) * max) * scale) + mid
9696
end

0 commit comments

Comments
 (0)