DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 

(gawk.info) Arithmetic Ops

Info Catalog (gawk.info) Conversion (gawk.info) Expressions (gawk.info) Concatenation
 
 Arithmetic Operators
 ====================
 
    The `awk' language uses the common arithmetic operators when
 evaluating expressions.  All of these arithmetic operators follow normal
 precedence rules, and work as you would expect them to.  Arithmetic
 operations are evaluated using double precision floating point, which
 has the usual problems of inexactness and exceptions.(1)
 
    Here is a file `grades' containing a list of student names and three
 test scores per student (it's a small class):
 
      Pat   100 97 58
      Sandy  84 72 93
      Chris  72 92 89
 
 This programs takes the file `grades', and prints the average of the
 scores.
 
      $ awk '{ sum = $2 + $3 + $4 ; avg = sum / 3
      >        print $1, avg }' grades
      -| Pat 85
      -| Sandy 83
      -| Chris 84.3333
 
    This table lists the arithmetic operators in `awk', in order from
 highest precedence to lowest:
 
 `- X'
      Negation.
 
 `+ X'
      Unary plus.  The expression is converted to a number.
 
 `X ^ Y'
 `X ** Y'
      Exponentiation: X raised to the Y power.  `2 ^ 3' has the value
      eight.  The character sequence `**' is equivalent to `^'.  (The
      POSIX standard only specifies the use of `^' for exponentiation.)
 
 `X * Y'
      Multiplication.
 
 `X / Y'
      Division.  Since all numbers in `awk' are floating point numbers,
      the result is not rounded to an integer: `3 / 4' has the value
      0.75.
 
 `X % Y'
      Remainder.  The quotient is rounded toward zero to an integer,
      multiplied by Y and this result is subtracted from X.  This
      operation is sometimes known as "trunc-mod."  The following
      relation always holds:
 
           b * int(a / b) + (a % b) == a
 
      One possibly undesirable effect of this definition of remainder is
      that `X % Y' is negative if X is negative.  Thus,
 
           -17 % 8 = -1
 
      In other `awk' implementations, the signedness of the remainder
      may be machine dependent.
 
 `X + Y'
      Addition.
 
 `X - Y'
      Subtraction.
 
    For maximum portability, do not use the `**' operator.
 
    Unary plus and minus have the same precedence, the multiplication
 operators all have the same precedence, and addition and subtraction
 have the same precedence.
 
    ---------- Footnotes ----------
 
    (1) David Goldberg, `What Every Computer Scientist Should Know About
 Floating-point Arithmetic' (http://www.validgh.com/goldberg/paper.ps),
 `ACM Computing Surveys' *23*, 1 (1991-03), 5-48.
 
Info Catalog (gawk.info) Conversion (gawk.info) Expressions (gawk.info) Concatenation
automatically generated byinfo2html