Next: Summary Up: Top-down design using Functions Previous: The need for functions

The mathematical function library in C++

The functions sin and fabs have already been used in programs in previous Lessons. For example in section 16.3 the statement

cout << endl << "  " << degree << "       "
     << sin(radian);
occurred. This statement used sin(radian) as a call of the C++ function with the name sin which returns as its value the sine of the angle (in radians) which is given as its input parameter (in this case the variable radian). In this use of a function there are no output parameters, the single result that the function produces is returned to the calling program via the name of the function.

 

Some of the mathematical functions available in the C++ mathematics library are listed below.
acos(x) inverse cosine, -1 <= x <= +1, returns value in radians in range 0 to PI
asin(x) inverse sine, -1 <= x <= +1, returns value in radians in range 0 to PI
atan(x) inverse tangent, returns value in radians in range -PI/2 to PI/2
cos(x) returns cosine of x, x in radians
sin(x) returns sine of x, x in radians
tan(x) returns tangent of x, x in radians
exp(x) exponential function, e to power x
log(x) natural log of x (base e), x > 0
sqrt(x) square root of x, x >= 0
fabs(x) absolute value of x
floor(x) largest integer not greater than x
ceil(x) smallest integer not less than x
In all these functions the parameter x is a floating point value. The x is used as a formal parameter, that is it is used to denote that a parameter is required and to allow the effect of the function to be described. When the function is called then this formal parameter is replaced by an actual parameter. The actual parameter can be a constant, a variable or an expression. An expression may include a call of another function.

These functions are called by quoting their name followed by the actual parameter enclosed in rounded brackets, for example, exp(x+1). The function call can then be used anywhere in an expression that an ordinary variable may be used. Hence the following examples:

y = sin(3.14159);
z = cos(a) + sin(a);
factor = sin(theta)/(sin(delta) - sin(delta-theta));
theta = acos(1.0/sqrt(1 - x*x));
if (sin(x) > 0.7071)
  cout << "Angle is greater than 45 degrees";
cout << "The value is " << exp(-a*t)*sin(a*t);

The file math.h must be included in any program that is going to use any functions from this library. math.h also defines some constants which may be used. For example M_PI can be used for $\pi$ and M_E can be used for $e$.



Next: Summary Up: Top-down design using Functions Previous: The need for functions