Math Functions in C

C provides a set of mathematical functions included in the <math.h> header file. These functions perform various mathematical operations.

Common Math Functions

Function Description Example
double sin(double x)Sine of angle x (in radians)sin(0.0)
double cos(double x)Cosine of angle x (in radians)cos(0.0)
double tan(double x)Tangent of angle x (in radians)tan(0.0)
double exp(double x)Exponential function exexp(1.0)
double log(double x)Natural logarithm of xlog(2.71828)
double log10(double x)Base-10 logarithm of xlog10(100.0)
double pow(double x, double y)x raised to the power ypow(2.0, 3.0)
double sqrt(double x)Square root of xsqrt(16.0)
double ceil(double x)Smallest integer value not less than xceil(2.3)
double floor(double x)Largest integer value not greater than xfloor(2.7)
double fabs(double x)Absolute value of xfabs(-5.0)
double fmod(double x, double y)Remainder of x divided by yfmod(5.3, 2.0)

Examples of Math Functions

1. Calculating Power and Square Root

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

int main() {
    double base = 2.0, exponent = 3.0;
    double result = pow(base, exponent);
    printf("%.2f raised to %.2f is %.2f\n", base, exponent, result);
    printf("Square root of %.2f is %.2f\n", result, sqrt(result));
    return 0;
}

2. Using Trigonometric Functions

#include <stdio.h>
#include <math.h>
#define PI 3.14159265

int main() {
    double angle = 30.0;
    double radians = angle * (PI / 180.0);
    printf("Sine of %.2f degrees is %.2f\n", angle, sin(radians));
    printf("Cosine of %.2f degrees is %.2f\n", angle, cos(radians));
    return 0;
}

Best Practices

  • Include <math.h> to access math functions.
  • Use constants like PI for clarity and accuracy.
  • Be aware of the domain and range of functions to avoid errors.

Don'ts

  • Don't forget to link the math library when compiling (use -lm flag in GCC).
  • Don't pass invalid arguments that are outside the function's domain.
  • Don't ignore the possibility of precision errors with floating-point numbers.

Key Takeaways

  • Math functions provide advanced mathematical operations.
  • Proper use of these functions enhances the computational capabilities of your programs.
  • Always consult the documentation for function behavior and requirements.