Awk built-in functions – mathematical functions

awk supports the following built-in mathematical functions:

  • atan2( y, x ) 
    Returns the arc tangent of y/x.
  • cos( x )
    Returns the cosine of x; x is radians.
  • exp( x )
    Returns the power function of x.
  • log( x )
    Returns the natural logarithm of x.
  • sin( x )
    Returns the sine of x; x is radians.
  • sqrt( x )
    Returns the square root of x.

Example

In the following example, we demonstrate the built-in function atan2 of awk.

➜  ~ awk 'BEGIN{
        PI = 3.1415926;
        x = -10;
        y = 10;
        result = atan2 (y,x) * 180 / PI;

        printf "The arc tangent for (x=%f, y=%f) is %f degrees\n", x, y, result
}'

In the following example, we demonstrate the built-in function cos of awk, which returns the cosine of X

➜  ~ awk 'BEGIN {
  PI = 3.1415926;
  param = 15;
  result = cos(param * PI / 180.0);

  printf "The cosine of %f degrees is %f.\n", param, result
}'

In the following example, we demonstrate the built-in function exp of awk, which returns the power function of x.

➜  ~ awk 'BEGIN {
  param = 15
  result = exp(param);

  printf "The exponential value of %f is %f.\n", param, result
}'

In the following example, we show you the built-in function sqrt of awk, which returns the square root of X.

➜  ~ awk 'BEGIN {
  param = 15
  result = sqrt(param)

  printf "sqrt(%f) = %f\n", param, result
}'

Add a Comment

Your email address will not be published. Required fields are marked *