C++ cmath

Mathematical functions and operations in C++

🧮 What is cmath?

The cmath library provides mathematical functions in C++. It includes functions for basic arithmetic, trigonometry, logarithms, exponentials, and other mathematical operations for scientific and engineering calculations.


#include <cmath>
#include <iostream>
using namespace std;

int main() {
    double result = sqrt(16);
    cout << "Square root of 16: " << result << endl;
    return 0;
}
                                    

Output:

Square root of 16: 4

Math Function Categories

🔢

Basic Functions

Fundamental mathematical operations

abs(-5)    // Absolute value
pow(2, 3)  // Power (2^3)
sqrt(25)   // Square root
📐

Trigonometric

Sine, cosine, tangent functions

sin(3.14159/2)  // Sine
cos(0)          // Cosine
tan(3.14159/4)  // Tangent
📊

Logarithmic

Natural and base-10 logarithms

log(2.718)   // Natural log
log10(100)   // Base-10 log
exp(1)       // e^x
🔄

Rounding

Functions to round numbers

ceil(4.2)   // Round up
floor(4.8)  // Round down
round(4.5)  // Round nearest

🔹 Basic Math Functions

Basic Math Functions provide essential mathematical operations for computational tasks, including absolute value, exponentiation, and roots. Functions like abs(-15.7) return 15.7, pow(4, 2) computes 16, and sqrt(25) yields 5. These operations are foundational for algorithms, physics simulations, and data analysis, ensuring accurate numerical processing. By implementing or using these functions, developers can handle common mathematical challenges efficiently, making them indispensable in scientific computing, game development, and engineering applications.

#include <cmath>
#include <iostream>
using namespace std;

int main() {
    double x = -15.7;
    double y = 4.0;
    
    // Absolute value
    cout << "abs(" << x << ") = " << abs(x) << endl;
    
    // Power function
    cout << "pow(" << y << ", 2) = " << pow(y, 2) << endl;
    cout << "pow(2, " << y << ") = " << pow(2, y) << endl;
    
    // Square root
    cout << "sqrt(" << y << ") = " << sqrt(y) << endl;
    cout << "sqrt(25) = " << sqrt(25) << endl;
    
    // Cube root
    cout << "cbrt(27) = " << cbrt(27) << endl;
    
    return 0;
}

Output:

abs(-15.7) = 15.7
pow(4, 2) = 16
pow(2, 4) = 16
sqrt(4) = 2
sqrt(25) = 5
cbrt(27) = 3

🔹 Trigonometric Functions

Trigonometric Functions calculate relationships between angles and sides in triangles, essential for graphics, physics, and engineering. They include sin(), cos(), and tan(), operating on angles in radians or degrees (e.g., 0.785398 radians for 45°). For example, sin(0.785398) = 0.707107 and cos(π/2) ≈ 0. These functions enable rotation, oscillation, and wave modeling in applications like game engines, signal processing, and robotics, providing precise angular calculations for complex simulations and visualizations.

#include <cmath>
#include <iostream>
using namespace std;

int main() {
    double pi = 3.14159265;
    double angle = pi / 4;  // 45 degrees in radians
    
    cout << "Angle: " << angle << " radians (45 degrees)" << endl;
    cout << "sin(" << angle << ") = " << sin(angle) << endl;
    cout << "cos(" << angle << ") = " << cos(angle) << endl;
    cout << "tan(" << angle << ") = " << tan(angle) << endl;
    
    // Special angles
    cout << "\nSpecial angles:" << endl;
    cout << "sin(0) = " << sin(0) << endl;
    cout << "cos(0) = " << cos(0) << endl;
    cout << "sin(π/2) = " << sin(pi/2) << endl;
    cout << "cos(π/2) = " << cos(pi/2) << endl;
    
    return 0;
}

Output:

Angle: 0.785398 radians (45 degrees)
sin(0.785398) = 0.707107
cos(0.785398) = 0.707107
tan(0.785398) = 1

Special angles:
sin(0) = 0
cos(0) = 1
sin(π/2) = 1
cos(π/2) = 6.12323e-17

🔹 Rounding Functions

Rounding Functions adjust floating-point numbers to integers or specified decimals using methods like floor, ceil, and round. For instance, floor(4.7) returns 4, ceil(4.2) gives 5, and round(4.5) results in 4 (following round-half-to-even). These functions are critical for financial calculations, data discretization, and UI displays where precision control is needed. They help avoid floating-point errors, ensure consistent formatting, and are widely used in statistics, billing systems, and graphical rendering.

#include <cmath>
#include <iostream>
using namespace std;

int main() {
    double numbers[] = {4.2, 4.7, -3.2, -3.8, 4.5, 5.5};
    int size = sizeof(numbers) / sizeof(numbers[0]);
    
    cout << "Number\tfloor\tceil\tround" << endl;
    cout << "======\t=====\t====\t=====" << endl;
    
    for (int i = 0; i < size; i++) {
        double num = numbers[i];
        cout << num << "\t" 
             << floor(num) << "\t" 
             << ceil(num) << "\t" 
             << round(num) << endl;
    }
    
    return 0;
}

Output:

Number floor ceil round
====== ===== ==== =====
4.2 4 5 4
4.7 4 5 5
-3.2 -4 -3 -3
-3.8 -4 -3 -4
4.5 4 5 4
5.5 5 6 6

🔹 Practical Math Example

The Practical Math Example demonstrates calculating the distance between two points in a 2D plane using the Euclidean distance formula. Given points (1, 2) and (4, 6), it computes differences (dx = 3, dy = 4), squares them, sums the results (9 + 16 = 25), and takes the square root to get distance = 5. This application is fundamental for geometry, pathfinding algorithms, graphics, and machine learning, providing a clear example of how mathematical concepts solve real-world spatial problems efficiently.

#include <cmath>
#include <iostream>
using namespace std;

int main() {
    // Two points: (x1, y1) and (x2, y2)
    double x1 = 1.0, y1 = 2.0;
    double x2 = 4.0, y2 = 6.0;
    
    cout << "Point 1: (" << x1 << ", " << y1 << ")" << endl;
    cout << "Point 2: (" << x2 << ", " << y2 << ")" << endl;
    
    // Calculate distance using distance formula
    // distance = sqrt((x2-x1)² + (y2-y1)²)
    double dx = x2 - x1;
    double dy = y2 - y1;
    double distance = sqrt(pow(dx, 2) + pow(dy, 2));
    
    cout << "\nDistance calculation:" << endl;
    cout << "dx = " << dx << endl;
    cout << "dy = " << dy << endl;
    cout << "distance = sqrt(" << dx << "² + " << dy << "²)" << endl;
    cout << "distance = sqrt(" << pow(dx, 2) << " + " << pow(dy, 2) << ")" << endl;
    cout << "distance = " << distance << endl;
    
    return 0;
}

Output:

Point 1: (1, 2)
Point 2: (4, 6)

Distance calculation:
dx = 3
dy = 4
distance = sqrt(3² + 4²)
distance = sqrt(9 + 16)
distance = 5

🧠 Test Your Knowledge

What does the sqrt() function do?