Skip to content

Commit 4036807

Browse files
committed
[GR-18163] Fix Random#rand when given a float range not returning random floats
PullRequest: truffleruby/3215
2 parents 8947d2b + 559e8cd commit 4036807

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
@@ -17,6 +17,7 @@ Bug fixes:
1717
* Update patch feature finding to prefer the longest matching load path (#2605, @bjfish).
1818
* Fix `Hash#{to_s,inspect}` for keys whose `#inspect` return a frozen String (#2613, @eregon).
1919
* Fix `Array#pack` with `x*` to not output null characters (#2614, @bjfish).
20+
* Fix `Random#rand` not returning random floats when given float ranges (#2612, @bjfish).
2021

2122
Compatibility:
2223

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)