From 012adf26b561be0b734466562cc818d6b77b0e54 Mon Sep 17 00:00:00 2001 From: Ben Hoyt Date: Sat, 14 Sep 2024 17:14:45 +1200 Subject: [PATCH] Make srand() use unix time in seconds, and set seed for next srand() (#241) This is more POSIX-compatible. Fixes #231 --- interp/interp_test.go | 1 + interp/vm.go | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/interp/interp_test.go b/interp/interp_test.go index 5fbb1e3..5cd38a1 100644 --- a/interp/interp_test.go +++ b/interp/interp_test.go @@ -621,6 +621,7 @@ BEGIN { print (a==x, b==y, c==z) } `, "", "0 0 0 0\n1 1 1\n", "", ""}, + {`BEGIN { s = srand(srand()); print (s > 1700000000) }`, "", "1\n", "", ""}, {` BEGIN { for (i = 0; i < 1000; i++) { diff --git a/interp/vm.go b/interp/vm.go index 57d84f1..12bc13e 100644 --- a/interp/vm.go +++ b/interp/vm.go @@ -1021,7 +1021,8 @@ func (p *interp) callBuiltin(builtinOp compiler.BuiltinOp) error { case compiler.BuiltinSrand: prevSeed := p.randSeed - p.random.Seed(time.Now().UnixNano()) + p.randSeed = float64(time.Now().Unix()) + p.random.Seed(int64(math.Float64bits(p.randSeed))) p.push(num(prevSeed)) case compiler.BuiltinSrandSeed: