< Day Day Up > |
6.22. Built-In Arithmetic FunctionsTable 6.13 lists the built-in arithmetic functions, where x and y are arbitrary expressions.
6.22.1 Integer FunctionThe 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
6.22.2 Random Number GeneratorThe rand FunctionThe 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 FunctionThe 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. |
< Day Day Up > |