Chapter 16: Mathematical Operations
C provides a robust suite of mathematical functions through the <math.h> library. However, as a systems language, C also requires you to understand the underlying representation of numbers, specifically floating-point values.
I. Standard Math Functions (<math.h>)
To use these functions, you must #include <math.h> and link with the math library (using the -lm flag in GCC).
| Function | Action | Example |
|---|---|---|
pow(x, y) | x raised to power y | pow(2, 3) = 8.0 |
sqrt(x) | Square root | sqrt(16) = 4.0 |
abs(x) / fabs(x) | Absolute value | fabs(-5.5) = 5.5 |
ceil(x) | Round up | ceil(4.2) = 5.0 |
floor(x) | Round down | floor(4.8) = 4.0 |
sin, cos, tan | Trigonometry | Uses radians |
#include <stdio.h>
#include <math.h>
int main() {
double base = 2.0, exp = 3.0;
printf("%.1f ^ %.1f = %.1f\n", base, exp, pow(base, exp));
return 0;
}
II. Floating-Point Mechanics (IEEE 754)
Most modern systems represent float and double using the IEEE 754 standard. A floating-point number is stored in three parts:
- Sign Bit: 0 for positive, 1 for negative.
- Exponent: Scales the number.
- Mantissa (Significand): Stores the actual digits.
Precision Issues
Because floating-point numbers are stored in binary, they cannot represent some decimal fractions (like 0.1) exactly. Never compare floats using ==. Use a small epsilon instead:
if (fabs(a - b) < 0.00001) { /* Equal */ }
III. Integer Overflow and Underflow
If you add 1 to the maximum value of a signed integer (INT_MAX), it "wraps around" to the minimum value (INT_MIN). This is Undefined Behavior in C and is a frequent cause of security bugs (like buffer overflows).
IV. Random Number Generation (<stdlib.h>)
rand(): Returns a pseudo-random integer between 0 andRAND_MAX.srand(seed): Seeds the random number generator. Usually seeded with the current time:srand(time(NULL)).
V. Complex Numbers (C99)
The <complex.h> header adds support for complex and imaginary numbers, essential for engineering and scientific applications.
#include <complex.h>
double complex z = 1.0 + 2.0 * I;
VI. Performance Tip: Fast Inverse Square Root
C is famous for "hacks" that bypass standard math libraries for speed. The Quake III Arena fast inverse square root is a legendary example of using bit manipulation and pointer casting to calculate 1/sqrt(x) significantly faster than the standard library.