## Numeric Built-in Functions

Here is a full list of built-in functions that work with numbers. Optional parameters are enclosed in square brackets ("[" and "]").

`int(x)`
This produces the nearest integer to x, located between x and zero, truncated toward zero. For example, `int(3)` is three, `int(3.9)` is three, `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 two.
`exp(x)`
This gives you the exponential of x (`e ^ 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 zero and one. The value is never zero and never one. Often you want random integers instead. Here is a user-defined function you can use to obtain a random non-negative integer less than n:
```function randint(n) {
return int(n * rand())
}
```
The multiplication produces a random real number greater than zero and less than `n`. We then make it an integer (using `int`) between zero and `n` - 1, inclusive. Here is an example where a similar function is used to produce random integers between one and n. This program prints 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))
}'
```
Caution: In most `awk` implementations, including `gawk`, `rand` starts generating numbers from the same starting number, or seed, each time you run `awk`. Thus, a program will generate 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.(10) 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.