C++ cmath

C++ <cmath>: Math Functions and Errors

The C++ <cmath> library provides a comprehensive collection of functions to perform complex mathematical operations. From calculating square roots and powers, to trigonometric functions like sine and cosine, <cmath> is indispensable for scientific and gaming applications.


1. Using Common Math Functions

To use these functions, you must first include the library at the top of your file. Most <cmath> functions take double (floating-point) numbers as arguments and return a double.

Math Library Example

#include <iostream>
#include <cmath> // Include the math library
using namespace std;

int main() { cout << "Square root of 64 is: " << sqrt(64) << "\n"; cout << "2 to the power of 3 is: " << pow(2, 3) << "\n"; cout << "Absolute value of -15 is: " << abs(-15) << "\n"; cout << "Rounding 4.6 yields: " << round(4.6) << "\n";

return 0; }


2. Common Errors with <cmath>

Math operations can easily fail or yield unintended results if you feed them the wrong type of data.

Error 1: Domain Errors (NaN)

A classic mathematical rule is that you cannot take the square root of a negative number. If you attempt to run sqrt(-9.0) in C++, your program won't crash, but it will return a special value called NaN (Not a Number). If you use NaN in further calculations, all subsequent results will also become NaN!

Error 2: Integer Division inside Functions

If you try to calculate a fractional power, like $10^{1/2}$ (the square root of 10), you might be tempted to write pow(10, 1/2). However, 1/2 evaluates to 0 because of C++ integer division. The result will incorrectly be pow(10, 0) which is 1. The Fix: Always use decimals: pow(10, 1.0/2.0).

Error 3: Trigonometric Input Format

Functions like sin(), cos(), and tan() expect their arguments to be in radians, not degrees! If you pass sin(90) expecting the sine of 90 degrees, you will get an incorrect mathematical result. You must convert degrees to radians first: degrees * (PI / 180).


Exercise

?

Which function from the `<cmath>` library is used to calculate the square root of a number?