This chapter contains information about functions for doing basic arithmetic operations, such as splitting a float into its integer and fractional parts. These functions are declared in the header file `math.h'.
The IEEE floating point format used by most modern computers supports values that are "not a number". These values are called NaNs. "Not a number" values result from certain operations which have no meaningful numeric result, such as zero divided by zero or infinity divided by infinity.
One noteworthy property of NaNs is that they are not equal to
themselves. Thus, x == x
can be 0 if the value of x
is a
NaN. You can use this to test whether a value is a NaN or not: if it is
not equal to itself, then it is a NaN. But the recommended way to test
for a NaN is with the isnan
function (see section 14.2 Predicates on Floats).
Almost any arithmetic operation in which one argument is a NaN returns a NaN.
You can use `#ifdef NAN' to test whether the machine supports
NaNs. (Of course, you must arrange for GNU extensions to be visible,
such as by defining _GNU_SOURCE
, and then you must include
`math.h'.)
This section describes some miscellaneous test functions on doubles.
Prototypes for these functions appear in `math.h'. These are BSD
functions, and thus are available if you define _BSD_SOURCE
or
_GNU_SOURCE
.
-1
if x represents negative infinity,
1
if x represents positive infinity, and 0
otherwise.
x !=
x
to get the same result).
infnan
to decide what to return on
occasion of an error. Its argument is an error code, EDOM
or
ERANGE
; infnan
returns a suitable value to indicate this
with. -ERANGE
is also acceptable as an argument, and corresponds
to -HUGE_VAL
as a value.
In the BSD library, on certain machines, infnan
raises a fatal
signal in all cases. The GNU library does not do likewise, because that
does not fit the ISO C specification.
Portability Note: The functions listed in this section are BSD extensions.
These functions are provided for obtaining the absolute value (or
magnitude) of a number. The absolute value of a real number
x is x is x is positive, -x if x is
negative. For a complex number z, whose real part is x and
whose imaginary part is y, the absolute value is sqrt
(x*x + y*y)
.
Prototypes for abs
and labs
are in `stdlib.h';
fabs
and cabs
are declared in `math.h'.
Most computers use a two's complement integer representation, in which
the absolute value of INT_MIN
(the smallest possible int
)
cannot be represented; thus, abs (INT_MIN)
is not defined.
abs
, except that both the argument and result
are of type long int
rather than int
.
cabs
function returns the absolute value of the complex
number z, whose real part is z.real
and whose
imaginary part is z.imag
. (See also the function
hypot
in section 13.4 Exponentiation and Logarithms.) The value is:
sqrt (z.real*z.real + z.imag*z.imag)
The functions described in this section are primarily provided as a way to efficiently perform certain low-level manipulations on floating point numbers that are represented internally using a binary radix; see section 28.17.3.1 Floating Point Representation Concepts. These functions are required to have equivalent behavior even if the representation does not use a radix of 2, but of course they are unlikely to be particularly efficient in those cases.
All these functions are declared in `math.h'.
frexp
function is used to split the number value
into a normalized fraction and an exponent.
If the argument value is not zero, the return value is value
times a power of two, and is always in the range 1/2 (inclusive) to 1
(exclusive). The corresponding exponent is stored in
*exponent
; the return value multiplied by 2 raised to this
exponent equals the original number value.
For example, frexp (12.8, &exponent)
returns 0.8
and
stores 4
in exponent
.
If value is zero, then the return value is zero and
zero is stored in *exponent
.
frexp
.)
For example, ldexp (0.8, 4)
returns 12.8
.
The following functions which come from BSD provide facilities
equivalent to those of ldexp
and frexp
:
scalb
function is the BSD name for ldexp
.
double
. This is
the highest integer power of 2
contained in x. The sign of
x is ignored. For example, logb (3.5)
is 1.0
and
logb (4.0)
is 2.0
.
When 2
raised to this power is divided into x, it gives a
quotient between 1
(inclusive) and 2
(exclusive).
If x is zero, the value is minus infinity (if the machine supports such a value), or else a very small number. If x is infinity, the value is infinity.
The value returned by logb
is one less than the value that
frexp
would store into *exponent
.
copysign
function returns a value whose absolute value is the
same as that of value, and whose sign matches that of sign.
This is a BSD function.
The functions listed here perform operations such as rounding, truncation, and remainder in division of floating point numbers. Some of these functions convert floating point numbers to integer values. They are all declared in `math.h'.
You can also convert floating-point numbers to integers simply by
casting them to int
. This discards the fractional part,
effectively rounding towards zero. However, this only works if the
result can actually be represented as an int
---for very large
numbers, this is impossible. The functions listed here return the
result as a double
instead to get around this problem.
ceil
function rounds x upwards to the nearest integer,
returning that value as a double
. Thus, ceil (1.5)
is 2.0
.
ceil
function rounds x downwards to the nearest
integer, returning that value as a double
. Thus, floor
(1.5)
is 1.0
and floor (-1.5)
is -2.0
.
-1
and 1
, exclusive). Their sum
equals value. Each of the parts has the same sign as value,
so the rounding of the integer part is towards zero.
modf
stores the integer part in *integer-part
, and
returns the fractional part. For example, modf (2.5, &intpart)
returns 0.5
and stores 2.0
into intpart
.
numerator - n * denominator
, where n
is the quotient of numerator divided by denominator, rounded
towards zero to an integer. Thus, fmod (6.5, 2.3)
returns
1.9
, which is 6.5
minus 4.6
.
The result has the same sign as the numerator and has magnitude less than the magnitude of the denominator.
If denominator is zero, fmod
fails and sets errno
to
EDOM
.
drem
is like fmod
except that it rounds the
internal quotient n to the nearest integer instead of towards zero
to an integer. For example, drem (6.5, 2.3)
returns -0.4
,
which is 6.5
minus 6.9
.
The absolute value of the result is less than or equal to half the
absolute value of the denominator. The difference between
fmod (numerator, denominator)
and drem
(numerator, denominator)
is always either
denominator, minus denominator, or zero.
If denominator is zero, drem
fails and sets errno
to
EDOM
.
This section describes functions for performing integer division. These
functions are redundant in the GNU C library, since in GNU C the `/'
operator always rounds towards zero. But in other C implementations,
`/' may round differently with negative arguments. div
and
ldiv
are useful because they specify how to round the quotient:
towards zero. The remainder has the same sign as the numerator.
These functions are specified to return a result r such that the value
r.quot*denominator + r.rem
equals
numerator.
To use these facilities, you should include the header file `stdlib.h' in your program.
div
function. It has the following members:
int quot
int rem
div
computes the quotient and remainder from
the division of numerator by denominator, returning the
result in a structure of type div_t
.
If the result cannot be represented (as in a division by zero), the behavior is undefined.
Here is an example, albeit not a very useful one.
div_t result; result = div (20, -6);
Now result.quot
is -3
and result.rem
is 2
.
ldiv
function. It has the following members:
long int quot
long int rem
(This is identical to div_t
except that the components are of
type long int
rather than int
.)
ldiv
function is similar to div
, except that the
arguments are of type long int
and the result is returned as a
structure of type ldiv
.
This section describes functions for "reading" integer and
floating-point numbers from a string. It may be more convenient in some
cases to use sscanf
or one of the related functions; see
section 7.12 Formatted Input. But often you can make a program more robust by
finding the tokens in the string by hand, then converting the numbers
one by one.
These functions are declared in `stdlib.h'.
strtol
("string-to-long") function converts the initial
part of string to a signed integer, which is returned as a value
of type long int
.
This function attempts to decompose string as follows:
isspace
function
(see section 4.1 Classification of Characters). These are discarded.
2
and 35
.
If base is 16
, the digits may optionally be preceded by
`0x' or `0X'. If base has no legal value the value returned
is 0l
and the global variable errno
is set to EINVAL
.
strtol
stores a pointer to this tail in
*tailptr
.
If the string is empty, contains only whitespace, or does not contain an
initial substring that has the expected syntax for an integer in the
specified base, no conversion is performed. In this case,
strtol
returns a value of zero and the value stored in
*tailptr
is the value of string.
In a locale other than the standard "C"
locale, this function
may recognize additional implementation-dependent syntax.
If the string has valid syntax for an integer but the value is not
representable because of overflow, strtol
returns either
LONG_MAX
or LONG_MIN
(see section 28.17.2 Range of an Integer Type), as
appropriate for the sign of the value. It also sets errno
to ERANGE
to indicate there was overflow.
Because the value 0l
is a correct result for strtol
the
user who is interested in handling errors should set the global variable
errno
to 0
before calling this function, so that the program
can later test whether an error occurred.
There is an example at the end of this section.
strtoul
("string-to-unsigned-long") function is like
strtol
except it deals with unsigned numbers, and returns its
value with type unsigned long int
. No `+' or `-' sign
may appear before the number, but the syntax is otherwise the same as
described above for strtol
. The value returned in case of
overflow is ULONG_MAX
(see section 28.17.2 Range of an Integer Type).
Like strtol
this function sets errno
and returns the value
0ul
in case the value for base is not in the legal range.
For strtoul
this can happen in another situation. In case the
number to be converted is negative strtoul
also sets errno
to EINVAL
and returns 0ul
.
strtoq
("string-to-quad-word") function is like
strtol
except that is deals with extra long numbers and it
returns its value with type long long int
.
If the string has valid syntax for an integer but the value is not
representable because of overflow, strtoq
returns either
LONG_LONG_MAX
or LONG_LONG_MIN
(see section 28.17.2 Range of an Integer Type), as
appropriate for the sign of the value. It also sets errno
to
ERANGE
to indicate there was overflow.
strtoll
is only an commonly used other name for the strtoq
function. Everything said for strtoq
applies to strtoll
as well.
strtouq
("string-to-unsigned-quad-word") function is like
strtoul
except that is deals with extra long numbers and it
returns its value with type unsigned long long int
. The value
returned in case of overflow is ULONG_LONG_MAX
(see section 28.17.2 Range of an Integer Type).
strtoull
is only an commonly used other name for the strtouq
function. Everything said for strtouq
applies to strtoull
as well.
strtol
function with a base
argument of 10
, except that it need not detect overflow errors.
The atol
function is provided mostly for compatibility with
existing code; using strtol
is more robust.
atol
, except that it returns an int
value rather than long int
. The atoi
function is also
considered obsolete; use strtol
instead.
The POSIX locales contain some information about how to format numbers (see section 19.6.1 Generic Numeric Formatting Parameters). This mainly deals with representing numbers for better readability for humans. The functions present so far in this section cannot handle numbers in this form.
If this functionality is needed in a program one can use the functions
from the scanf
family which know about the flag `'' for
parsing numeric input (see section 7.12.4 Numeric Input Conversions). Sometimes it
is more desirable to have finer control.
In these situation one could use the function
__strtoXXX_internal
. XXX here stands for any of the
above forms. All numeric conversion functions (including the functions
to process floating-point numbers) have such a counterpart. The
difference to the normal form is the extra argument at the end of the
parameter list. If this value has an non-zero value the handling of
number grouping is enabled. The advantage of using these functions is
that the tailptr parameters allow to determine which part of the
input is processed. The scanf
functions don't provide this
information. The drawback of using these functions is that they are not
portable. They only exist in the GNU C library.
Here is a function which parses a string as a sequence of integers and returns the sum of them:
int sum_ints_from_string (char *string) { int sum = 0; while (1) { char *tail; int next; /* Skip whitespace by hand, to detect the end. */ while (isspace (*string)) string++; if (*string == 0) break; /* There is more nonwhitespace, */ /* so it ought to be another number. */ errno = 0; /* Parse it. */ next = strtol (string, &tail, 0); /* Add it in, if not overflow. */ if (errno) printf ("Overflow\n"); else sum += next; /* Advance past it. */ string = tail; } return sum; }
These functions are declared in `stdlib.h'.
strtod
("string-to-double") function converts the initial
part of string to a floating-point number, which is returned as a
value of type double
.
This function attempts to decompose string as follows:
isspace
function
(see section 4.1 Classification of Characters). These are discarded.
*tailptr
.
If the string is empty, contains only whitespace, or does not contain an
initial substring that has the expected syntax for a floating-point
number, no conversion is performed. In this case, strtod
returns
a value of zero and the value returned in *tailptr
is the
value of string.
In a locale other than the standard "C"
or "POSIX"
locales,
this function may recognize additional locale-dependent syntax.
If the string has valid syntax for a floating-point number but the value
is not representable because of overflow, strtod
returns either
positive or negative HUGE_VAL
(see section 13 Mathematics), depending on
the sign of the value. Similarly, if the value is not representable
because of underflow, strtod
returns zero. It also sets errno
to ERANGE
if there was overflow or underflow.
Since the value zero which is returned in the error case is also a valid
result the user should set the global variable errno
to zero
before calling this function. So one can test for failures after the
call since all failures set errno
to a non-zero value.
strtod
function but it returns a
float
value instead of a double
value. If the precision
of a float
value is sufficient this function should be used since
it is much faster than strtod
on some architectures. The reasons
are obvious: IEEE 754 defines float
to have a mantissa of 23
bits while double
has 53 bits and every additional bit of
precision can require additional computation.
If the string has valid syntax for a floating-point number but the value
is not representable because of overflow, strtof
returns either
positive or negative HUGE_VALf
(see section 13 Mathematics), depending on
the sign of the value.
This function is a GNU extension.
strtod
function but it returns a
long double
value instead of a double
value. It should be
used when high precision is needed. On systems which define a long
double
type (i.e., on which it is not the same as double
)
running this function might take significantly more time since more bits
of precision are required.
If the string has valid syntax for a floating-point number but the value
is not representable because of overflow, strtold
returns either
positive or negative HUGE_VALl
(see section 13 Mathematics), depending on
the sign of the value.
This function is a GNU extension.
As for the integer parsing functions there are additional functions which will handle numbers represented using the grouping scheme of the current locale (see section 14.7.1 Parsing of Integers).
strtod
function, except that it
need not detect overflow and underflow errors. The atof
function
is provided mostly for compatibility with existing code; using
strtod
is more robust.
Go to the first, previous, next, last section, table of contents.