Skip to content

Commit 4878cbd

Browse files
authored
Merge pull request #131 from Flipez/fix-random-prediction
[stdlib/math] Seed rand on each call
2 parents 3e2ed3c + 33b8428 commit 4878cbd

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

stdlib/math.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package stdlib
33
import (
44
"math"
55
"math/rand"
6+
"time"
67

78
"github.com/flipez/rocket-lang/object"
89
)
@@ -11,6 +12,10 @@ var mathFunctions = map[string]*object.BuiltinFunction{}
1112
var mathProperties = map[string]*object.BuiltinProperty{}
1213

1314
func init() {
15+
// Randomize seed each runtime to avoid predictable results
16+
randSource := rand.NewSource(time.Now().UnixNano())
17+
randomizedRand := rand.New(randSource)
18+
1419
mathFunctions["abs"] = object.NewBuiltinFunction("abs",
1520
object.MethodLayout{
1621
ReturnPattern: object.Args(object.Arg(object.FLOAT_OBJ)),
@@ -215,7 +220,7 @@ func init() {
215220
ReturnPattern: object.Args(object.Arg(object.FLOAT_OBJ)),
216221
},
217222
func(_ object.Environment, args ...object.Object) object.Object {
218-
return object.NewFloat(rand.Float64())
223+
return object.NewFloat(randomizedRand.Float64())
219224
},
220225
)
221226
mathFunctions["remainder"] = object.NewBuiltinFunction("remainder",

0 commit comments

Comments
 (0)