random numbers in awk?

Ozan Yigit oz at yunexus.yorku.ca
Thu Apr 25 01:08:11 AEST 1991


In article <1991Apr24.041134.14519 at athena.mit.edu>
jik at athena.mit.edu (Jonathan I. Kamens) writes:

>  The standard awk has no built-in way of getting a random number.

You mean the "old" awk. The standard awk (sometimes known as nawk, and is
a part of most up-to-date UN*X distributions these days) as documented in
TheBook, has rand(). Accept no substitutes. ;-)

>  There are probably other ways to get a random number, and other people will
>point them out :-).

Sure, like one can program a good random number generator, even in old
awk. Here is the integer minimal standard random number generator[1] in
old awk. It has been tested for correctness.

BEGIN {
	a = 16807
	m = 2147483647
	q = 127773	# m div a
	r = 2836	# m mod a
	seed = 123	# use awk -f ... seed=<whatever>
}

{
	test = a * (seed % q) - r * int(seed / q);
	if (test > 0)
		seed = test;
	else
		seed = test + m;
	print rand = seed
}

>  Of course, if you were using perl instead of awk ...

But, perl [or c, icon, python ...] is *not* awk. ;-) 

oz
---
[1] Park, Stephen K. and Keith W. Miller, ``Random Number Generators:
Good Ones are Hard to Find'', Communications of the ACM 31 (10), 1988
pp. 1192-1201
---
A pencil is so far the most effective software | internet: oz at nexus.yorku.ca
design tool I have found...   -- Amanda Walker | uucp: utai/utzoo!yunexus!oz



More information about the Comp.unix.questions mailing list