srand(seed) 为 "seed" 取一个整数值
rand() 返回一个十进制数 >= 0 并且 < 1。
因此,保存 rand() 的输出以直接用作下一个种子将导致 srand() 始终使用零种子。看(记住对 srand() 的调用会返回使用的 PREVIOUS 种子):
$ awk -v s=0.1 'BEGIN{srand(s); print rand(); print srand()}'
0.566305
0
$ awk -v s=0.9 'BEGIN{srand(s); print rand(); print srand()}'
0.566305
0
因此,如果您想使用 rand() 的输出作为下一个种子,您需要将其乘以您希望种子小于的任何数字,例如 1,000,000:
$ awk 'BEGIN{
if ( (getline s < "myseed.txt") > 0 ) {
print "seed read from file =", s
srand(1000000*s)
}
else {
print "using default seed of seconds since epoch"
srand()
}
r = rand()
print r > "myseed.txt"
print "seed actually used by srand() was:", srand()
print "rand() =", r
}'
using default seed of seconds since epoch
seed actually used by srand() was: 1368282525
rand() = 0.331514
$ awk 'BEGIN{
if ( (getline s < "myseed.txt") > 0 ) {
print "seed read from file =", s
srand(1000000*s)
}
else {
print "using default seed of seconds since epoch"
srand()
}
r = rand()
print r > "myseed.txt"
print "seed actually used by srand() was:", srand()
print "rand() =", r
}'
seed read from file = 0.331514
seed actually used by srand() was: 331514
rand() = 0.677688
$ awk 'BEGIN{
if ( (getline s < "myseed.txt") > 0 ) {
print "seed read from file =", s
srand(1000000*s)
}
else {
print "using default seed of seconds since epoch"
srand()
}
r = rand()
print r > "myseed.txt"
print "seed actually used by srand() was:", srand()
print "rand() =", r
}'
seed read from file = 0.677688
seed actually used by srand() was: 677688
rand() = 0.363388
在第一次执行时,文件“myseed.txt”不存在。