Mathematical constants in C provided by math.h
C provides the following mathematical constants in the header
file math.h
.
C name | Value | Meaning |
---|---|---|
M_E | e | The base of natural logarithms, e. |
M_LOG2E | log2e | The base 2 logarithm of e. |
M_LOG10E | log10e | The base 2 logarithm of e. |
M_LN2 | ln 2 | The natural logarithm of 2. |
M_LN10 | ln 10 | The natural logarithm of 10. |
M_PI | π | The circumference of a circle with diameter 1, π. |
M_PI_2 | π/2 | Half of π. |
M_PI_4 | π/4 | A quarter of π. |
M_1_PI | 1/π | The inverse of π. |
M_2_PI | 2/π | Twice the inverse of π. |
M_2_SQRTPI | 2/(√ π) | The inverse of the square root of π. |
M_SQRT2 | √2 | The square root of 2. |
M_SQRT1_2 | 1/(√2) | The inverse of the square root of 2. |
HUGE |
The maximum value of a single-precision floating-point number. | |
MAXFLOAT |
The maximum value of a non-infinite single-precision floating-point number. | |
HUGE_VAL |
∞ | Positive infinity. |
The following example C program prints out the values of the maths constants.
#include <stdio.h> #include <math.h> #define V(x) {x, #x} struct constant { double value; const char * name; } constants[] = { V (M_E), V (M_LOG2E), V (M_LOG10E), V (M_LN2), V (M_LN10), V (M_PI), V (M_PI_2), V (M_PI_4), V (M_1_PI), V (M_2_PI), V (M_2_SQRTPI), V (M_SQRT2), V (M_SQRT1_2), V (HUGE), V (MAXFLOAT), V (HUGE_VAL), }; int n_constants = sizeof (constants) / sizeof (struct constant); int main () { int i; for (i = 0; i < n_constants; i++) { printf ("%s: %g\n", constants[i].name, constants[i].value); } return 0; }
The output of the example looks like this:
M_E: 2.71828 M_LOG2E: 1.4427 M_LOG10E: 0.434294 M_LN2: 0.693147 M_LN10: 2.30259 M_PI: 3.14159 M_PI_2: 1.5708 M_PI_4: 0.785398 M_1_PI: 0.31831 M_2_PI: 0.63662 M_2_SQRTPI: 1.12838 M_SQRT2: 1.41421 M_SQRT1_2: 0.707107 HUGE: 3.40282e+38 MAXFLOAT: 3.40282e+38 HUGE_VAL: inf
Copyright © Ben Bullock 2009-2024. All
rights reserved.
For comments, questions, and corrections, please email
Ben Bullock
(benkasminbullock@gmail.com).
/
Privacy /
Disclaimer