C math.h Guide: Core Functions, Usage & Examples

目次

1. Introduction

What Is math.h?

The C language provides the standard library math.h that supports mathematical calculations. By using this library, you can perform various mathematical operations such as trigonometric functions, exponentials and logarithms, square roots, and absolute value calculations.

Advantages of Using math.h

  • You can implement mathematical calculations with simple functions.
  • High‑precision calculations are easy to implement.
  • Since it’s a standard library, no additional installation is required.

How to Include math.h

To use math.h, write the #include directive at the beginning of your program as follows.
#include <stdio.h>
#include <math.h>
Also, when using functions from math.h, you need to add the -lm option at compile time. For example, when using GCC, compile as follows.
gcc program.c -o program -lm

Main Uses of math.h

math.h is used for the following purposes.
  1. Angle calculations using trigonometric functions
  2. Numeric operations using exponentials and logarithms
  3. Square‑root calculations
  4. Rounding of numeric values
  5. Absolute value calculations

2. Main math.h Functions by Use Case

2.1 Trigonometric Functions (Angle Calculations)

Trigonometric functions are used for calculations involving circles and triangles and are applied in a wide range of fields such as physics simulations and graphics processing.

Overview of sin(), cos(), and tan()

These functions are used to obtain the sine, cosine, and tangent respectively.
#include <stdio.h>
#include <math.h>

int main() {
    double angle = 3.14159 / 4; // 45 degrees (radians)

    printf("sin(45°) = %f
", sin(angle));
    printf("cos(45°) = %f
", cos(angle));
    printf("tan(45°) = %f
", tan(angle));

    return 0;
}
Output
sin(45°) = 0.707107
cos(45°) = 0.707107
tan(45°) = 1.000000
Notes
  • math.h trigonometric functions take radians as input. When using degree values, you need to convert them with (angle × π / 180).
double degrees = 45.0;
double radians = degrees * M_PI / 180.0;

2.2 Inverse Trigonometric Functions (Finding Angles)

Inverse trigonometric functions are used to determine angles from given ratios.

Overview of asin(), acos(), atan(), and atan2()

  • asin(x): returns the arcsine of x (range: -π/2 to π/2)
  • acos(x): returns the arccosine of x (range: 0 to π)
  • atan(x): returns the arctangent of x (range: -π/2 to π/2)
  • atan2(y, x): returns the arctangent of y/x (covers all quadrants)
#include <stdio.h>
#include <math.h>

int main() {
    double value = 0.5;

    printf("asin(0.5) = %f radians
", asin(value));
    printf("acos(0.5) = %f radians
", acos(value));
    printf("atan(1.0) = %f radians
", atan(1.0));
    printf("atan2(1.0, 1.0) = %f radians
", atan2(1.0, 1.0));

    return 0;
}
Notes
  • The arguments for asin() and acos() must be in the range -1.0 to 1.0. Passing values outside this range returns NaN (Not a Number).

2.3 Exponential and Logarithmic Functions (Exponentiation and Logarithm Calculations)

Exponential and logarithmic calculations are widely used in data analysis, statistics, and machine learning.

Overview of exp(), log(), and log10()

  • exp(x): computes e^x
  • log(x): computes the natural logarithm (ln x) (base e)
  • log10(x): computes the common logarithm (base 10)
#include <stdio.h>
#include <math.h>

int main() {
    double x = 2.0;

    printf("exp(2.0) = %f
", exp(x));
    printf("log(10.0) = %f
", log(10.0));
    printf("log10(100.0) = %f
", log10(100.0));

    return 0;
}
Output
exp(2.0) = 7.389056
log(10.0) = 2.302585
log10(100.0) = 2.000000
Notes
  • Passing a value ≤ 0 to log() results in NaN (e.g., log(0.0)).
  • exp(x) may overflow when given a large value.

2.4 Power and Square Root (Numeric Computations)

Power and square root calculations form the basis of many mathematical algorithms.

Overview of pow() and sqrt()

  • pow(x, y): computes x^y (x raised to the power y)
  • sqrt(x): computes the square root of x
#include <stdio.h>
#include <math.h>

int main() {
    double x = 9.0;

    printf("pow(2, 3) = %f
", pow(2.0, 3.0));
    printf("sqrt(9.0) = %f
", sqrt(x));

    return 0;
}
Notes
  • pow(x, y) can also compute a square root by specifying y as 0.5 (e.g., pow(9.0, 0.5) = 3.0).
  • Passing a negative value to sqrt(x) results in NaN.

2.5 Numeric Processing (Rounding and Absolute Value)

Functions that round numbers to integers or compute absolute values are important for monetary calculations and integer processing.

Overview of fabs(), ceil(), floor(), and round()

  • fabs(x): returns the absolute value of x
  • ceil(x): rounds x up (ceil)
  • floor(x): rounds x down (floor)
  • round(x): rounds x to the nearest integer
#include <stdio.h>
#include <math.h>

int main() {
    double num = -5.7;

    printf("fabs(-5.7) = %f
", fabs(num));
    printf("ceil(-5.7) = %f
", ceil(num));
    printf("floor(-5.7) = %f
", floor(num));
    printf("round(-5.7) = %f
", round(num));

    return 0;
}
Output
fabs(-5.7) = 5.700000
ceil(-5.7) = -5.000000
floor(-5.7) = -6.000000
round(-5.7) = -6.000000
侍エンジニア塾

3. How to Use math.h and Points to Note

3.1 Compile Options When Using math.h

math.h When used, many C compilers require explicitly linking the math library (libm).

Compilation with GCC

When using GCC, if you do not specify the -lm option, programs that include math functions may not link correctly, and errors like the following can occur.
undefined reference to `sin'
To avoid this problem, compile with the -lm option as shown below.
gcc program.c -o program -lm

When Using Clang or MSVC

  • Clang may also require the -lm option (depending on the environment).
  • In Microsoft Visual Studio (MSVC), the functions in math.h are available without specifying -lm.

3.2 Notes on Floating-Point Precision and Errors

The math functions in math.h use floating-point arithmetic (IEEE 754 standard), so precision errors may occur.

What Is Floating-Point Error?

Floating-point numbers are represented internally as approximations, so they cannot hold exact values. Consequently, small errors can appear in calculation results.

Concrete Example of Error

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

int main() {
    double x = 0.1;
    double y = 0.2;
    double z = 0.3;

    if ((x + y) == z) {
        printf("Equaln");
    } else {
        printf("Not Equaln");
    }

    return 0;
}
Output
Not Equal
Thus, cases occur where 0.1 + 0.2 does not become exactly 0.3.

Comparison Considering Floating-Point Error

When accounting for error, set a threshold (epsilon) for comparison.
#include <stdio.h>
#include <math.h>

#define EPSILON 1e-9

int main() {
    double x = 0.1, y = 0.2, z = 0.3;

    if (fabs((x + y) - z) < EPSILON) {
        printf("Approximately Equaln");
    } else {
        printf("Not Equaln");
    }

    return 0;
}
Output
Approximately Equal

3.3 Error Handling in math.h

Some functions in math.h generate errors when given invalid arguments. In such cases, you need to handle the errors appropriately.

Examples of Errors

  • sqrt(-1.0)NaN (Not a Number)
  • log(0.0)-inf (negative infinity)
  • 1.0 / 0.0inf (positive infinity)

Error Handling Using errno

#include 
#include 
#include 

int main() {
    errno = 0; // reset errno
    double result = sqrt(-1.0); 

    if (errno != 0) {
        perror("A calculation error occurred");
    } else {
        printf("Result: %f\n", result);
    }

    return 0;
}
Main errno error codes
Error CodeMeaning
EDOMAn invalid value was passed to a math function (e.g., sqrt(-1.0))
ERANGEThe result exceeded the representable range (e.g., exp(1000.0))

3.4 Best Practices for Using math.h

  • Add the -lm option at compile time
  • Consider floating-point errors and use a threshold when comparing
  • Perform error handling when invalid input values are passed
  • Check to prevent overflow/underflow
  • Verify that the calculation result is not NaN or inf

4. FAQ (Frequently Asked Questions)

4.1 How to handle errors when math.h functions cause an error?

Example Problem

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

int main() {
    double result = sqrt(-1.0);
    printf("sqrt(-1.0) = %fn", result);
    return 0;
}
Output
sqrt(-1.0) = nan
In this case, taking the square root of a negative number returns NaN (Not a Number).

Solution

  • Check input values in advance to prevent invalid values.
  • Leverage errno to detect errors.
#include <stdio.h>
#include <math.h>
#include <errno.h>

int main() {
    errno = 0;
    double result = sqrt(-1.0);

    if (errno == EDOM) {
        printf("Error: Invalid input value\n");
    } else {
        printf("sqrt(-1.0) = %fn", result);
    }

    return 0;
}

4.2 What compile options are needed when using math.h?

C language math.h depends on the math library (libm). Therefore, when compiling with GCC, you need to add the -lm option.

Compilation Method

gcc program.c -o program -lm

What Happens If the Option Is Not Specified?

If you use math.h functions without adding -lm, GCC produces an “undefined reference” error like the following.
/tmp/ccxlj3hs.o: In function `main':
program.c:(.text+0x15): undefined reference to `sin'
collect2: error: ld returned 1 exit status

4.3 What is the precision of math.h functions?

math.h uses floating-point numbers based on the IEEE 754 standard, so the precision of calculations has limits.

Example Problem

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

int main() {
    double x = 0.1, y = 0.2;
    double z = x + y;

    if (z == 0.3) {
        printf("Equal\n");
    } else {
        printf("Different\n");
    }

    return 0;
}
Output
Different

Solution

Floating-point comparisons need to consider an error tolerance (EPSILON).
#include <stdio.h>
#include <math.h>

#define EPSILON 1e-9

int main() {
    double x = 0.1, y = 0.2, z = 0.3;

    if (fabs((x + y) - z) < EPSILON) {
        printf("Approximately equal\n");
    } else {
        printf("Different\n");
    }

    return 0;
}
Output
Approximately equal

4.4 Can math.h functions be used with integer types?

math.h functions expect floating-point types (double) as arguments. Therefore, passing an integer causes an implicit conversion to double.

Example Problem

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

int main() {
    int x = 4;
    printf("sqrt(4) = %fn", sqrt(x));
    return 0;
}

Solution

By explicitly casting, you can prevent unintended behavior.
#include <stdio.h>
#include <math.h>

int main() {
    int x = 4;
    double result = sqrt((double)x); // explicit cast
    printf("sqrt(4) = %fn", result);
    return 0;
}

4.5 Is there a π constant defined in math.h?

Since C99, the standard defines a π constant M_PI in math.h.

Example Usage

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

int main() {
    printf("π = %.15fn", M_PI);
    return 0;
}
Output
π = 3.141592653589793

When M_PI Is Unavailable

Some compilers or older environments may not define M_PI. In that case, you need to define it yourself.
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

5. math.h Applications: Practical Examples

5.1 Applications in Physics Simulations

1. Object Falling Motion (Free-Fall Calculation)

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

#define G 9.81  // gravitational acceleration

int main() {
    double time = 3.0;  // 3 seconds of fall
    double distance = 0.5 * G * pow(time, 2);

    printf("After %.2f seconds, the object will fall %.2f meters.n", time, distance);
    return 0;
}
Output
After 3.00 seconds, the object will fall 44.15 meters.

5.2 Applications in Statistical Analysis

Standard Deviation Calculation

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

double mean(double data[], int size) {
    double sum = 0.0;
    for (int i = 0; i < size; i++) {
        sum += data[i];
    }
    return sum / size;
}

double standardDeviation(double data[], int size) {
    double avg = mean(data, size);
    double sum = 0.0;
    for (int i = 0; i < size; i++) {
        sum += pow(data[i] - avg, 2);
    }
    return sqrt(sum / size);
}

int main() {
    double dataset[] = {10.0, 20.0, 30.0, 40.0, 50.0};
    int size = sizeof(dataset) / sizeof(dataset[0]);

    printf("Standard Deviation: %.2fn", standardDeviation(dataset, size));
    return 0;
}
Output
Standard Deviation: 14.14

5.3 Applications in Game Development

2D Game Character Angle Calculation

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

int main() {
    double playerX = 1.0, playerY = 1.0;
    double enemyX = 4.0, enemyY = 5.0;

    double angle = atan2(enemyY - playerY, enemyX - playerX) * 180.0 / M_PI;

    printf("Enemy direction: %.2f degreesn", angle);
    return 0;
}
Output
Enemy direction: 45.00 degrees

3D Game Collision Detection

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

int main() {
    double obj1[3] = {1.0, 2.0, 3.0};  // coordinates of object 1
    double obj2[3] = {4.0, 6.0, 3.0};  // coordinates of object 2
    double distance;

    distance = sqrt(pow(obj2[0] - obj1[0], 2) +
                    pow(obj2[1] - obj1[1], 2) +
                    pow(obj2[2] - obj1[2], 2));

    printf("Distance between objects: %.2fn", distance);
    return 0;
}
Output
Distance between objects: 5.00

6. Summary

6.1 Main Points of math.h

  1. Basics of math.h
  • It is the C language standard library and is used for mathematical calculations.
  • You need to declare #include <math.h> at the beginning of your program.
  1. Compilation Considerations
  • When using math.h functions, GCC requires the -lm option.
   gcc program.c -o program -lm
  1. Key Functions by Use Case
  • Trigonometric functions (sin, cos, tan) → Angle calculations
  • Inverse trigonometric functions (asin, acos, atan, atan2) → Obtaining angles
  • Exponential and logarithmic (exp, log, log10) → Exponential and logarithmic operations
  • Power and square root (pow, sqrt) → Powers and square roots
  • Numeric processing (fabs, ceil, floor, round) → Absolute values and rounding
  1. Considerations of Precision and Error
  • Functions in math.h use floating‑point arithmetic (IEEE‑754 standard), so precision errors can occur.
   #define EPSILON 1e-9
   if (fabs(a - b) < EPSILON) { /* consider as almost equal */ }
  1. Error Handling
  • Providing invalid input (e.g., sqrt(-1.0), log(0.0)) can result in NaN or inf.
   errno = 0;
   double result = sqrt(-1.0);
   if (errno != 0) {
       perror("Error occurred");
   }
  1. Practical Examples
  • Physical simulation → Calculations of falling and projectile motion
  • Statistical analysis → Calculation of standard deviation
  • Game development → Enemy direction calculation (atan2()) and collision detection (sqrt())

6.2 Reference Links for Learning math.h

If you want to learn more about math.h, the following resources are recommended.

6.3 Final Learning Steps

  1. Try Basic Functions
  • Create simple programs using functions such as sqrt(), pow(), sin(), cos().
  1. Write Code with Error Handling in Mind
  • Use errno to understand behavior on invalid input.
  1. Create Practical Programs
  • Leverage math.h in concrete projects such as game development or data analysis.

Final Summary

math.h provides many mathematical functions as the C standard library. By understanding proper usage and considering precision errors and error handling, you can perform safer and more accurate mathematical computations. Be sure to use math.h in real programs and challenge yourself with more advanced C programming.