The Pre-Processor and standard libraries - Mathematical functions

Chapter chap8 section 7

The math.h include file contains prototypes for a useful set of mathematical functions.

	asin    atan    atan2   cos     sin     tan
	cosh    sinh    tanh    exp     frexp   ldexp
	log     log10   modf    pow     sqrt    ceil
	fabs    floor   fmod

For details of what these do you should consult the appropriate manual. There is no standard set of mathematical constants (such as "pi") defined in any header file, you've got to set these up for yourself although many implementations do provide such information, frequently in the math.h include file.

If a mathematical function fails due to an inappropriate input value or the output value lying outside the range of representable numbers then the global variable errno is set to a value indicating the type of error. The value returned by the mathematical function is implementation dependent. The include file errno.h includes the declaration of errno and #define's for the two likely values EDOM and ERANGE used for indicating errors in mathematical function evaluation. EDOM means the input value is inappropriate, a domain error and ERANGE means that the output value is out of range.

On some systems you may need to include extra command line arguments for the C compiler to make it look in the mathematical functions library. On a Unix system

cc summ.c -lm

would be typical, the "-lm" flag specifying the maths library. This shouldn't be necessary on an ANSI system. The following program which tabulates squares, square roots and cube roots shows the use of the maths library functions sqrt() and pow().

#include	<math.h>
main()
{
	int	i=0;
	while(i++<16)
		printf("%2d %4d %8.6lf %8.6lf\n",
			i,i*i,sqrt(i),pow(i,1.0/3));
}
producing the output
 1    1 1.000000 1.000000
 2    4 1.414214 1.259921
 3    9 1.732051 1.442250
 4   16 2.000000 1.587401
 5   25 2.236068 1.709976
 6   36 2.449490 1.817121
 7   49 2.645751 1.912931
 8   64 2.828427 2.000000
 9   81 3.000000 2.080084
10  100 3.162278 2.154435
11  121 3.316625 2.223980
12  144 3.464102 2.289428
13  169 3.605551 2.351335
14  196 3.741657 2.410142
15  225 3.872983 2.466212
16  256 4.000000 2.519842
Notice that the operand of the sqrt() library function was of type int, this did not cause any problems since the prototype for sqrt() specifies a parameter of type double and the compiler has simply included a type conversion in the code that generates the value of the parameter.


The string handling macros and functions