Node:Mathematical functions, Next:Questions for Chapter 13, Previous:Common library functions, Up:Libraries
Let us now examine some simple math library functions. (This section presupposes some familiarity on your part with trigonometry. If you have none, you might want to skip this section for now - but reading it won't hurt you!)
The following mathematical functions, among others, are available on GNU
systems. Many of the functions described below are macros, so the usual
caveats about macro parameters apply. (See Macro functions.) All of
these functions require parameters of type double
or long
float
. Constants used must be written in floating point form: for
instance, write 7.0
instead of just 7
.
Here is a list of some functions you can expect to find in the headers
math.h
, tgmath.h
, and limits.h
.
abs
fabs
for a proper function version.
acos
asin
atan
atan2
atan2
will find the result
more accurately than atan
will.
result = atan2 (x, y); result = atan2 (x, 3.14);
ceil
cos
cosh
exp
fabs
abs
if you
want one that is a macro.
floor
log
log10
pow
result = pow (x,y); /*raise x to the power y */ result = pow (x,2); /* square x */
sin
sinh
sqrt
tan
tanh
Here is a code example that uses a few of the math library routines listed above.
#include <stdio.h> #include <math.h> int main() { double my_pi; my_pi = 4 * atan(1.0); /* Print the value of pi we just calculated, to 32 digits. */ printf ("my_pi = %.32f\n", my_pi); /* Print value of pi from math library, to 32 digits. */ printf ("M_PI = %.32f\n", M_PI); return 0; }
If you save the above example as pi.c
, you will have to
enter a command such as the one below to compile it.
gcc pi.c -o pi -lm
When you compile and run the code example, it should print the following
results:
my_pi = 3.14159265358979311599796346854419 M_PI = 3.14159265358979311599796346854419