Math Functions

Built-in mathematical functions in C

๐Ÿงฎ What are Math Functions?

C provides a rich set of built-in mathematical functions through the math.h library. These functions handle complex calculations like trigonometry, logarithms, powers, and rounding operations efficiently.


// Using math functions
#include <stdio.h>
#include <math.h>  // Required for math functions

int main() {
    double num = 16.0;
    printf("Square root of %.1f = %.2f\n", num, sqrt(num));
    printf("Power 2^3 = %.0f\n", pow(2, 3));
    return 0;
}
                                    

Math Function Categories

๐Ÿ“

Basic Math

Power, square root, absolute value

pow(2, 3)    // 2^3 = 8
sqrt(25)     // โˆš25 = 5
fabs(-5.5)   // |โˆ’5.5| = 5.5
๐Ÿ“Š

Rounding

Floor, ceiling, round functions

floor(4.8)   // 4.0
ceil(4.2)    // 5.0
round(4.6)   // 5.0
๐Ÿ“ˆ

Trigonometry

Sine, cosine, tangent functions

sin(M_PI/2)  // 1.0
cos(0)       // 1.0
tan(M_PI/4)  // 1.0
๐Ÿ“‰

Logarithms

Natural and base-10 logarithms

log(2.718)   // ln(e) โ‰ˆ 1
log10(100)   // logโ‚โ‚€(100) = 2
exp(1)       // eยน โ‰ˆ 2.718

๐Ÿ”น Basic Math Functions

Essential mathematical operations in C include power, square root, absolute value, and minimum/maximum calculations. The pow() function calculates powers, sqrt() computes square roots, fabs() returns absolute values, and fmin()/fmax() find minimum/maximum values. These functions handle common mathematical requirements in scientific computing, game development, and data analysis applications. Include math.h header and compile with -lm flag to use math library functions effectively.

#include <stdio.h>
#include <math.h>

int main() {
    double x = 25.0, y = -7.5;
    
    // Power and roots
    printf("Power: 2^3 = %.0f\n", pow(2, 3));
    printf("Square root: โˆš%.0f = %.2f\n", x, sqrt(x));
    printf("Cube root: โˆ›8 = %.2f\n", cbrt(8));
    
    // Absolute values
    printf("Absolute: |%.1f| = %.1f\n", y, fabs(y));
    
    // Min and Max
    printf("Min(5, 3) = %.0f\n", fmin(5, 3));
    printf("Max(5, 3) = %.0f\n", fmax(5, 3));
    
    return 0;
}

Output:

Power: 2^3 = 8
Square root: โˆš25 = 5.00
Cube root: โˆ›8 = 2.00
Absolute: |-7.5| = 7.5
Min(5, 3) = 3
Max(5, 3) = 5

๐Ÿ”น Rounding Functions

Different rounding functions provide various ways to convert decimal numbers into integers. floor() rounds down to nearest integer, ceil() rounds up, round() rounds to nearest integer, and trunc() removes decimal parts without rounding. Negative numbers behave differently with each function, requiring careful consideration when choosing rounding methods. Understanding rounding behavior prevents unexpected results in financial calculations, data analysis, and scientific computations.

#include <stdio.h>
#include <math.h>

int main() {
    double numbers[] = {4.2, 4.7, -3.8, -3.2, 5.5};
    int size = 5;
    
    printf("Number\tFloor\tCeil\tRound\tTrunc\n");
    printf("------\t-----\t----\t-----\t-----\n");
    
    for (int i = 0; i < size; i++) {
        printf("%.1f\t%.0f\t%.0f\t%.0f\t%.0f\n",
               numbers[i],
               floor(numbers[i]),    // Round down
               ceil(numbers[i]),     // Round up
               round(numbers[i]),    // Round to nearest
               trunc(numbers[i]));   // Remove decimal part
    }
    
    return 0;
}

Output:

Number Floor Ceil Round Trunc
------ ----- ---- ----- -----
4.2 4 5 4 4
4.7 4 5 5 4
-3.8 -4 -3 -4 -3
-3.2 -4 -3 -3 -3
5.5 5 6 6 5

๐Ÿ”น Trigonometric Functions

Trigonometric functions enable angle calculations and geometry operations essential for graphics and physics applications. Functions sin(), cos(), and tan() work with angles in radians, not degrees, requiring conversion using the formula radians = degrees * PI / 180. These functions power game development, computer graphics, physics simulations, and engineering calculations. Understanding trigonometric values and angle conversion ensures correct results in applications using angle-based logic.

#include <stdio.h>
#include <math.h>

int main() {
    // Angles in radians (ฯ€/180 * degrees)
    double angle30 = M_PI / 6;  // 30 degrees
    double angle45 = M_PI / 4;  // 45 degrees
    double angle90 = M_PI / 2;  // 90 degrees
    
    printf("Trigonometric Functions:\n");
    printf("Angle\tSin\tCos\tTan\n");
    printf("-----\t---\t---\t---\n");
    
    printf("30ยฐ\t%.2f\t%.2f\t%.2f\n", 
           sin(angle30), cos(angle30), tan(angle30));
    printf("45ยฐ\t%.2f\t%.2f\t%.2f\n", 
           sin(angle45), cos(angle45), tan(angle45));
    printf("90ยฐ\t%.2f\t%.2f\t%.2f\n", 
           sin(angle90), cos(angle90), tan(angle90));
    
    // Convert radians to degrees
    double radians = 1.0;
    double degrees = radians * 180.0 / M_PI;
    printf("\n%.2f radians = %.2f degrees\n", radians, degrees);
    
    return 0;
}

Output:

Trigonometric Functions:
Angle Sin Cos Tan
----- --- --- ---
30ยฐ 0.50 0.87 0.58
45ยฐ 0.71 0.71 1.00
90ยฐ 1.00 0.00 16331239353195370.00

1.00 radians = 57.30 degrees

๐Ÿ”น Logarithmic and Exponential Functions

Logarithmic and exponential functions model growth, decay, and scale-dependent phenomena in scientific applications. exp() calculates exponential values, log() computes natural logarithms, log10() calculates base-10 logarithms, and log2() computes base-2 logarithms. These functions appear in finance, physics, biology, and computer science for modeling various natural phenomena and algorithm analysis. Mastering logarithmic and exponential operations enables solving complex real-world problems.

#include <stdio.h>
#include <math.h>

int main() {
    double x = 10.0, y = 2.718;  // e โ‰ˆ 2.718
    
    printf("Exponential Functions:\n");
    printf("exp(1) = e^1 = %.3f\n", exp(1));
    printf("exp(2) = e^2 = %.3f\n", exp(2));
    
    printf("\nLogarithmic Functions:\n");
    printf("log(%.3f) = ln(e) = %.3f\n", y, log(y));
    printf("log10(%.0f) = logโ‚โ‚€(10) = %.0f\n", x, log10(x));
    printf("log10(100) = %.0f\n", log10(100));
    printf("log10(1000) = %.0f\n", log10(1000));
    
    // Logarithm base 2
    printf("log2(8) = %.0f\n", log2(8));
    printf("log2(16) = %.0f\n", log2(16));
    
    return 0;
}

Output:

Exponential Functions:
exp(1) = e^1 = 2.718
exp(2) = e^2 = 7.389

Logarithmic Functions:
log(2.718) = ln(e) = 1.000
log10(10) = logโ‚โ‚€(10) = 1
log10(100) = 2
log10(1000) = 3
log2(8) = 3
log2(16) = 4

๐Ÿ”น Practical Math Examples

Real-world applications demonstrate how mathematical functions solve practical problems in distance calculation and finance. Calculate distances using the Pythagorean theorem with sqrt(), compute circular areas using pow() and mathematical constants, and calculate compound interest for financial planning. These examples show how theoretical mathematics translates into functional programs solving actual business and scientific challenges, reinforcing the practical importance of mathematical functions in real applications.

#include <stdio.h>
#include <math.h>

// Calculate distance between two points
double distance(double x1, double y1, double x2, double y2) {
    return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
}

// Calculate area of circle
double circleArea(double radius) {
    return M_PI * pow(radius, 2);
}

// Calculate compound interest
double compoundInterest(double principal, double rate, int time) {
    return principal * pow(1 + rate/100, time);
}

int main() {
    // Distance calculation
    double dist = distance(0, 0, 3, 4);
    printf("Distance between (0,0) and (3,4): %.2f\n", dist);
    
    // Circle area
    double area = circleArea(5.0);
    printf("Area of circle with radius 5: %.2f\n", area);
    
    // Compound interest
    double amount = compoundInterest(1000, 5, 3);
    printf("$1000 at 5%% for 3 years: $%.2f\n", amount);
    
    return 0;
}

Output:

Distance between (0,0) and (3,4): 5.00
Area of circle with radius 5: 78.54
$1000 at 5% for 3 years: $1157.63

๐Ÿ”น Important Notes

Math functions in C require proper compilation and linking. When working with mathematical operations, you need to include the math library to access functions like sqrt(), sin(), and pow(). These functions are essential for scientific computing and numerical analysis. Understanding how to properly compile and link mathematical functions ensures your programs run without errors and perform efficiently.

๐Ÿ“ Remember:

  • Include math.h: Always include the math header
  • Link math library: Use -lm flag when compiling
  • Use double: Math functions work with double precision
  • Radians for trig: Trigonometric functions use radians, not degrees
  • Check domain: Some functions have restrictions (sqrt of negative numbers)

๐Ÿ”ง Compilation:

To compile C programs with math functions, use the -lm flag. The command gcc program.c -lm -o program links the math library to your executable. The -lm flag tells the compiler to include the math library, which contains all mathematical function definitions. Without this flag, you'll encounter linking errors when trying to use math functions in your programs.

๐Ÿง  Test Your Knowledge

Which header file must be included to use math functions in C?