Some Functions
- Computing a function is a small section of code
- It possibly takes some input known as parameters/arguments.
- It possibly returns a value.
- If you have the definition of a function in mathematics, ignore it.
- In this section we will discover a number of mathematical functions.
- Most are from the math library
-
#include <cmath>
- The power function
-
pow(b,e)
- computes $b^e$ where
- We call
b
and e
parameters or arguments.
- See this reference
- Note there are at least four different versions.
- the compiler selects the version to call based on the arguments.
-
abs
and fabs
and labs
- Compute the absolute value of an integer, (float, double, long double) and long
-
sin
, cos
...
- Trig functions.
- Works with angles in radians.
-
sqrt
- Many others
- Problem 3 from the end of the chapter
The factorial of a number n, (written n!) is the number times the factorial of itself minus one. This self-referential definition is easier to understand through an example: The factorial of 2 is 2 * 1; the factorial of 3 is 3 * 2 * 1; the factorial of 4 is 4 * 3 * 2 * 1; and so on. Factorials grow very large, very quickly. An approximation to the factorial for larger values is given by Stirling's formula:
$$n! = e^{-n}n^n\sqrt{2\pi n}$$
The exp
function in the <cmath>
header file gives the value of $e$ raised to a given power. Write a c++ program that computes the factorial of 15 both directly and with Stirling's formula, and outputs both results, together with their difference. You will need to use the double
type for this computation.