Skip to content

Commit b3c89cd

Browse files
committed
random module improvements
1 parent ba16400 commit b3c89cd

1 file changed

Lines changed: 9 additions & 36 deletions

File tree

library/modules/random.go

Lines changed: 9 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -9,25 +9,26 @@ import (
99
"github.com/shopspring/decimal"
1010
)
1111

12+
var seed int64
13+
var randomizer *rand.Rand
14+
1215
var RandomMethods = map[string]*object.LibraryFunction{}
1316
var RandomProperties = map[string]*object.LibraryProperty{}
14-
var seed int64 = 0
1517

1618
func init() {
17-
// Set an initial fixed seed value. This can be overwritten at runtime.
18-
rand.Seed(seed)
19+
seed = time.Now().UnixNano()
20+
randomizer = rand.New(rand.NewSource(seed))
1921

2022
RegisterMethod(RandomMethods, "seed", randomSeed)
2123
RegisterMethod(RandomMethods, "random", randomRandom)
22-
RegisterMethod(RandomMethods, "range", randomRange)
2324

2425
RegisterProperty(RandomProperties, "seed", randomSeedProperty)
2526
}
2627

2728
// randomRandom returns a uniform pseudo-random real number in the range (0, 1).
2829
func randomRandom(scope *object.Scope, tok token.Token, args ...object.Object) object.Object {
2930
min := float64(0)
30-
max := float64(0)
31+
max := float64(1)
3132

3233
if len(args) > 0 {
3334
max, _ = args[0].(*object.Number).Value.Float64()
@@ -41,9 +42,9 @@ func randomRandom(scope *object.Scope, tok token.Token, args ...object.Object) o
4142
number := float64(0)
4243

4344
if max > 0 {
44-
number = float64(min + rand.Float64()*(max-min))
45+
number = float64(min + randomizer.Float64()*(max-min))
4546
} else {
46-
number = rand.Float64()
47+
number = randomizer.Float64()
4748
}
4849

4950
return &object.Number{Value: decimal.NewFromFloat(number)}
@@ -59,39 +60,11 @@ func randomSeed(scope *object.Scope, tok token.Token, args ...object.Object) obj
5960
seed = time.Now().UnixNano()
6061
}
6162

62-
rand.Seed(seed)
63+
randomizer.Seed(seed)
6364

6465
return nil
6566
}
6667

67-
// When called with a single number value (a), a
68-
// pseudo-random number will be returned in the range (0, a). When called with
69-
// two numbers (a, b), a pseudo-random number will be returned in the
70-
// range (a, b).
71-
func randomRange(scope *object.Scope, tok token.Token, args ...object.Object) object.Object {
72-
min := float64(0)
73-
max := float64(0)
74-
75-
if len(args) > 0 {
76-
max, _ = args[0].(*object.Number).Value.Float64()
77-
78-
if len(args) > 1 {
79-
min = max
80-
max, _ = args[1].(*object.Number).Value.Float64()
81-
}
82-
}
83-
84-
number := float64(0)
85-
86-
if max > 0 {
87-
number = float64(min + rand.Float64()*(max-min))
88-
} else {
89-
number = rand.Float64()
90-
}
91-
92-
return &object.Number{Value: decimal.NewFromFloat(number)}
93-
}
94-
9568
// Properties
9669

9770
// randomSeedProperty returns the current seed value used internally.

0 commit comments

Comments
 (0)