Go forward to String Functions.
Go backward to Calling Built-in.
Go up to Built-in.
Numeric Built-in Functions
==========================
Here is a full list of built-in functions that work with numbers:
`int(X)'
This gives you the integer part of X, truncated toward 0. This
produces the nearest integer to X, located between X and 0.
For example, `int(3)' is 3, `int(3.9)' is 3, `int(-3.9)' is -3,
and `int(-3)' is -3 as well.
`sqrt(X)'
This gives you the positive square root of X. It reports an error
if X is negative. Thus, `sqrt(4)' is 2.
`exp(X)'
This gives you the exponential of X, or reports an error if X is
out of range. The range of values X can have depends on your
machine's floating point representation.
`log(X)'
This gives you the natural logarithm of X, if X is positive;
otherwise, it reports an error.
`sin(X)'
This gives you the sine of X, with X in radians.
`cos(X)'
This gives you the cosine of X, with X in radians.
`atan2(Y, X)'
This gives you the arctangent of `Y / X' in radians.
`rand()'
This gives you a random number. The values of `rand' are
uniformly-distributed between 0 and 1. The value is never 0 and
never 1.
Often you want random integers instead. Here is a user-defined
function you can use to obtain a random nonnegative integer less
than N:
function randint(n) {
return int(n * rand())
}
The multiplication produces a random real number greater than 0
and less than N. We then make it an integer (using `int') between
0 and `N - 1'.
Here is an example where a similar function is used to produce
random integers between 1 and N. Note that this program will
print a new random number for each input record.
awk '
# Function to roll a simulated die.
function roll(n) { return 1 + int(rand() * n) }
# Roll 3 six-sided dice and print total number of points.
{
printf("%d points\n", roll(6)+roll(6)+roll(6))
}'
*Note:* `rand' starts generating numbers from the same point, or
"seed", each time you run `awk'. This means that a program will
produce the same results each time you run it. The numbers are
random within one `awk' run, but predictable from run to run.
This is convenient for debugging, but if you want a program to do
different things each time it is used, you must change the seed to
a value that will be different in each run. To do this, use
`srand'.
`srand(X)'
The function `srand' sets the starting point, or "seed", for
generating random numbers to the value X.
Each seed value leads to a particular sequence of "random" numbers.
Thus, if you set the seed to the same value a second time, you
will get the same sequence of "random" numbers again.
If you omit the argument X, as in `srand()', then the current date
and time of day are used for a seed. This is the way to get random
numbers that are truly unpredictable.
The return value of `srand' is the previous seed. This makes it
easy to keep track of the seeds for use in consistently reproducing
sequences of random numbers.