21.07.2015 Views

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8: Functions 131int(x)sqrt(x)exp(x)log(x)sin(x)cos(x)This returns the nearest integer to x, located between x and zero and truncatedtoward zero.For example, int(3) is 3, int(3.9) is 3, int(-3.9) is −3, and int(-3) is −3as well.This returns the positive square root of x. gawk reports an error if x is negative.Thus, sqrt(4) is 2.This returns the exponential of x (e ^ x) or reports an error if x is out ofrange. The range of values x can have depends on your machine’s floatingpointrepresentation.This returns the natural logarithm of x, if x is positive; otherwise, it reports anerror.This returns the sine of x, with x in radians.This returns the cosine of x, with x in radians.atan2(y, x)This returns the arctangent of y / x in radians.rand()This returns a random number. The values of rand are uniformly distributedbetween zero and one. The value could be zero but is never one. 1Often random integers are needed instead. Following is a user-defined functionthat can be used to obtain a random non-negative integer less than n:function randint(n) {return int(n * rand())}The multiplication produces a random number greater than zero and less thann. Using int, this result is made into an integer between zero and n − 1,inclusive.The following example uses a similar function to produce random integers betweenone and n. This program prints a new random number for each inputrecord:# 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 generatingnumbers from the same starting number, or seed, each time you run awk. Thus,1 The C version of rand is known to produce fairly poor sequences of random numbers. However, nothingrequires that an awk implementation use the C rand to implement the awk version of rand. In fact, gawkuses the BSD random function, which is considerably better than rand, to produce random numbers.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!