Barbara Ericson, Allen B. Downey, Jason L. Wright (Editor)
Section3.3Math Functions
In mathematics, you have probably seen functions like and , and you have learned to evaluate expressions like and . First, you evaluate the expression in parentheses, which is called the argument of the function. For example, is approximately 1.571, and is 0.1 (if happens to be 10).
Then you can evaluate the function itself, either by looking it up in a table or by performing various computations. The of 1.571 is 1, and the of 0.1 is -1 (assuming that indicates the logarithm base 10).
This process can be applied repeatedly to evaluate more complicated expressions like . First we evaluate the argument of the innermost function, then evaluate the function, and so on.
C++ provides a set of built-in functions that includes most of the mathematical operations you can think of. The math functions are invoked using a syntax that is similar to mathematical notation:
The second example finds the sine of the value of the variable angle. C++ assumes that the values you use with sin and the other trigonometric functions (cos, tan) are in radians.
If you don’t happen to know to 15 digits, you can calculate it using the acos function. The arccosine (or inverse cosine) of -1 is , because the cosine of is -1.
Listing3.3.2.This program also uses built-in functions from the cmath library, specifically the functions that deal with angles. As you can see, we have a line of code that converts the default radians value to degrees.
Before you can use any of the math functions, you have to include the math header file. Header files contain information the compiler needs about functions that are defined outside your program. For example, in the “Hello, world!” program we included a header file named iostream using an include statement:
contains information about input and output (I/O) streams, including the object named cout. C++ has a powerful feature called namespaces, that allow you to write your own implementation of cout. But in most cases, we would need to use the standard implementation. To convey this to the compiler, we use the line
cmath is one of a number of header files that start with ‘c’ to signify that they are derived from similar header files in the C language. In C the math library is named math.h. In C++ you should always use the version of the library that starts with ’c’ as opposed to the one that ends with ’.h’.