Skip to content

Commit 27d409b

Browse files
author
David Brady
committed
Fixed bug in random number generator in Generating Predictable Random Numbers
1 parent 7bc9f67 commit 27d409b

File tree

1 file changed

+7
-22
lines changed

1 file changed

+7
-22
lines changed

chapters/math/generating-predictable-random-numbers.textile

Lines changed: 7 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -28,36 +28,21 @@ class Rand
2828
@seed = seed
2929

3030
# return a random integer 0 <= n < @modulo
31-
randn:
31+
randn: ->
3232
# new_seed = (a * seed + c) % m
3333
@seed = (@multiplier*@seed + @offset) % @modulo
3434

3535
# return a random float 0 <= f < 1.0
36-
rand: ->
36+
randf: ->
3737
this.randn() / @modulo
3838

3939
# return a random int 0 <= f < n
40-
randi: (n) ->
41-
Math.floor(this.rand() * n)
40+
rand: (n) ->
41+
Math.floor(this.randf() * n)
4242

43-
r = new Rand 0
44-
r.randn().toString(16)
45-
# => "3c6ef35f"
46-
47-
r.randn().toString(16)
48-
# => "47502932"
49-
50-
r.randn().toString(16)
51-
# => "d1ccf6e9"
52-
53-
r.randn().toString(16)
54-
# => "aaf95334"
55-
56-
r.randn().toString(16)
57-
# => "6252e503"
58-
59-
r.randn().toString(16)
60-
# => "9f2ec686"
43+
# return a random int min <= f < max
44+
rand2: (min, max) ->
45+
min + this.rand(max-min)
6146
{% endhighlight %}
6247

6348
h2. Discussion

0 commit comments

Comments
 (0)