Lesson 26
Math Library
Covers common <cmath> functions including square roots, powers, rounding, trigonometric, and logarithmic functions.
Lesson content
What is the Math Library?
The Math Library is a standard C++ library that contains functions for performing mathematical operations. It is included using the <cmath> header.
#include <cmath>The library provides functions for:
- Square roots
- Powers and exponents
- Absolute values
- Trigonometric calculations
- Logarithms
- Rounding numbers
- Finding minimum and maximum values
- Floating-point operations
Why does it exist?
- Performing accurate calculations
- Reducing development time
- Improving code readability
- Providing optimized mathematical algorithms
Real-world use cases
- Game development
- Scientific computing
- Machine learning
- Data analysis
- Financial calculations
- Computer graphics
- Physics simulations
- Engineering software
Prerequisites
- Variables
- Data types
- Functions
- Operators
- Basic arithmetic
- Input and output
Including the Math Library
#include <cmath>
// This header provides access to all standard mathematical functions.Common math functions
- sqrt(x) – square root, e.g. sqrt(25) → 5
- pow(x, y) – x raised to the power y, e.g. pow(2, 3) → 8
- abs(x) – absolute value, e.g. abs(-10) → 10
- ceil(x) – round up, e.g. ceil(5.2) → 6
- floor(x) – round down, e.g. floor(5.9) → 5
- round(x) – round to nearest integer, e.g. round(5.6) → 6
- trunc(x) – remove decimal part, e.g. trunc(5.9) → 5
- fmod(x, y) – floating-point remainder, e.g. fmod(10,3) → 1
- sin(x) – sine (radians), e.g. sin(0) → 0
- cos(x) – cosine (radians), e.g. cos(0) → 1
- tan(x) – tangent (radians), e.g. tan(0) → 0
- log(x) – natural logarithm, e.g. log(10)
- log10(x) – base-10 logarithm, e.g. log10(100) → 2
- exp(x) – e raised to x, e.g. exp(1)
- cbrt(x) – cube root, e.g. cbrt(27) → 3
- hypot(x, y) – hypotenuse, e.g. hypot(3,4) → 5
Power function
double result = pow(3, 4);
// Output: 81Square root
double root = sqrt(64);
// Output: 8Absolute value
int value = abs(-25);
// Output: 25Rounding functions
ceil(4.2); // 5
floor(4.8); // 4
round(4.5); // 5
trunc(4.9); // 4Trigonometric functions
These functions use radians, not degrees.
sin(0);
cos(0);
tan(0);
// Output:
// 0
// 1
// 0Logarithmic functions
log(10);
log10(1000);
// Output:
// 2.30259
// 3Example 1: Square root and power
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
cout << sqrt(49) << endl;
cout << pow(2, 5) << endl;
return 0;
}
// Output:
// 7
// 32Example 2: Rounding numbers
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
cout << ceil(5.2) << endl;
cout << floor(5.8) << endl;
cout << round(5.5) << endl;
cout << trunc(5.9) << endl;
return 0;
}
// Output:
// 6
// 5
// 6
// 5Example 3: Trigonometric functions
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
cout << sin(0) << endl;
cout << cos(0) << endl;
cout << tan(0) << endl;
return 0;
}Example 4: Distance between two points
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x1 = 2.0;
double y1 = 3.0;
double x2 = 7.0;
double y2 = 11.0;
double distance = hypot(x2 - x1, y2 - y1);
cout << distance << endl;
return 0;
}
// Output: 9.43398Example 5: Scientific calculator
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double number = 81.0;
cout << "Square Root: " << sqrt(number) << endl;
cout << "Cube Root: " << cbrt(number) << endl;
cout << "Power: " << pow(number, 2) << endl;
cout << "Natural Log: " << log(number) << endl;
cout << "Base-10 Log: " << log10(number) << endl;
return 0;
}Common mistakes and pitfalls
- Calling sqrt(-4) for real numbers. Fix: ensure the input is non-negative or use complex numbers
- Passing degrees directly to sin(). Fix: convert degrees to radians using degrees * M_PI / 180.0
- Using pow(x, 2) for simple squaring in performance-critical code. Fix: use x * x when appropriate
- Forgetting #include <cmath>. Fix: include the <cmath> header
- Comparing floating-point results with ==. Fix: compare within a small tolerance (epsilon)
Best practices
- Include <cmath> whenever mathematical functions are needed
- Use descriptive variable names for mathematical calculations
- Validate input before calling functions like sqrt() or log()
- Prefer std::hypot() over manually calculating sqrt(x*x + y*y) to improve numerical stability
- Be aware that trigonometric functions expect radians, not degrees
- Avoid unnecessary calls to pow() when simple multiplication is clearer and faster
When not to use this
- Simple arithmetic operators (+, -, *, /) are sufficient
- Exact decimal arithmetic is required (consider specialized decimal libraries)
- You're implementing custom algorithms for educational purposes and want to understand the underlying mathematics
Summary
- Include the <cmath> header to access mathematical functions
- Use sqrt() for square roots and pow() for exponentiation
- Use abs() to calculate absolute values
- Use ceil(), floor(), round(), and trunc() for different rounding behaviors
- Trigonometric functions (sin(), cos(), tan()) use radians
- log() computes the natural logarithm, while log10() computes the base-10 logarithm
- Validate inputs to avoid domain errors (such as sqrt() of a negative number)
- Prefer clear, readable code and choose the most appropriate math function for the task
Frequently asked questions
Which header file contains mathematical functions in C++?
Use the <cmath> header.
What is the difference between pow() and sqrt()?
pow(x, y) raises x to the power y, while sqrt(x) returns the square root of x. For example, pow(3, 2) is 9 and sqrt(9) is 3.
Why does sin(90) not return 1?
Because C++ trigonometric functions expect radians, not degrees. Convert degrees to radians first, such as degrees * 3.14159265358979323846 / 180.0, before calling sin().
What is the difference between ceil(), floor(), and round()?
ceil(5.2) rounds up to 6, floor(5.8) rounds down to 5, and round(5.5) rounds to the nearest integer, 6.
Is the C++ Math Library enough for advanced scientific programming?
For many applications, yes. However, highly specialized scientific computing may require additional libraries, such as linear algebra or symbolic mathematics libraries, depending on the project's needs.