Previous Section  < Day Day Up >  Next Section

6.22. Built-In Arithmetic Functions

Table 6.13 lists the built-in arithmetic functions, where x and y are arbitrary expressions.

Table 6.13. Arithmetic Functions

Function

Value Returned

atan2(x,y)

Arctangent of y/x in the range

cos(x)

Cosine of x (x in radians)

exp(x)

Exponential function e to the power of x

int(x)

Integer portion of x; truncated toward 0 when x > 0

log(x)

Natural (base e) logarithm of x

rand( )

Random number r, where 0 < r< 1

sin(x)

Sine of x (with x in radians)

sqrt(x)

Square root of x

srand(x)

x is a new seed for rand( )


6.22.1 Integer Function

The int function truncates any digits to the right of the decimal point to create a whole number. There is no rounding off.

Example 6.156.

1   % awk 'END{print 31/3}' filename

    10.3333

2   % awk 'END{print int(31/3})' filename

    10


EXPLANATION

  1. In the END block, the result of the division is to print a floating-point number.

  2. In the END block, the int function causes the result of the division to be truncated at the decimal point. A whole number is displayed.

6.22.2 Random Number Generator

The rand Function

The rand function generates a pseudorandom floating-point number greater than or equal to 0 and less than 1.

Example 6.157.

% nawk '{print rand()}' filename

0.513871

0.175726

0.308634



% nawk '{print rand()}' filename

0.513871

0.175726

0.308634


EXPLANATION

Each time the program runs, the same set of numbers is printed. The srand function can be used to seed the rand function with a new starting value. Otherwise, as in this example, the same sequence is repeated each time rand is called.

The srand Function

The srand function without an argument uses the time of day to generate the seed for the rand function. Srand(x) uses x as the seed. Normally, x should vary during the run of the program.

Example 6.158.

% nawk 'BEGIN{srand()};{print rand()}' filename

0.508744

0.639485

0.657277



% nawk 'BEGIN{srand()};{print rand()}' filename

0.133518

0.324747

0.691794


EXPLANATION

The srand function sets a new seed for rand. The starting point is the time of day. Each time rand is called, a new sequence of numbers is printed.

Example 6.159.

% nawk 'BEGIN{srand()};{print 1 + int(rand() * 25)}' filename

6

24

14


EXPLANATION

The srand function sets a new seed for rand. The starting point is the time of day. The rand function selects a random number between 0 and 25 and casts it to an integer value.

    Previous Section  < Day Day Up >  Next Section