Update.
[platform/upstream/glibc.git] / manual / arith.texi
1 @node Arithmetic, Date and Time, Mathematics, Top
2 @c %MENU% Low level arithmetic functions
3 @chapter Arithmetic Functions
4
5 This chapter contains information about functions for doing basic
6 arithmetic operations, such as splitting a float into its integer and
7 fractional parts or retrieving the imaginary part of a complex value.
8 These functions are declared in the header files @file{math.h} and
9 @file{complex.h}.
10
11 @menu
12 * Floating Point Numbers::      Basic concepts.  IEEE 754.
13 * Floating Point Classes::      The five kinds of floating-point number.
14 * Floating Point Errors::       When something goes wrong in a calculation.
15 * Rounding::                    Controlling how results are rounded.
16 * Control Functions::           Saving and restoring the FPU's state.
17 * Arithmetic Functions::        Fundamental operations provided by the library.
18 * Complex Numbers::             The types.  Writing complex constants.
19 * Operations on Complex::       Projection, conjugation, decomposition.
20 * Integer Division::            Integer division with guaranteed rounding.
21 * Parsing of Numbers::          Converting strings to numbers.
22 * System V Number Conversion::  An archaic way to convert numbers to strings.
23 @end menu
24
25 @node Floating Point Numbers
26 @section Floating Point Numbers
27 @cindex floating point
28 @cindex IEEE 754
29 @cindex IEEE floating point
30
31 Most computer hardware has support for two different kinds of numbers:
32 integers (@math{@dots{}-3, -2, -1, 0, 1, 2, 3@dots{}}) and
33 floating-point numbers.  Floating-point numbers have three parts: the
34 @dfn{mantissa}, the @dfn{exponent}, and the @dfn{sign bit}.  The real
35 number represented by a floating-point value is given by
36 @tex
37 $(s \mathrel? -1 \mathrel: 1) \cdot 2^e \cdot M$
38 @end tex
39 @ifnottex
40 @math{(s ? -1 : 1) @mul{} 2^e @mul{} M}
41 @end ifnottex
42 where @math{s} is the sign bit, @math{e} the exponent, and @math{M}
43 the mantissa.  @xref{Floating Point Concepts}, for details.  (It is
44 possible to have a different @dfn{base} for the exponent, but all modern
45 hardware uses @math{2}.)
46
47 Floating-point numbers can represent a finite subset of the real
48 numbers.  While this subset is large enough for most purposes, it is
49 important to remember that the only reals that can be represented
50 exactly are rational numbers that have a terminating binary expansion
51 shorter than the width of the mantissa.  Even simple fractions such as
52 @math{1/5} can only be approximated by floating point.
53
54 Mathematical operations and functions frequently need to produce values
55 that are not representable.  Often these values can be approximated
56 closely enough for practical purposes, but sometimes they can't.
57 Historically there was no way to tell when the results of a calculation
58 were inaccurate.  Modern computers implement the @w{IEEE 754} standard
59 for numerical computations, which defines a framework for indicating to
60 the program when the results of calculation are not trustworthy.  This
61 framework consists of a set of @dfn{exceptions} that indicate why a
62 result could not be represented, and the special values @dfn{infinity}
63 and @dfn{not a number} (NaN).
64
65 @node Floating Point Classes
66 @section Floating-Point Number Classification Functions
67 @cindex floating-point classes
68 @cindex classes, floating-point
69 @pindex math.h
70
71 @w{ISO C99} defines macros that let you determine what sort of
72 floating-point number a variable holds.
73
74 @comment math.h
75 @comment ISO
76 @deftypefn {Macro} int fpclassify (@emph{float-type} @var{x})
77 This is a generic macro which works on all floating-point types and
78 which returns a value of type @code{int}.  The possible values are:
79
80 @vtable @code
81 @item FP_NAN
82 The floating-point number @var{x} is ``Not a Number'' (@pxref{Infinity
83 and NaN})
84 @item FP_INFINITE
85 The value of @var{x} is either plus or minus infinity (@pxref{Infinity
86 and NaN})
87 @item FP_ZERO
88 The value of @var{x} is zero.  In floating-point formats like @w{IEEE
89 754}, where zero can be signed, this value is also returned if
90 @var{x} is negative zero.
91 @item FP_SUBNORMAL
92 Numbers whose absolute value is too small to be represented in the
93 normal format are represented in an alternate, @dfn{denormalized} format
94 (@pxref{Floating Point Concepts}).  This format is less precise but can
95 represent values closer to zero.  @code{fpclassify} returns this value
96 for values of @var{x} in this alternate format.
97 @item FP_NORMAL
98 This value is returned for all other values of @var{x}.  It indicates
99 that there is nothing special about the number.
100 @end vtable
101
102 @end deftypefn
103
104 @code{fpclassify} is most useful if more than one property of a number
105 must be tested.  There are more specific macros which only test one
106 property at a time.  Generally these macros execute faster than
107 @code{fpclassify}, since there is special hardware support for them.
108 You should therefore use the specific macros whenever possible.
109
110 @comment math.h
111 @comment ISO
112 @deftypefn {Macro} int isfinite (@emph{float-type} @var{x})
113 This macro returns a nonzero value if @var{x} is finite: not plus or
114 minus infinity, and not NaN.  It is equivalent to
115
116 @smallexample
117 (fpclassify (x) != FP_NAN && fpclassify (x) != FP_INFINITE)
118 @end smallexample
119
120 @code{isfinite} is implemented as a macro which accepts any
121 floating-point type.
122 @end deftypefn
123
124 @comment math.h
125 @comment ISO
126 @deftypefn {Macro} int isnormal (@emph{float-type} @var{x})
127 This macro returns a nonzero value if @var{x} is finite and normalized.
128 It is equivalent to
129
130 @smallexample
131 (fpclassify (x) == FP_NORMAL)
132 @end smallexample
133 @end deftypefn
134
135 @comment math.h
136 @comment ISO
137 @deftypefn {Macro} int isnan (@emph{float-type} @var{x})
138 This macro returns a nonzero value if @var{x} is NaN.  It is equivalent
139 to
140
141 @smallexample
142 (fpclassify (x) == FP_NAN)
143 @end smallexample
144 @end deftypefn
145
146 Another set of floating-point classification functions was provided by
147 BSD.  The GNU C library also supports these functions; however, we
148 recommend that you use the ISO C99 macros in new code.  Those are standard
149 and will be available more widely.  Also, since they are macros, you do
150 not have to worry about the type of their argument.
151
152 @comment math.h
153 @comment BSD
154 @deftypefun int isinf (double @var{x})
155 @comment math.h
156 @comment BSD
157 @deftypefunx int isinff (float @var{x})
158 @comment math.h
159 @comment BSD
160 @deftypefunx int isinfl (long double @var{x})
161 This function returns @code{-1} if @var{x} represents negative infinity,
162 @code{1} if @var{x} represents positive infinity, and @code{0} otherwise.
163 @end deftypefun
164
165 @comment math.h
166 @comment BSD
167 @deftypefun int isnan (double @var{x})
168 @comment math.h
169 @comment BSD
170 @deftypefunx int isnanf (float @var{x})
171 @comment math.h
172 @comment BSD
173 @deftypefunx int isnanl (long double @var{x})
174 This function returns a nonzero value if @var{x} is a ``not a number''
175 value, and zero otherwise.
176
177 @strong{Note:} The @code{isnan} macro defined by @w{ISO C99} overrides
178 the BSD function.  This is normally not a problem, because the two
179 routines behave identically.  However, if you really need to get the BSD
180 function for some reason, you can write
181
182 @smallexample
183 (isnan) (x)
184 @end smallexample
185 @end deftypefun
186
187 @comment math.h
188 @comment BSD
189 @deftypefun int finite (double @var{x})
190 @comment math.h
191 @comment BSD
192 @deftypefunx int finitef (float @var{x})
193 @comment math.h
194 @comment BSD
195 @deftypefunx int finitel (long double @var{x})
196 This function returns a nonzero value if @var{x} is finite or a ``not a
197 number'' value, and zero otherwise.
198 @end deftypefun
199
200 @comment math.h
201 @comment BSD
202 @deftypefun double infnan (int @var{error})
203 This function is provided for compatibility with BSD.  Its argument is
204 an error code, @code{EDOM} or @code{ERANGE}; @code{infnan} returns the
205 value that a math function would return if it set @code{errno} to that
206 value.  @xref{Math Error Reporting}.  @code{-ERANGE} is also acceptable
207 as an argument, and corresponds to @code{-HUGE_VAL} as a value.
208
209 In the BSD library, on certain machines, @code{infnan} raises a fatal
210 signal in all cases.  The GNU library does not do likewise, because that
211 does not fit the @w{ISO C} specification.
212 @end deftypefun
213
214 @strong{Portability Note:} The functions listed in this section are BSD
215 extensions.
216
217
218 @node Floating Point Errors
219 @section Errors in Floating-Point Calculations
220
221 @menu
222 * FP Exceptions::               IEEE 754 math exceptions and how to detect them.
223 * Infinity and NaN::            Special values returned by calculations.
224 * Status bit operations::       Checking for exceptions after the fact.
225 * Math Error Reporting::        How the math functions report errors.
226 @end menu
227
228 @node FP Exceptions
229 @subsection FP Exceptions
230 @cindex exception
231 @cindex signal
232 @cindex zero divide
233 @cindex division by zero
234 @cindex inexact exception
235 @cindex invalid exception
236 @cindex overflow exception
237 @cindex underflow exception
238
239 The @w{IEEE 754} standard defines five @dfn{exceptions} that can occur
240 during a calculation.  Each corresponds to a particular sort of error,
241 such as overflow.
242
243 When exceptions occur (when exceptions are @dfn{raised}, in the language
244 of the standard), one of two things can happen.  By default the
245 exception is simply noted in the floating-point @dfn{status word}, and
246 the program continues as if nothing had happened.  The operation
247 produces a default value, which depends on the exception (see the table
248 below).  Your program can check the status word to find out which
249 exceptions happened.
250
251 Alternatively, you can enable @dfn{traps} for exceptions.  In that case,
252 when an exception is raised, your program will receive the @code{SIGFPE}
253 signal.  The default action for this signal is to terminate the
254 program.  @xref{Signal Handling}, for how you can change the effect of
255 the signal.
256
257 @findex matherr
258 In the System V math library, the user-defined function @code{matherr}
259 is called when certain exceptions occur inside math library functions.
260 However, the Unix98 standard deprecates this interface.  We support it
261 for historical compatibility, but recommend that you do not use it in
262 new programs.
263
264 @noindent
265 The exceptions defined in @w{IEEE 754} are:
266
267 @table @samp
268 @item Invalid Operation
269 This exception is raised if the given operands are invalid for the
270 operation to be performed.  Examples are
271 (see @w{IEEE 754}, @w{section 7}):
272 @enumerate
273 @item
274 Addition or subtraction: @math{@infinity{} - @infinity{}}.  (But
275 @math{@infinity{} + @infinity{} = @infinity{}}).
276 @item
277 Multiplication: @math{0 @mul{} @infinity{}}.
278 @item
279 Division: @math{0/0} or @math{@infinity{}/@infinity{}}.
280 @item
281 Remainder: @math{x} REM @math{y}, where @math{y} is zero or @math{x} is
282 infinite.
283 @item
284 Square root if the operand is less then zero.  More generally, any
285 mathematical function evaluated outside its domain produces this
286 exception.
287 @item
288 Conversion of a floating-point number to an integer or decimal
289 string, when the number cannot be represented in the target format (due
290 to overflow, infinity, or NaN).
291 @item
292 Conversion of an unrecognizable input string.
293 @item
294 Comparison via predicates involving @math{<} or @math{>}, when one or
295 other of the operands is NaN.  You can prevent this exception by using
296 the unordered comparison functions instead; see @ref{FP Comparison Functions}.
297 @end enumerate
298
299 If the exception does not trap, the result of the operation is NaN.
300
301 @item Division by Zero
302 This exception is raised when a finite nonzero number is divided
303 by zero.  If no trap occurs the result is either @math{+@infinity{}} or
304 @math{-@infinity{}}, depending on the signs of the operands.
305
306 @item Overflow
307 This exception is raised whenever the result cannot be represented
308 as a finite value in the precision format of the destination.  If no trap
309 occurs the result depends on the sign of the intermediate result and the
310 current rounding mode (@w{IEEE 754}, @w{section 7.3}):
311 @enumerate
312 @item
313 Round to nearest carries all overflows to @math{@infinity{}}
314 with the sign of the intermediate result.
315 @item
316 Round toward @math{0} carries all overflows to the largest representable
317 finite number with the sign of the intermediate result.
318 @item
319 Round toward @math{-@infinity{}} carries positive overflows to the
320 largest representable finite number and negative overflows to
321 @math{-@infinity{}}.
322
323 @item
324 Round toward @math{@infinity{}} carries negative overflows to the
325 most negative representable finite number and positive overflows
326 to @math{@infinity{}}.
327 @end enumerate
328
329 Whenever the overflow exception is raised, the inexact exception is also
330 raised.
331
332 @item Underflow
333 The underflow exception is raised when an intermediate result is too
334 small to be calculated accurately, or if the operation's result rounded
335 to the destination precision is too small to be normalized.
336
337 When no trap is installed for the underflow exception, underflow is
338 signaled (via the underflow flag) only when both tininess and loss of
339 accuracy have been detected.  If no trap handler is installed the
340 operation continues with an imprecise small value, or zero if the
341 destination precision cannot hold the small exact result.
342
343 @item Inexact
344 This exception is signalled if a rounded result is not exact (such as
345 when calculating the square root of two) or a result overflows without
346 an overflow trap.
347 @end table
348
349 @node Infinity and NaN
350 @subsection Infinity and NaN
351 @cindex infinity
352 @cindex not a number
353 @cindex NaN
354
355 @w{IEEE 754} floating point numbers can represent positive or negative
356 infinity, and @dfn{NaN} (not a number).  These three values arise from
357 calculations whose result is undefined or cannot be represented
358 accurately.  You can also deliberately set a floating-point variable to
359 any of them, which is sometimes useful.  Some examples of calculations
360 that produce infinity or NaN:
361
362 @ifnottex
363 @smallexample
364 @math{1/0 = @infinity{}}
365 @math{log (0) = -@infinity{}}
366 @math{sqrt (-1) = NaN}
367 @end smallexample
368 @end ifnottex
369 @tex
370 $${1\over0} = \infty$$
371 $$\log 0 = -\infty$$
372 $$\sqrt{-1} = \hbox{NaN}$$
373 @end tex
374
375 When a calculation produces any of these values, an exception also
376 occurs; see @ref{FP Exceptions}.
377
378 The basic operations and math functions all accept infinity and NaN and
379 produce sensible output.  Infinities propagate through calculations as
380 one would expect: for example, @math{2 + @infinity{} = @infinity{}},
381 @math{4/@infinity{} = 0}, atan @math{(@infinity{}) = @pi{}/2}.  NaN, on
382 the other hand, infects any calculation that involves it.  Unless the
383 calculation would produce the same result no matter what real value
384 replaced NaN, the result is NaN.
385
386 In comparison operations, positive infinity is larger than all values
387 except itself and NaN, and negative infinity is smaller than all values
388 except itself and NaN.  NaN is @dfn{unordered}: it is not equal to,
389 greater than, or less than anything, @emph{including itself}. @code{x ==
390 x} is false if the value of @code{x} is NaN.  You can use this to test
391 whether a value is NaN or not, but the recommended way to test for NaN
392 is with the @code{isnan} function (@pxref{Floating Point Classes}).  In
393 addition, @code{<}, @code{>}, @code{<=}, and @code{>=} will raise an
394 exception when applied to NaNs.
395
396 @file{math.h} defines macros that allow you to explicitly set a variable
397 to infinity or NaN.
398
399 @comment math.h
400 @comment ISO
401 @deftypevr Macro float INFINITY
402 An expression representing positive infinity.  It is equal to the value
403 produced  by mathematical operations like @code{1.0 / 0.0}.
404 @code{-INFINITY} represents negative infinity.
405
406 You can test whether a floating-point value is infinite by comparing it
407 to this macro.  However, this is not recommended; you should use the
408 @code{isfinite} macro instead.  @xref{Floating Point Classes}.
409
410 This macro was introduced in the @w{ISO C99} standard.
411 @end deftypevr
412
413 @comment math.h
414 @comment GNU
415 @deftypevr Macro float NAN
416 An expression representing a value which is ``not a number''.  This
417 macro is a GNU extension, available only on machines that support the
418 ``not a number'' value---that is to say, on all machines that support
419 IEEE floating point.
420
421 You can use @samp{#ifdef NAN} to test whether the machine supports
422 NaN.  (Of course, you must arrange for GNU extensions to be visible,
423 such as by defining @code{_GNU_SOURCE}, and then you must include
424 @file{math.h}.)
425 @end deftypevr
426
427 @w{IEEE 754} also allows for another unusual value: negative zero.  This
428 value is produced when you divide a positive number by negative
429 infinity, or when a negative result is smaller than the limits of
430 representation.  Negative zero behaves identically to zero in all
431 calculations, unless you explicitly test the sign bit with
432 @code{signbit} or @code{copysign}.
433
434 @node Status bit operations
435 @subsection Examining the FPU status word
436
437 @w{ISO C99} defines functions to query and manipulate the
438 floating-point status word.  You can use these functions to check for
439 untrapped exceptions when it's convenient, rather than worrying about
440 them in the middle of a calculation.
441
442 These constants represent the various @w{IEEE 754} exceptions.  Not all
443 FPUs report all the different exceptions.  Each constant is defined if
444 and only if the FPU you are compiling for supports that exception, so
445 you can test for FPU support with @samp{#ifdef}.  They are defined in
446 @file{fenv.h}.
447
448 @vtable @code
449 @comment fenv.h
450 @comment ISO
451 @item FE_INEXACT
452  The inexact exception.
453 @comment fenv.h
454 @comment ISO
455 @item FE_DIVBYZERO
456  The divide by zero exception.
457 @comment fenv.h
458 @comment ISO
459 @item FE_UNDERFLOW
460  The underflow exception.
461 @comment fenv.h
462 @comment ISO
463 @item FE_OVERFLOW
464  The overflow exception.
465 @comment fenv.h
466 @comment ISO
467 @item FE_INVALID
468  The invalid exception.
469 @end vtable
470
471 The macro @code{FE_ALL_EXCEPT} is the bitwise OR of all exception macros
472 which are supported by the FP implementation.
473
474 These functions allow you to clear exception flags, test for exceptions,
475 and save and restore the set of exceptions flagged.
476
477 @comment fenv.h
478 @comment ISO
479 @deftypefun int feclearexcept (int @var{excepts})
480 This function clears all of the supported exception flags indicated by
481 @var{excepts}.
482
483 The function returns zero in case the operation was successful, a
484 non-zero value otherwise.
485 @end deftypefun
486
487 @comment fenv.h
488 @comment ISO
489 @deftypefun int feraiseexcept (int @var{excepts})
490 This function raises the supported exceptions indicated by
491 @var{excepts}.  If more than one exception bit in @var{excepts} is set
492 the order in which the exceptions are raised is undefined except that
493 overflow (@code{FE_OVERFLOW}) or underflow (@code{FE_UNDERFLOW}) are
494 raised before inexact (@code{FE_INEXACT}).  Whether for overflow or
495 underflow the inexact exception is also raised is also implementation
496 dependent.
497
498 The function returns zero in case the operation was successful, a
499 non-zero value otherwise.
500 @end deftypefun
501
502 @comment fenv.h
503 @comment ISO
504 @deftypefun int fetestexcept (int @var{excepts})
505 Test whether the exception flags indicated by the parameter @var{except}
506 are currently set.  If any of them are, a nonzero value is returned
507 which specifies which exceptions are set.  Otherwise the result is zero.
508 @end deftypefun
509
510 To understand these functions, imagine that the status word is an
511 integer variable named @var{status}.  @code{feclearexcept} is then
512 equivalent to @samp{status &= ~excepts} and @code{fetestexcept} is
513 equivalent to @samp{(status & excepts)}.  The actual implementation may
514 be very different, of course.
515
516 Exception flags are only cleared when the program explicitly requests it,
517 by calling @code{feclearexcept}.  If you want to check for exceptions
518 from a set of calculations, you should clear all the flags first.  Here
519 is a simple example of the way to use @code{fetestexcept}:
520
521 @smallexample
522 @{
523   double f;
524   int raised;
525   feclearexcept (FE_ALL_EXCEPT);
526   f = compute ();
527   raised = fetestexcept (FE_OVERFLOW | FE_INVALID);
528   if (raised & FE_OVERFLOW) @{ /* ... */ @}
529   if (raised & FE_INVALID) @{ /* ... */ @}
530   /* ... */
531 @}
532 @end smallexample
533
534 You cannot explicitly set bits in the status word.  You can, however,
535 save the entire status word and restore it later.  This is done with the
536 following functions:
537
538 @comment fenv.h
539 @comment ISO
540 @deftypefun int fegetexceptflag (fexcept_t *@var{flagp}, int @var{excepts})
541 This function stores in the variable pointed to by @var{flagp} an
542 implementation-defined value representing the current setting of the
543 exception flags indicated by @var{excepts}.
544
545 The function returns zero in case the operation was successful, a
546 non-zero value otherwise.
547 @end deftypefun
548
549 @comment fenv.h
550 @comment ISO
551 @deftypefun int fesetexceptflag (const fexcept_t *@var{flagp}, int
552 @var{excepts})
553 This function restores the flags for the exceptions indicated by
554 @var{excepts} to the values stored in the variable pointed to by
555 @var{flagp}.
556
557 The function returns zero in case the operation was successful, a
558 non-zero value otherwise.
559 @end deftypefun
560
561 Note that the value stored in @code{fexcept_t} bears no resemblance to
562 the bit mask returned by @code{fetestexcept}.  The type may not even be
563 an integer.  Do not attempt to modify an @code{fexcept_t} variable.
564
565 @node Math Error Reporting
566 @subsection Error Reporting by Mathematical Functions
567 @cindex errors, mathematical
568 @cindex domain error
569 @cindex range error
570
571 Many of the math functions are defined only over a subset of the real or
572 complex numbers.  Even if they are mathematically defined, their result
573 may be larger or smaller than the range representable by their return
574 type.  These are known as @dfn{domain errors}, @dfn{overflows}, and
575 @dfn{underflows}, respectively.  Math functions do several things when
576 one of these errors occurs.  In this manual we will refer to the
577 complete response as @dfn{signalling} a domain error, overflow, or
578 underflow.
579
580 When a math function suffers a domain error, it raises the invalid
581 exception and returns NaN.  It also sets @var{errno} to @code{EDOM};
582 this is for compatibility with old systems that do not support @w{IEEE
583 754} exception handling.  Likewise, when overflow occurs, math
584 functions raise the overflow exception and return @math{@infinity{}} or
585 @math{-@infinity{}} as appropriate.  They also set @var{errno} to
586 @code{ERANGE}.  When underflow occurs, the underflow exception is
587 raised, and zero (appropriately signed) is returned.  @var{errno} may be
588 set to @code{ERANGE}, but this is not guaranteed.
589
590 Some of the math functions are defined mathematically to result in a
591 complex value over parts of their domains.  The most familiar example of
592 this is taking the square root of a negative number.  The complex math
593 functions, such as @code{csqrt}, will return the appropriate complex value
594 in this case.  The real-valued functions, such as @code{sqrt}, will
595 signal a domain error.
596
597 Some older hardware does not support infinities.  On that hardware,
598 overflows instead return a particular very large number (usually the
599 largest representable number).  @file{math.h} defines macros you can use
600 to test for overflow on both old and new hardware.
601
602 @comment math.h
603 @comment ISO
604 @deftypevr Macro double HUGE_VAL
605 @comment math.h
606 @comment ISO
607 @deftypevrx Macro float HUGE_VALF
608 @comment math.h
609 @comment ISO
610 @deftypevrx Macro {long double} HUGE_VALL
611 An expression representing a particular very large number.  On machines
612 that use @w{IEEE 754} floating point format, @code{HUGE_VAL} is infinity.
613 On other machines, it's typically the largest positive number that can
614 be represented.
615
616 Mathematical functions return the appropriately typed version of
617 @code{HUGE_VAL} or @code{@minus{}HUGE_VAL} when the result is too large
618 to be represented.
619 @end deftypevr
620
621 @node Rounding
622 @section Rounding Modes
623
624 Floating-point calculations are carried out internally with extra
625 precision, and then rounded to fit into the destination type.  This
626 ensures that results are as precise as the input data.  @w{IEEE 754}
627 defines four possible rounding modes:
628
629 @table @asis
630 @item Round to nearest.
631 This is the default mode.  It should be used unless there is a specific
632 need for one of the others.  In this mode results are rounded to the
633 nearest representable value.  If the result is midway between two
634 representable values, the even representable is chosen. @dfn{Even} here
635 means the lowest-order bit is zero.  This rounding mode prevents
636 statistical bias and guarantees numeric stability: round-off errors in a
637 lengthy calculation will remain smaller than half of @code{FLT_EPSILON}.
638
639 @c @item Round toward @math{+@infinity{}}
640 @item Round toward plus Infinity.
641 All results are rounded to the smallest representable value
642 which is greater than the result.
643
644 @c @item Round toward @math{-@infinity{}}
645 @item Round toward minus Infinity.
646 All results are rounded to the largest representable value which is less
647 than the result.
648
649 @item Round toward zero.
650 All results are rounded to the largest representable value whose
651 magnitude is less than that of the result.  In other words, if the
652 result is negative it is rounded up; if it is positive, it is rounded
653 down.
654 @end table
655
656 @noindent
657 @file{fenv.h} defines constants which you can use to refer to the
658 various rounding modes.  Each one will be defined if and only if the FPU
659 supports the corresponding rounding mode.
660
661 @table @code
662 @comment fenv.h
663 @comment ISO
664 @vindex FE_TONEAREST
665 @item FE_TONEAREST
666 Round to nearest.
667
668 @comment fenv.h
669 @comment ISO
670 @vindex FE_UPWARD
671 @item FE_UPWARD
672 Round toward @math{+@infinity{}}.
673
674 @comment fenv.h
675 @comment ISO
676 @vindex FE_DOWNWARD
677 @item FE_DOWNWARD
678 Round toward @math{-@infinity{}}.
679
680 @comment fenv.h
681 @comment ISO
682 @vindex FE_TOWARDZERO
683 @item FE_TOWARDZERO
684 Round toward zero.
685 @end table
686
687 Underflow is an unusual case.  Normally, @w{IEEE 754} floating point
688 numbers are always normalized (@pxref{Floating Point Concepts}).
689 Numbers smaller than @math{2^r} (where @math{r} is the minimum exponent,
690 @code{FLT_MIN_RADIX-1} for @var{float}) cannot be represented as
691 normalized numbers.  Rounding all such numbers to zero or @math{2^r}
692 would cause some algorithms to fail at 0.  Therefore, they are left in
693 denormalized form.  That produces loss of precision, since some bits of
694 the mantissa are stolen to indicate the decimal point.
695
696 If a result is too small to be represented as a denormalized number, it
697 is rounded to zero.  However, the sign of the result is preserved; if
698 the calculation was negative, the result is @dfn{negative zero}.
699 Negative zero can also result from some operations on infinity, such as
700 @math{4/-@infinity{}}.  Negative zero behaves identically to zero except
701 when the @code{copysign} or @code{signbit} functions are used to check
702 the sign bit directly.
703
704 At any time one of the above four rounding modes is selected.  You can
705 find out which one with this function:
706
707 @comment fenv.h
708 @comment ISO
709 @deftypefun int fegetround (void)
710 Returns the currently selected rounding mode, represented by one of the
711 values of the defined rounding mode macros.
712 @end deftypefun
713
714 @noindent
715 To change the rounding mode, use this function:
716
717 @comment fenv.h
718 @comment ISO
719 @deftypefun int fesetround (int @var{round})
720 Changes the currently selected rounding mode to @var{round}.  If
721 @var{round} does not correspond to one of the supported rounding modes
722 nothing is changed.  @code{fesetround} returns a nonzero value if it
723 changed the rounding mode, zero if the mode is not supported.
724 @end deftypefun
725
726 You should avoid changing the rounding mode if possible.  It can be an
727 expensive operation; also, some hardware requires you to compile your
728 program differently for it to work.  The resulting code may run slower.
729 See your compiler documentation for details.
730 @c This section used to claim that functions existed to round one number
731 @c in a specific fashion.  I can't find any functions in the library
732 @c that do that. -zw
733
734 @node Control Functions
735 @section Floating-Point Control Functions
736
737 @w{IEEE 754} floating-point implementations allow the programmer to
738 decide whether traps will occur for each of the exceptions, by setting
739 bits in the @dfn{control word}.  In C, traps result in the program
740 receiving the @code{SIGFPE} signal; see @ref{Signal Handling}.
741
742 @strong{Note:} @w{IEEE 754} says that trap handlers are given details of
743 the exceptional situation, and can set the result value.  C signals do
744 not provide any mechanism to pass this information back and forth.
745 Trapping exceptions in C is therefore not very useful.
746
747 It is sometimes necessary to save the state of the floating-point unit
748 while you perform some calculation.  The library provides functions
749 which save and restore the exception flags, the set of exceptions that
750 generate traps, and the rounding mode.  This information is known as the
751 @dfn{floating-point environment}.
752
753 The functions to save and restore the floating-point environment all use
754 a variable of type @code{fenv_t} to store information.  This type is
755 defined in @file{fenv.h}.  Its size and contents are
756 implementation-defined.  You should not attempt to manipulate a variable
757 of this type directly.
758
759 To save the state of the FPU, use one of these functions:
760
761 @comment fenv.h
762 @comment ISO
763 @deftypefun int fegetenv (fenv_t *@var{envp})
764 Store the floating-point environment in the variable pointed to by
765 @var{envp}.
766
767 The function returns zero in case the operation was successful, a
768 non-zero value otherwise.
769 @end deftypefun
770
771 @comment fenv.h
772 @comment ISO
773 @deftypefun int feholdexcept (fenv_t *@var{envp})
774 Store the current floating-point environment in the object pointed to by
775 @var{envp}.  Then clear all exception flags, and set the FPU to trap no
776 exceptions.  Not all FPUs support trapping no exceptions; if
777 @code{feholdexcept} cannot set this mode, it returns zero.  If it
778 succeeds, it returns a nonzero value.
779 @end deftypefun
780
781 The functions which restore the floating-point environment can take two
782 kinds of arguments:
783
784 @itemize @bullet
785 @item
786 Pointers to @code{fenv_t} objects, which were initialized previously by a
787 call to @code{fegetenv} or @code{feholdexcept}.
788 @item
789 @vindex FE_DFL_ENV
790 The special macro @code{FE_DFL_ENV} which represents the floating-point
791 environment as it was available at program start.
792 @item
793 Implementation defined macros with names starting with @code{FE_}.
794
795 @vindex FE_NOMASK_ENV
796 If possible, the GNU C Library defines a macro @code{FE_NOMASK_ENV}
797 which represents an environment where every exception raised causes a
798 trap to occur.  You can test for this macro using @code{#ifdef}.  It is
799 only defined if @code{_GNU_SOURCE} is defined.
800
801 Some platforms might define other predefined environments.
802 @end itemize
803
804 @noindent
805 To set the floating-point environment, you can use either of these
806 functions:
807
808 @comment fenv.h
809 @comment ISO
810 @deftypefun int fesetenv (const fenv_t *@var{envp})
811 Set the floating-point environment to that described by @var{envp}.
812
813 The function returns zero in case the operation was successful, a
814 non-zero value otherwise.
815 @end deftypefun
816
817 @comment fenv.h
818 @comment ISO
819 @deftypefun int feupdateenv (const fenv_t *@var{envp})
820 Like @code{fesetenv}, this function sets the floating-point environment
821 to that described by @var{envp}.  However, if any exceptions were
822 flagged in the status word before @code{feupdateenv} was called, they
823 remain flagged after the call.  In other words, after @code{feupdateenv}
824 is called, the status word is the bitwise OR of the previous status word
825 and the one saved in @var{envp}.
826
827 The function returns zero in case the operation was successful, a
828 non-zero value otherwise.
829 @end deftypefun
830
831 @noindent
832 To control for individual exceptions if raising them causes a trap to
833 occur, you can use the following two functions.
834
835 @strong{Portability Note:} These functions are all GNU extensions.
836
837 @comment fenv.h
838 @comment GNU
839 @deftypefun int feenableexcept (int @var{excepts})
840 This functions enables traps for each of the exceptions as indicated by
841 the parameter @var{except}.  The individual excepetions are described in
842 @ref{Examining the FPU status word}.  Only the specified exceptions are
843 enabled, the status of the other exceptions is not changed.
844
845 The function returns the previous enabled exceptions in case the
846 operation was successful, @code{-1} otherwise.
847 @end deftypefun
848
849 @comment fenv.h
850 @comment GNU
851 @deftypefun int fedisableexcept (int @var{excepts})
852 This functions disables traps for each of the exceptions as indicated by
853 the parameter @var{except}.  The individual excepetions are described in
854 @ref{Examining the FPU status word}.  Only the specified exceptions are
855 disabled, the status of the other exceptions is not changed.
856
857 The function returns the previous enabled exceptions in case the
858 operation was successful, @code{-1} otherwise.
859 @end deftypefun
860
861 @comment fenv.h
862 @comment GNU
863 @deftypefun int fegetexcept (int @var{excepts})
864 The function returns a bitmask of all currently enabled exceptions.  It
865 returns @code{-1} in case of failure.
866
867 @node Arithmetic Functions
868 @section Arithmetic Functions
869
870 The C library provides functions to do basic operations on
871 floating-point numbers.  These include absolute value, maximum and minimum,
872 normalization, bit twiddling, rounding, and a few others.
873
874 @menu
875 * Absolute Value::              Absolute values of integers and floats.
876 * Normalization Functions::     Extracting exponents and putting them back.
877 * Rounding Functions::          Rounding floats to integers.
878 * Remainder Functions::         Remainders on division, precisely defined.
879 * FP Bit Twiddling::            Sign bit adjustment.  Adding epsilon.
880 * FP Comparison Functions::     Comparisons without risk of exceptions.
881 * Misc FP Arithmetic::          Max, min, positive difference, multiply-add.
882 @end menu
883
884 @node Absolute Value
885 @subsection Absolute Value
886 @cindex absolute value functions
887
888 These functions are provided for obtaining the @dfn{absolute value} (or
889 @dfn{magnitude}) of a number.  The absolute value of a real number
890 @var{x} is @var{x} if @var{x} is positive, @minus{}@var{x} if @var{x} is
891 negative.  For a complex number @var{z}, whose real part is @var{x} and
892 whose imaginary part is @var{y}, the absolute value is @w{@code{sqrt
893 (@var{x}*@var{x} + @var{y}*@var{y})}}.
894
895 @pindex math.h
896 @pindex stdlib.h
897 Prototypes for @code{abs}, @code{labs} and @code{llabs} are in @file{stdlib.h};
898 @code{imaxabs} is declared in @file{inttypes.h};
899 @code{fabs}, @code{fabsf} and @code{fabsl} are declared in @file{math.h}.
900 @code{cabs}, @code{cabsf} and @code{cabsl} are declared in @file{complex.h}.
901
902 @comment stdlib.h
903 @comment ISO
904 @deftypefun int abs (int @var{number})
905 @comment stdlib.h
906 @comment ISO
907 @deftypefunx {long int} labs (long int @var{number})
908 @comment stdlib.h
909 @comment ISO
910 @deftypefunx {long long int} llabs (long long int @var{number})
911 @comment inttypes.h
912 @comment ISO
913 @deftypefunx intmax_t imaxabs (intmax_t @var{number})
914 These functions return the absolute value of @var{number}.
915
916 Most computers use a two's complement integer representation, in which
917 the absolute value of @code{INT_MIN} (the smallest possible @code{int})
918 cannot be represented; thus, @w{@code{abs (INT_MIN)}} is not defined.
919
920 @code{llabs} and @code{imaxdiv} are new to @w{ISO C99}.
921 @end deftypefun
922
923 @comment math.h
924 @comment ISO
925 @deftypefun double fabs (double @var{number})
926 @comment math.h
927 @comment ISO
928 @deftypefunx float fabsf (float @var{number})
929 @comment math.h
930 @comment ISO
931 @deftypefunx {long double} fabsl (long double @var{number})
932 This function returns the absolute value of the floating-point number
933 @var{number}.
934 @end deftypefun
935
936 @comment complex.h
937 @comment ISO
938 @deftypefun double cabs (complex double @var{z})
939 @comment complex.h
940 @comment ISO
941 @deftypefunx float cabsf (complex float @var{z})
942 @comment complex.h
943 @comment ISO
944 @deftypefunx {long double} cabsl (complex long double @var{z})
945 These functions return the absolute  value of the complex number @var{z}
946 (@pxref{Complex Numbers}).  The absolute value of a complex number is:
947
948 @smallexample
949 sqrt (creal (@var{z}) * creal (@var{z}) + cimag (@var{z}) * cimag (@var{z}))
950 @end smallexample
951
952 This function should always be used instead of the direct formula
953 because it takes special care to avoid losing precision.  It may also
954 take advantage of hardware support for this operation. See @code{hypot}
955 in @ref{Exponents and Logarithms}.
956 @end deftypefun
957
958 @node Normalization Functions
959 @subsection Normalization Functions
960 @cindex normalization functions (floating-point)
961
962 The functions described in this section are primarily provided as a way
963 to efficiently perform certain low-level manipulations on floating point
964 numbers that are represented internally using a binary radix;
965 see @ref{Floating Point Concepts}.  These functions are required to
966 have equivalent behavior even if the representation does not use a radix
967 of 2, but of course they are unlikely to be particularly efficient in
968 those cases.
969
970 @pindex math.h
971 All these functions are declared in @file{math.h}.
972
973 @comment math.h
974 @comment ISO
975 @deftypefun double frexp (double @var{value}, int *@var{exponent})
976 @comment math.h
977 @comment ISO
978 @deftypefunx float frexpf (float @var{value}, int *@var{exponent})
979 @comment math.h
980 @comment ISO
981 @deftypefunx {long double} frexpl (long double @var{value}, int *@var{exponent})
982 These functions are used to split the number @var{value}
983 into a normalized fraction and an exponent.
984
985 If the argument @var{value} is not zero, the return value is @var{value}
986 times a power of two, and is always in the range 1/2 (inclusive) to 1
987 (exclusive).  The corresponding exponent is stored in
988 @code{*@var{exponent}}; the return value multiplied by 2 raised to this
989 exponent equals the original number @var{value}.
990
991 For example, @code{frexp (12.8, &exponent)} returns @code{0.8} and
992 stores @code{4} in @code{exponent}.
993
994 If @var{value} is zero, then the return value is zero and
995 zero is stored in @code{*@var{exponent}}.
996 @end deftypefun
997
998 @comment math.h
999 @comment ISO
1000 @deftypefun double ldexp (double @var{value}, int @var{exponent})
1001 @comment math.h
1002 @comment ISO
1003 @deftypefunx float ldexpf (float @var{value}, int @var{exponent})
1004 @comment math.h
1005 @comment ISO
1006 @deftypefunx {long double} ldexpl (long double @var{value}, int @var{exponent})
1007 These functions return the result of multiplying the floating-point
1008 number @var{value} by 2 raised to the power @var{exponent}.  (It can
1009 be used to reassemble floating-point numbers that were taken apart
1010 by @code{frexp}.)
1011
1012 For example, @code{ldexp (0.8, 4)} returns @code{12.8}.
1013 @end deftypefun
1014
1015 The following functions, which come from BSD, provide facilities
1016 equivalent to those of @code{ldexp} and @code{frexp}.
1017
1018 @comment math.h
1019 @comment BSD
1020 @deftypefun double logb (double @var{x})
1021 @comment math.h
1022 @comment BSD
1023 @deftypefunx float logbf (float @var{x})
1024 @comment math.h
1025 @comment BSD
1026 @deftypefunx {long double} logbl (long double @var{x})
1027 These functions return the integer part of the base-2 logarithm of
1028 @var{x}, an integer value represented in type @code{double}.  This is
1029 the highest integer power of @code{2} contained in @var{x}.  The sign of
1030 @var{x} is ignored.  For example, @code{logb (3.5)} is @code{1.0} and
1031 @code{logb (4.0)} is @code{2.0}.
1032
1033 When @code{2} raised to this power is divided into @var{x}, it gives a
1034 quotient between @code{1} (inclusive) and @code{2} (exclusive).
1035
1036 If @var{x} is zero, the return value is minus infinity if the machine
1037 supports infinities, and a very small number if it does not.  If @var{x}
1038 is infinity, the return value is infinity.
1039
1040 For finite @var{x}, the value returned by @code{logb} is one less than
1041 the value that @code{frexp} would store into @code{*@var{exponent}}.
1042 @end deftypefun
1043
1044 @comment math.h
1045 @comment BSD
1046 @deftypefun double scalb (double @var{value}, int @var{exponent})
1047 @comment math.h
1048 @comment BSD
1049 @deftypefunx float scalbf (float @var{value}, int @var{exponent})
1050 @comment math.h
1051 @comment BSD
1052 @deftypefunx {long double} scalbl (long double @var{value}, int @var{exponent})
1053 The @code{scalb} function is the BSD name for @code{ldexp}.
1054 @end deftypefun
1055
1056 @comment math.h
1057 @comment BSD
1058 @deftypefun {long long int} scalbn (double @var{x}, int n)
1059 @comment math.h
1060 @comment BSD
1061 @deftypefunx {long long int} scalbnf (float @var{x}, int n)
1062 @comment math.h
1063 @comment BSD
1064 @deftypefunx {long long int} scalbnl (long double @var{x}, int n)
1065 @code{scalbn} is identical to @code{scalb}, except that the exponent
1066 @var{n} is an @code{int} instead of a floating-point number.
1067 @end deftypefun
1068
1069 @comment math.h
1070 @comment BSD
1071 @deftypefun {long long int} scalbln (double @var{x}, long int n)
1072 @comment math.h
1073 @comment BSD
1074 @deftypefunx {long long int} scalblnf (float @var{x}, long int n)
1075 @comment math.h
1076 @comment BSD
1077 @deftypefunx {long long int} scalblnl (long double @var{x}, long int n)
1078 @code{scalbln} is identical to @code{scalb}, except that the exponent
1079 @var{n} is a @code{long int} instead of a floating-point number.
1080 @end deftypefun
1081
1082 @comment math.h
1083 @comment BSD
1084 @deftypefun {long long int} significand (double @var{x})
1085 @comment math.h
1086 @comment BSD
1087 @deftypefunx {long long int} significandf (float @var{x})
1088 @comment math.h
1089 @comment BSD
1090 @deftypefunx {long long int} significandl (long double @var{x})
1091 @code{significand} returns the mantissa of @var{x} scaled to the range
1092 @math{[1, 2)}.
1093 It is equivalent to @w{@code{scalb (@var{x}, (double) -ilogb (@var{x}))}}.
1094
1095 This function exists mainly for use in certain standardized tests
1096 of @w{IEEE 754} conformance.
1097 @end deftypefun
1098
1099 @node Rounding Functions
1100 @subsection Rounding Functions
1101 @cindex converting floats to integers
1102
1103 @pindex math.h
1104 The functions listed here perform operations such as rounding and
1105 truncation of floating-point values. Some of these functions convert
1106 floating point numbers to integer values.  They are all declared in
1107 @file{math.h}.
1108
1109 You can also convert floating-point numbers to integers simply by
1110 casting them to @code{int}.  This discards the fractional part,
1111 effectively rounding towards zero.  However, this only works if the
1112 result can actually be represented as an @code{int}---for very large
1113 numbers, this is impossible.  The functions listed here return the
1114 result as a @code{double} instead to get around this problem.
1115
1116 @comment math.h
1117 @comment ISO
1118 @deftypefun double ceil (double @var{x})
1119 @comment math.h
1120 @comment ISO
1121 @deftypefunx float ceilf (float @var{x})
1122 @comment math.h
1123 @comment ISO
1124 @deftypefunx {long double} ceill (long double @var{x})
1125 These functions round @var{x} upwards to the nearest integer,
1126 returning that value as a @code{double}.  Thus, @code{ceil (1.5)}
1127 is @code{2.0}.
1128 @end deftypefun
1129
1130 @comment math.h
1131 @comment ISO
1132 @deftypefun double floor (double @var{x})
1133 @comment math.h
1134 @comment ISO
1135 @deftypefunx float floorf (float @var{x})
1136 @comment math.h
1137 @comment ISO
1138 @deftypefunx {long double} floorl (long double @var{x})
1139 These functions round @var{x} downwards to the nearest
1140 integer, returning that value as a @code{double}.  Thus, @code{floor
1141 (1.5)} is @code{1.0} and @code{floor (-1.5)} is @code{-2.0}.
1142 @end deftypefun
1143
1144 @comment math.h
1145 @comment ISO
1146 @deftypefun double trunc (double @var{x})
1147 @comment math.h
1148 @comment ISO
1149 @deftypefunx float truncf (float @var{x})
1150 @comment math.h
1151 @comment ISO
1152 @deftypefunx {long double} truncl (long double @var{x})
1153 @code{trunc} is another name for @code{floor}
1154 @end deftypefun
1155
1156 @comment math.h
1157 @comment ISO
1158 @deftypefun double rint (double @var{x})
1159 @comment math.h
1160 @comment ISO
1161 @deftypefunx float rintf (float @var{x})
1162 @comment math.h
1163 @comment ISO
1164 @deftypefunx {long double} rintl (long double @var{x})
1165 These functions round @var{x} to an integer value according to the
1166 current rounding mode.  @xref{Floating Point Parameters}, for
1167 information about the various rounding modes.  The default
1168 rounding mode is to round to the nearest integer; some machines
1169 support other modes, but round-to-nearest is always used unless
1170 you explicitly select another.
1171
1172 If @var{x} was not initially an integer, these functions raise the
1173 inexact exception.
1174 @end deftypefun
1175
1176 @comment math.h
1177 @comment ISO
1178 @deftypefun double nearbyint (double @var{x})
1179 @comment math.h
1180 @comment ISO
1181 @deftypefunx float nearbyintf (float @var{x})
1182 @comment math.h
1183 @comment ISO
1184 @deftypefunx {long double} nearbyintl (long double @var{x})
1185 These functions return the same value as the @code{rint} functions, but
1186 do not raise the inexact exception if @var{x} is not an integer.
1187 @end deftypefun
1188
1189 @comment math.h
1190 @comment ISO
1191 @deftypefun double round (double @var{x})
1192 @comment math.h
1193 @comment ISO
1194 @deftypefunx float roundf (float @var{x})
1195 @comment math.h
1196 @comment ISO
1197 @deftypefunx {long double} roundl (long double @var{x})
1198 These functions are similar to @code{rint}, but they round halfway
1199 cases away from zero instead of to the nearest even integer.
1200 @end deftypefun
1201
1202 @comment math.h
1203 @comment ISO
1204 @deftypefun {long int} lrint (double @var{x})
1205 @comment math.h
1206 @comment ISO
1207 @deftypefunx {long int} lrintf (float @var{x})
1208 @comment math.h
1209 @comment ISO
1210 @deftypefunx {long int} lrintl (long double @var{x})
1211 These functions are just like @code{rint}, but they return a
1212 @code{long int} instead of a floating-point number.
1213 @end deftypefun
1214
1215 @comment math.h
1216 @comment ISO
1217 @deftypefun {long long int} llrint (double @var{x})
1218 @comment math.h
1219 @comment ISO
1220 @deftypefunx {long long int} llrintf (float @var{x})
1221 @comment math.h
1222 @comment ISO
1223 @deftypefunx {long long int} llrintl (long double @var{x})
1224 These functions are just like @code{rint}, but they return a
1225 @code{long long int} instead of a floating-point number.
1226 @end deftypefun
1227
1228 @comment math.h
1229 @comment ISO
1230 @deftypefun {long int} lround (double @var{x})
1231 @comment math.h
1232 @comment ISO
1233 @deftypefunx {long int} lroundf (float @var{x})
1234 @comment math.h
1235 @comment ISO
1236 @deftypefunx {long int} lroundl (long double @var{x})
1237 These functions are just like @code{round}, but they return a
1238 @code{long int} instead of a floating-point number.
1239 @end deftypefun
1240
1241 @comment math.h
1242 @comment ISO
1243 @deftypefun {long long int} llround (double @var{x})
1244 @comment math.h
1245 @comment ISO
1246 @deftypefunx {long long int} llroundf (float @var{x})
1247 @comment math.h
1248 @comment ISO
1249 @deftypefunx {long long int} llroundl (long double @var{x})
1250 These functions are just like @code{round}, but they return a
1251 @code{long long int} instead of a floating-point number.
1252 @end deftypefun
1253
1254
1255 @comment math.h
1256 @comment ISO
1257 @deftypefun double modf (double @var{value}, double *@var{integer-part})
1258 @comment math.h
1259 @comment ISO
1260 @deftypefunx float modff (float @var{value}, float *@var{integer-part})
1261 @comment math.h
1262 @comment ISO
1263 @deftypefunx {long double} modfl (long double @var{value}, long double *@var{integer-part})
1264 These functions break the argument @var{value} into an integer part and a
1265 fractional part (between @code{-1} and @code{1}, exclusive).  Their sum
1266 equals @var{value}.  Each of the parts has the same sign as @var{value},
1267 and the integer part is always rounded toward zero.
1268
1269 @code{modf} stores the integer part in @code{*@var{integer-part}}, and
1270 returns the fractional part.  For example, @code{modf (2.5, &intpart)}
1271 returns @code{0.5} and stores @code{2.0} into @code{intpart}.
1272 @end deftypefun
1273
1274 @node Remainder Functions
1275 @subsection Remainder Functions
1276
1277 The functions in this section compute the remainder on division of two
1278 floating-point numbers.  Each is a little different; pick the one that
1279 suits your problem.
1280
1281 @comment math.h
1282 @comment ISO
1283 @deftypefun double fmod (double @var{numerator}, double @var{denominator})
1284 @comment math.h
1285 @comment ISO
1286 @deftypefunx float fmodf (float @var{numerator}, float @var{denominator})
1287 @comment math.h
1288 @comment ISO
1289 @deftypefunx {long double} fmodl (long double @var{numerator}, long double @var{denominator})
1290 These functions compute the remainder from the division of
1291 @var{numerator} by @var{denominator}.  Specifically, the return value is
1292 @code{@var{numerator} - @w{@var{n} * @var{denominator}}}, where @var{n}
1293 is the quotient of @var{numerator} divided by @var{denominator}, rounded
1294 towards zero to an integer.  Thus, @w{@code{fmod (6.5, 2.3)}} returns
1295 @code{1.9}, which is @code{6.5} minus @code{4.6}.
1296
1297 The result has the same sign as the @var{numerator} and has magnitude
1298 less than the magnitude of the @var{denominator}.
1299
1300 If @var{denominator} is zero, @code{fmod} signals a domain error.
1301 @end deftypefun
1302
1303 @comment math.h
1304 @comment BSD
1305 @deftypefun double drem (double @var{numerator}, double @var{denominator})
1306 @comment math.h
1307 @comment BSD
1308 @deftypefunx float dremf (float @var{numerator}, float @var{denominator})
1309 @comment math.h
1310 @comment BSD
1311 @deftypefunx {long double} dreml (long double @var{numerator}, long double @var{denominator})
1312 These functions are like @code{fmod} except that they rounds the
1313 internal quotient @var{n} to the nearest integer instead of towards zero
1314 to an integer.  For example, @code{drem (6.5, 2.3)} returns @code{-0.4},
1315 which is @code{6.5} minus @code{6.9}.
1316
1317 The absolute value of the result is less than or equal to half the
1318 absolute value of the @var{denominator}.  The difference between
1319 @code{fmod (@var{numerator}, @var{denominator})} and @code{drem
1320 (@var{numerator}, @var{denominator})} is always either
1321 @var{denominator}, minus @var{denominator}, or zero.
1322
1323 If @var{denominator} is zero, @code{drem} signals a domain error.
1324 @end deftypefun
1325
1326 @comment math.h
1327 @comment BSD
1328 @deftypefun double remainder (double @var{numerator}, double @var{denominator})
1329 @comment math.h
1330 @comment BSD
1331 @deftypefunx float remainderf (float @var{numerator}, float @var{denominator})
1332 @comment math.h
1333 @comment BSD
1334 @deftypefunx {long double} remainderl (long double @var{numerator}, long double @var{denominator})
1335 This function is another name for @code{drem}.
1336 @end deftypefun
1337
1338 @node FP Bit Twiddling
1339 @subsection Setting and modifying single bits of FP values
1340 @cindex FP arithmetic
1341
1342 There are some operations that are too complicated or expensive to
1343 perform by hand on floating-point numbers.  @w{ISO C99} defines
1344 functions to do these operations, which mostly involve changing single
1345 bits.
1346
1347 @comment math.h
1348 @comment ISO
1349 @deftypefun double copysign (double @var{x}, double @var{y})
1350 @comment math.h
1351 @comment ISO
1352 @deftypefunx float copysignf (float @var{x}, float @var{y})
1353 @comment math.h
1354 @comment ISO
1355 @deftypefunx {long double} copysignl (long double @var{x}, long double @var{y})
1356 These functions return @var{x} but with the sign of @var{y}.  They work
1357 even if @var{x} or @var{y} are NaN or zero.  Both of these can carry a
1358 sign (although not all implementations support it) and this is one of
1359 the few operations that can tell the difference.
1360
1361 @code{copysign} never raises an exception.
1362 @c except signalling NaNs
1363
1364 This function is defined in @w{IEC 559} (and the appendix with
1365 recommended functions in @w{IEEE 754}/@w{IEEE 854}).
1366 @end deftypefun
1367
1368 @comment math.h
1369 @comment ISO
1370 @deftypefun int signbit (@emph{float-type} @var{x})
1371 @code{signbit} is a generic macro which can work on all floating-point
1372 types.  It returns a nonzero value if the value of @var{x} has its sign
1373 bit set.
1374
1375 This is not the same as @code{x < 0.0}, because @w{IEEE 754} floating
1376 point allows zero to be signed.  The comparison @code{-0.0 < 0.0} is
1377 false, but @code{signbit (-0.0)} will return a nonzero value.
1378 @end deftypefun
1379
1380 @comment math.h
1381 @comment ISO
1382 @deftypefun double nextafter (double @var{x}, double @var{y})
1383 @comment math.h
1384 @comment ISO
1385 @deftypefunx float nextafterf (float @var{x}, float @var{y})
1386 @comment math.h
1387 @comment ISO
1388 @deftypefunx {long double} nextafterl (long double @var{x}, long double @var{y})
1389 The @code{nextafter} function returns the next representable neighbor of
1390 @var{x} in the direction towards @var{y}.  The size of the step between
1391 @var{x} and the result depends on the type of the result.  If
1392 @math{@var{x} = @var{y}} the function simply returns @var{x}.  If either
1393 value is @code{NaN}, @code{NaN} is returned.  Otherwise
1394 a value corresponding to the value of the least significant bit in the
1395 mantissa is added or subtracted, depending on the direction.
1396 @code{nextafter} will signal overflow or underflow if the result goes
1397 outside of the range of normalized numbers.
1398
1399 This function is defined in @w{IEC 559} (and the appendix with
1400 recommended functions in @w{IEEE 754}/@w{IEEE 854}).
1401 @end deftypefun
1402
1403 @comment math.h
1404 @comment ISO
1405 @deftypefun double nexttoward (double @var{x}, long double @var{y})
1406 @comment math.h
1407 @comment ISO
1408 @deftypefunx float nexttowardf (float @var{x}, long double @var{y})
1409 @comment math.h
1410 @comment ISO
1411 @deftypefunx {long double} nexttowardl (long double @var{x}, long double @var{y})
1412 These functions are identical to the corresponding versions of
1413 @code{nextafter} except that their second argument is a @code{long
1414 double}.
1415 @end deftypefun
1416
1417 @cindex NaN
1418 @comment math.h
1419 @comment ISO
1420 @deftypefun double nan (const char *@var{tagp})
1421 @comment math.h
1422 @comment ISO
1423 @deftypefunx float nanf (const char *@var{tagp})
1424 @comment math.h
1425 @comment ISO
1426 @deftypefunx {long double} nanl (const char *@var{tagp})
1427 The @code{nan} function returns a representation of NaN, provided that
1428 NaN is supported by the target platform.
1429 @code{nan ("@var{n-char-sequence}")} is equivalent to
1430 @code{strtod ("NAN(@var{n-char-sequence})")}.
1431
1432 The argument @var{tagp} is used in an unspecified manner.  On @w{IEEE
1433 754} systems, there are many representations of NaN, and @var{tagp}
1434 selects one.  On other systems it may do nothing.
1435 @end deftypefun
1436
1437 @node FP Comparison Functions
1438 @subsection Floating-Point Comparison Functions
1439 @cindex unordered comparison
1440
1441 The standard C comparison operators provoke exceptions when one or other
1442 of the operands is NaN.  For example,
1443
1444 @smallexample
1445 int v = a < 1.0;
1446 @end smallexample
1447
1448 @noindent
1449 will raise an exception if @var{a} is NaN.  (This does @emph{not}
1450 happen with @code{==} and @code{!=}; those merely return false and true,
1451 respectively, when NaN is examined.)  Frequently this exception is
1452 undesirable.  @w{ISO C99} therefore defines comparison functions that
1453 do not raise exceptions when NaN is examined.  All of the functions are
1454 implemented as macros which allow their arguments to be of any
1455 floating-point type.  The macros are guaranteed to evaluate their
1456 arguments only once.
1457
1458 @comment math.h
1459 @comment ISO
1460 @deftypefn Macro int isgreater (@emph{real-floating} @var{x}, @emph{real-floating} @var{y})
1461 This macro determines whether the argument @var{x} is greater than
1462 @var{y}.  It is equivalent to @code{(@var{x}) > (@var{y})}, but no
1463 exception is raised if @var{x} or @var{y} are NaN.
1464 @end deftypefn
1465
1466 @comment math.h
1467 @comment ISO
1468 @deftypefn Macro int isgreaterequal (@emph{real-floating} @var{x}, @emph{real-floating} @var{y})
1469 This macro determines whether the argument @var{x} is greater than or
1470 equal to @var{y}.  It is equivalent to @code{(@var{x}) >= (@var{y})}, but no
1471 exception is raised if @var{x} or @var{y} are NaN.
1472 @end deftypefn
1473
1474 @comment math.h
1475 @comment ISO
1476 @deftypefn Macro int isless (@emph{real-floating} @var{x}, @emph{real-floating} @var{y})
1477 This macro determines whether the argument @var{x} is less than @var{y}.
1478 It is equivalent to @code{(@var{x}) < (@var{y})}, but no exception is
1479 raised if @var{x} or @var{y} are NaN.
1480 @end deftypefn
1481
1482 @comment math.h
1483 @comment ISO
1484 @deftypefn Macro int islessequal (@emph{real-floating} @var{x}, @emph{real-floating} @var{y})
1485 This macro determines whether the argument @var{x} is less than or equal
1486 to @var{y}.  It is equivalent to @code{(@var{x}) <= (@var{y})}, but no
1487 exception is raised if @var{x} or @var{y} are NaN.
1488 @end deftypefn
1489
1490 @comment math.h
1491 @comment ISO
1492 @deftypefn Macro int islessgreater (@emph{real-floating} @var{x}, @emph{real-floating} @var{y})
1493 This macro determines whether the argument @var{x} is less or greater
1494 than @var{y}.  It is equivalent to @code{(@var{x}) < (@var{y}) ||
1495 (@var{x}) > (@var{y})} (although it only evaluates @var{x} and @var{y}
1496 once), but no exception is raised if @var{x} or @var{y} are NaN.
1497
1498 This macro is not equivalent to @code{@var{x} != @var{y}}, because that
1499 expression is true if @var{x} or @var{y} are NaN.
1500 @end deftypefn
1501
1502 @comment math.h
1503 @comment ISO
1504 @deftypefn Macro int isunordered (@emph{real-floating} @var{x}, @emph{real-floating} @var{y})
1505 This macro determines whether its arguments are unordered.  In other
1506 words, it is true if @var{x} or @var{y} are NaN, and false otherwise.
1507 @end deftypefn
1508
1509 Not all machines provide hardware support for these operations.  On
1510 machines that don't, the macros can be very slow.  Therefore, you should
1511 not use these functions when NaN is not a concern.
1512
1513 @strong{Note:} There are no macros @code{isequal} or @code{isunequal}.
1514 They are unnecessary, because the @code{==} and @code{!=} operators do
1515 @emph{not} throw an exception if one or both of the operands are NaN.
1516
1517 @node Misc FP Arithmetic
1518 @subsection Miscellaneous FP arithmetic functions
1519 @cindex minimum
1520 @cindex maximum
1521 @cindex positive difference
1522 @cindex multiply-add
1523
1524 The functions in this section perform miscellaneous but common
1525 operations that are awkward to express with C operators.  On some
1526 processors these functions can use special machine instructions to
1527 perform these operations faster than the equivalent C code.
1528
1529 @comment math.h
1530 @comment ISO
1531 @deftypefun double fmin (double @var{x}, double @var{y})
1532 @comment math.h
1533 @comment ISO
1534 @deftypefunx float fminf (float @var{x}, float @var{y})
1535 @comment math.h
1536 @comment ISO
1537 @deftypefunx {long double} fminl (long double @var{x}, long double @var{y})
1538 The @code{fmin} function returns the lesser of the two values @var{x}
1539 and @var{y}.  It is similar to the expression
1540 @smallexample
1541 ((x) < (y) ? (x) : (y))
1542 @end smallexample
1543 except that @var{x} and @var{y} are only evaluated once.
1544
1545 If an argument is NaN, the other argument is returned.  If both arguments
1546 are NaN, NaN is returned.
1547 @end deftypefun
1548
1549 @comment math.h
1550 @comment ISO
1551 @deftypefun double fmax (double @var{x}, double @var{y})
1552 @comment math.h
1553 @comment ISO
1554 @deftypefunx float fmaxf (float @var{x}, float @var{y})
1555 @comment math.h
1556 @comment ISO
1557 @deftypefunx {long double} fmaxl (long double @var{x}, long double @var{y})
1558 The @code{fmax} function returns the greater of the two values @var{x}
1559 and @var{y}.
1560
1561 If an argument is NaN, the other argument is returned.  If both arguments
1562 are NaN, NaN is returned.
1563 @end deftypefun
1564
1565 @comment math.h
1566 @comment ISO
1567 @deftypefun double fdim (double @var{x}, double @var{y})
1568 @comment math.h
1569 @comment ISO
1570 @deftypefunx float fdimf (float @var{x}, float @var{y})
1571 @comment math.h
1572 @comment ISO
1573 @deftypefunx {long double} fdiml (long double @var{x}, long double @var{y})
1574 The @code{fdim} function returns the positive difference between
1575 @var{x} and @var{y}.  The positive difference is @math{@var{x} -
1576 @var{y}} if @var{x} is greater than @var{y}, and @math{0} otherwise.
1577
1578 If @var{x}, @var{y}, or both are NaN, NaN is returned.
1579 @end deftypefun
1580
1581 @comment math.h
1582 @comment ISO
1583 @deftypefun double fma (double @var{x}, double @var{y}, double @var{z})
1584 @comment math.h
1585 @comment ISO
1586 @deftypefunx float fmaf (float @var{x}, float @var{y}, float @var{z})
1587 @comment math.h
1588 @comment ISO
1589 @deftypefunx {long double} fmal (long double @var{x}, long double @var{y}, long double @var{z})
1590 @cindex butterfly
1591 The @code{fma} function performs floating-point multiply-add.  This is
1592 the operation @math{(@var{x} @mul{} @var{y}) + @var{z}}, but the
1593 intermediate result is not rounded to the destination type.  This can
1594 sometimes improve the precision of a calculation.
1595
1596 This function was introduced because some processors have a special
1597 instruction to perform multiply-add.  The C compiler cannot use it
1598 directly, because the expression @samp{x*y + z} is defined to round the
1599 intermediate result.  @code{fma} lets you choose when you want to round
1600 only once.
1601
1602 @vindex FP_FAST_FMA
1603 On processors which do not implement multiply-add in hardware,
1604 @code{fma} can be very slow since it must avoid intermediate rounding.
1605 @file{math.h} defines the symbols @code{FP_FAST_FMA},
1606 @code{FP_FAST_FMAF}, and @code{FP_FAST_FMAL} when the corresponding
1607 version of @code{fma} is no slower than the expression @samp{x*y + z}.
1608 In the GNU C library, this always means the operation is implemented in
1609 hardware.
1610 @end deftypefun
1611
1612 @node Complex Numbers
1613 @section Complex Numbers
1614 @pindex complex.h
1615 @cindex complex numbers
1616
1617 @w{ISO C99} introduces support for complex numbers in C.  This is done
1618 with a new type qualifier, @code{complex}.  It is a keyword if and only
1619 if @file{complex.h} has been included.  There are three complex types,
1620 corresponding to the three real types:  @code{float complex},
1621 @code{double complex}, and @code{long double complex}.
1622
1623 To construct complex numbers you need a way to indicate the imaginary
1624 part of a number.  There is no standard notation for an imaginary
1625 floating point constant.  Instead, @file{complex.h} defines two macros
1626 that can be used to create complex numbers.
1627
1628 @deftypevr Macro {const float complex} _Complex_I
1629 This macro is a representation of the complex number ``@math{0+1i}''.
1630 Multiplying a real floating-point value by @code{_Complex_I} gives a
1631 complex number whose value is purely imaginary.  You can use this to
1632 construct complex constants:
1633
1634 @smallexample
1635 @math{3.0 + 4.0i} = @code{3.0 + 4.0 * _Complex_I}
1636 @end smallexample
1637
1638 Note that @code{_Complex_I * _Complex_I} has the value @code{-1}, but
1639 the type of that value is @code{complex}.
1640 @end deftypevr
1641
1642 @c Put this back in when gcc supports _Imaginary_I.  It's too confusing.
1643 @ignore
1644 @noindent
1645 Without an optimizing compiler this is more expensive than the use of
1646 @code{_Imaginary_I} but with is better than nothing.  You can avoid all
1647 the hassles if you use the @code{I} macro below if the name is not
1648 problem.
1649
1650 @deftypevr Macro {const float imaginary} _Imaginary_I
1651 This macro is a representation of the value ``@math{1i}''.  I.e., it is
1652 the value for which
1653
1654 @smallexample
1655 _Imaginary_I * _Imaginary_I = -1
1656 @end smallexample
1657
1658 @noindent
1659 The result is not of type @code{float imaginary} but instead @code{float}.
1660 One can use it to easily construct complex number like in
1661
1662 @smallexample
1663 3.0 - _Imaginary_I * 4.0
1664 @end smallexample
1665
1666 @noindent
1667 which results in the complex number with a real part of 3.0 and a
1668 imaginary part -4.0.
1669 @end deftypevr
1670 @end ignore
1671
1672 @noindent
1673 @code{_Complex_I} is a bit of a mouthful.  @file{complex.h} also defines
1674 a shorter name for the same constant.
1675
1676 @deftypevr Macro {const float complex} I
1677 This macro has exactly the same value as @code{_Complex_I}.  Most of the
1678 time it is preferable.  However, it causes problems if you want to use
1679 the identifier @code{I} for something else.  You can safely write
1680
1681 @smallexample
1682 #include <complex.h>
1683 #undef I
1684 @end smallexample
1685
1686 @noindent
1687 if you need @code{I} for your own purposes.  (In that case we recommend
1688 you also define some other short name for @code{_Complex_I}, such as
1689 @code{J}.)
1690
1691 @ignore
1692 If the implementation does not support the @code{imaginary} types
1693 @code{I} is defined as @code{_Complex_I} which is the second best
1694 solution.  It still can be used in the same way but requires a most
1695 clever compiler to get the same results.
1696 @end ignore
1697 @end deftypevr
1698
1699 @node Operations on Complex
1700 @section Projections, Conjugates, and Decomposing of Complex Numbers
1701 @cindex project complex numbers
1702 @cindex conjugate complex numbers
1703 @cindex decompose complex numbers
1704 @pindex complex.h
1705
1706 @w{ISO C99} also defines functions that perform basic operations on
1707 complex numbers, such as decomposition and conjugation.  The prototypes
1708 for all these functions are in @file{complex.h}.  All functions are
1709 available in three variants, one for each of the three complex types.
1710
1711 @comment complex.h
1712 @comment ISO
1713 @deftypefun double creal (complex double @var{z})
1714 @comment complex.h
1715 @comment ISO
1716 @deftypefunx float crealf (complex float @var{z})
1717 @comment complex.h
1718 @comment ISO
1719 @deftypefunx {long double} creall (complex long double @var{z})
1720 These functions return the real part of the complex number @var{z}.
1721 @end deftypefun
1722
1723 @comment complex.h
1724 @comment ISO
1725 @deftypefun double cimag (complex double @var{z})
1726 @comment complex.h
1727 @comment ISO
1728 @deftypefunx float cimagf (complex float @var{z})
1729 @comment complex.h
1730 @comment ISO
1731 @deftypefunx {long double} cimagl (complex long double @var{z})
1732 These functions return the imaginary part of the complex number @var{z}.
1733 @end deftypefun
1734
1735 @comment complex.h
1736 @comment ISO
1737 @deftypefun {complex double} conj (complex double @var{z})
1738 @comment complex.h
1739 @comment ISO
1740 @deftypefunx {complex float} conjf (complex float @var{z})
1741 @comment complex.h
1742 @comment ISO
1743 @deftypefunx {complex long double} conjl (complex long double @var{z})
1744 These functions return the conjugate value of the complex number
1745 @var{z}.  The conjugate of a complex number has the same real part and a
1746 negated imaginary part.  In other words, @samp{conj(a + bi) = a + -bi}.
1747 @end deftypefun
1748
1749 @comment complex.h
1750 @comment ISO
1751 @deftypefun double carg (complex double @var{z})
1752 @comment complex.h
1753 @comment ISO
1754 @deftypefunx float cargf (complex float @var{z})
1755 @comment complex.h
1756 @comment ISO
1757 @deftypefunx {long double} cargl (complex long double @var{z})
1758 These functions return the argument of the complex number @var{z}.
1759 The argument of a complex number is the angle in the complex plane
1760 between the positive real axis and a line passing through zero and the
1761 number.  This angle is measured in the usual fashion and ranges from @math{0}
1762 to @math{2@pi{}}.
1763
1764 @code{carg} has a branch cut along the positive real axis.
1765 @end deftypefun
1766
1767 @comment complex.h
1768 @comment ISO
1769 @deftypefun {complex double} cproj (complex double @var{z})
1770 @comment complex.h
1771 @comment ISO
1772 @deftypefunx {complex float} cprojf (complex float @var{z})
1773 @comment complex.h
1774 @comment ISO
1775 @deftypefunx {complex long double} cprojl (complex long double @var{z})
1776 These functions return the projection of the complex value @var{z} onto
1777 the Riemann sphere.  Values with a infinite imaginary part are projected
1778 to positive infinity on the real axis, even if the real part is NaN.  If
1779 the real part is infinite, the result is equivalent to
1780
1781 @smallexample
1782 INFINITY + I * copysign (0.0, cimag (z))
1783 @end smallexample
1784 @end deftypefun
1785
1786 @node Integer Division
1787 @section Integer Division
1788 @cindex integer division functions
1789
1790 This section describes functions for performing integer division.  These
1791 functions are redundant when GNU CC is used, because in GNU C the
1792 @samp{/} operator always rounds towards zero.  But in other C
1793 implementations, @samp{/} may round differently with negative arguments.
1794 @code{div} and @code{ldiv} are useful because they specify how to round
1795 the quotient: towards zero.  The remainder has the same sign as the
1796 numerator.
1797
1798 These functions are specified to return a result @var{r} such that the value
1799 @code{@var{r}.quot*@var{denominator} + @var{r}.rem} equals
1800 @var{numerator}.
1801
1802 @pindex stdlib.h
1803 To use these facilities, you should include the header file
1804 @file{stdlib.h} in your program.
1805
1806 @comment stdlib.h
1807 @comment ISO
1808 @deftp {Data Type} div_t
1809 This is a structure type used to hold the result returned by the @code{div}
1810 function.  It has the following members:
1811
1812 @table @code
1813 @item int quot
1814 The quotient from the division.
1815
1816 @item int rem
1817 The remainder from the division.
1818 @end table
1819 @end deftp
1820
1821 @comment stdlib.h
1822 @comment ISO
1823 @deftypefun div_t div (int @var{numerator}, int @var{denominator})
1824 This function @code{div} computes the quotient and remainder from
1825 the division of @var{numerator} by @var{denominator}, returning the
1826 result in a structure of type @code{div_t}.
1827
1828 If the result cannot be represented (as in a division by zero), the
1829 behavior is undefined.
1830
1831 Here is an example, albeit not a very useful one.
1832
1833 @smallexample
1834 div_t result;
1835 result = div (20, -6);
1836 @end smallexample
1837
1838 @noindent
1839 Now @code{result.quot} is @code{-3} and @code{result.rem} is @code{2}.
1840 @end deftypefun
1841
1842 @comment stdlib.h
1843 @comment ISO
1844 @deftp {Data Type} ldiv_t
1845 This is a structure type used to hold the result returned by the @code{ldiv}
1846 function.  It has the following members:
1847
1848 @table @code
1849 @item long int quot
1850 The quotient from the division.
1851
1852 @item long int rem
1853 The remainder from the division.
1854 @end table
1855
1856 (This is identical to @code{div_t} except that the components are of
1857 type @code{long int} rather than @code{int}.)
1858 @end deftp
1859
1860 @comment stdlib.h
1861 @comment ISO
1862 @deftypefun ldiv_t ldiv (long int @var{numerator}, long int @var{denominator})
1863 The @code{ldiv} function is similar to @code{div}, except that the
1864 arguments are of type @code{long int} and the result is returned as a
1865 structure of type @code{ldiv_t}.
1866 @end deftypefun
1867
1868 @comment stdlib.h
1869 @comment ISO
1870 @deftp {Data Type} lldiv_t
1871 This is a structure type used to hold the result returned by the @code{lldiv}
1872 function.  It has the following members:
1873
1874 @table @code
1875 @item long long int quot
1876 The quotient from the division.
1877
1878 @item long long int rem
1879 The remainder from the division.
1880 @end table
1881
1882 (This is identical to @code{div_t} except that the components are of
1883 type @code{long long int} rather than @code{int}.)
1884 @end deftp
1885
1886 @comment stdlib.h
1887 @comment ISO
1888 @deftypefun lldiv_t lldiv (long long int @var{numerator}, long long int @var{denominator})
1889 The @code{lldiv} function is like the @code{div} function, but the
1890 arguments are of type @code{long long int} and the result is returned as
1891 a structure of type @code{lldiv_t}.
1892
1893 The @code{lldiv} function was added in @w{ISO C99}.
1894 @end deftypefun
1895
1896 @comment inttypes.h
1897 @comment ISO
1898 @deftp {Data Type} imaxdiv_t
1899 This is a structure type used to hold the result returned by the @code{imaxdiv}
1900 function.  It has the following members:
1901
1902 @table @code
1903 @item intmax_t quot
1904 The quotient from the division.
1905
1906 @item intmax_t rem
1907 The remainder from the division.
1908 @end table
1909
1910 (This is identical to @code{div_t} except that the components are of
1911 type @code{intmax_t} rather than @code{int}.)
1912 @end deftp
1913
1914 @comment inttypes.h
1915 @comment ISO
1916 @deftypefun imaxdiv_t imaxdiv (intmax_t @var{numerator}, intmax_t @var{denominator})
1917 The @code{imaxdiv} function is like the @code{div} function, but the
1918 arguments are of type @code{intmax_t} and the result is returned as
1919 a structure of type @code{imaxdiv_t}.
1920
1921 The @code{imaxdiv} function was added in @w{ISO C99}.
1922 @end deftypefun
1923
1924
1925 @node Parsing of Numbers
1926 @section Parsing of Numbers
1927 @cindex parsing numbers (in formatted input)
1928 @cindex converting strings to numbers
1929 @cindex number syntax, parsing
1930 @cindex syntax, for reading numbers
1931
1932 This section describes functions for ``reading'' integer and
1933 floating-point numbers from a string.  It may be more convenient in some
1934 cases to use @code{sscanf} or one of the related functions; see
1935 @ref{Formatted Input}.  But often you can make a program more robust by
1936 finding the tokens in the string by hand, then converting the numbers
1937 one by one.
1938
1939 @menu
1940 * Parsing of Integers::         Functions for conversion of integer values.
1941 * Parsing of Floats::           Functions for conversion of floating-point
1942                                  values.
1943 @end menu
1944
1945 @node Parsing of Integers
1946 @subsection Parsing of Integers
1947
1948 @pindex stdlib.h
1949 These functions are declared in @file{stdlib.h}.
1950
1951 @comment stdlib.h
1952 @comment ISO
1953 @deftypefun {long int} strtol (const char *@var{string}, char **@var{tailptr}, int @var{base})
1954 The @code{strtol} (``string-to-long'') function converts the initial
1955 part of @var{string} to a signed integer, which is returned as a value
1956 of type @code{long int}.
1957
1958 This function attempts to decompose @var{string} as follows:
1959
1960 @itemize @bullet
1961 @item
1962 A (possibly empty) sequence of whitespace characters.  Which characters
1963 are whitespace is determined by the @code{isspace} function
1964 (@pxref{Classification of Characters}).  These are discarded.
1965
1966 @item
1967 An optional plus or minus sign (@samp{+} or @samp{-}).
1968
1969 @item
1970 A nonempty sequence of digits in the radix specified by @var{base}.
1971
1972 If @var{base} is zero, decimal radix is assumed unless the series of
1973 digits begins with @samp{0} (specifying octal radix), or @samp{0x} or
1974 @samp{0X} (specifying hexadecimal radix); in other words, the same
1975 syntax used for integer constants in C.
1976
1977 Otherwise @var{base} must have a value between @code{2} and @code{35}.
1978 If @var{base} is @code{16}, the digits may optionally be preceded by
1979 @samp{0x} or @samp{0X}.  If base has no legal value the value returned
1980 is @code{0l} and the global variable @code{errno} is set to @code{EINVAL}.
1981
1982 @item
1983 Any remaining characters in the string.  If @var{tailptr} is not a null
1984 pointer, @code{strtol} stores a pointer to this tail in
1985 @code{*@var{tailptr}}.
1986 @end itemize
1987
1988 If the string is empty, contains only whitespace, or does not contain an
1989 initial substring that has the expected syntax for an integer in the
1990 specified @var{base}, no conversion is performed.  In this case,
1991 @code{strtol} returns a value of zero and the value stored in
1992 @code{*@var{tailptr}} is the value of @var{string}.
1993
1994 In a locale other than the standard @code{"C"} locale, this function
1995 may recognize additional implementation-dependent syntax.
1996
1997 If the string has valid syntax for an integer but the value is not
1998 representable because of overflow, @code{strtol} returns either
1999 @code{LONG_MAX} or @code{LONG_MIN} (@pxref{Range of Type}), as
2000 appropriate for the sign of the value.  It also sets @code{errno}
2001 to @code{ERANGE} to indicate there was overflow.
2002
2003 You should not check for errors by examining the return value of
2004 @code{strtol}, because the string might be a valid representation of
2005 @code{0l}, @code{LONG_MAX}, or @code{LONG_MIN}.  Instead, check whether
2006 @var{tailptr} points to what you expect after the number
2007 (e.g. @code{'\0'} if the string should end after the number).  You also
2008 need to clear @var{errno} before the call and check it afterward, in
2009 case there was overflow.
2010
2011 There is an example at the end of this section.
2012 @end deftypefun
2013
2014 @comment stdlib.h
2015 @comment ISO
2016 @deftypefun {unsigned long int} strtoul (const char *@var{string}, char **@var{tailptr}, int @var{base})
2017 The @code{strtoul} (``string-to-unsigned-long'') function is like
2018 @code{strtol} except it returns an @code{unsigned long int} value.  If
2019 the number has a leading @samp{-} sign, the return value is negated.
2020 The syntax is the same as described above for @code{strtol}.  The value
2021 returned on overflow is @code{ULONG_MAX} (@pxref{Range of
2022 Type}).
2023
2024 @code{strtoul} sets @var{errno} to @code{EINVAL} if @var{base} is out of
2025 range, or @code{ERANGE} on overflow.
2026 @end deftypefun
2027
2028 @comment stdlib.h
2029 @comment ISO
2030 @deftypefun {long long int} strtoll (const char *@var{string}, char **@var{tailptr}, int @var{base})
2031 The @code{strtoll} function is like @code{strtol} except that it returns
2032 a @code{long long int} value, and accepts numbers with a correspondingly
2033 larger range.
2034
2035 If the string has valid syntax for an integer but the value is not
2036 representable because of overflow, @code{strtoll} returns either
2037 @code{LONG_LONG_MAX} or @code{LONG_LONG_MIN} (@pxref{Range of Type}), as
2038 appropriate for the sign of the value.  It also sets @code{errno} to
2039 @code{ERANGE} to indicate there was overflow.
2040
2041 The @code{strtoll} function was introduced in @w{ISO C99}.
2042 @end deftypefun
2043
2044 @comment stdlib.h
2045 @comment BSD
2046 @deftypefun {long long int} strtoq (const char *@var{string}, char **@var{tailptr}, int @var{base})
2047 @code{strtoq} (``string-to-quad-word'') is the BSD name for @code{strtoll}.
2048 @end deftypefun
2049
2050 @comment stdlib.h
2051 @comment ISO
2052 @deftypefun {unsigned long long int} strtoull (const char *@var{string}, char **@var{tailptr}, int @var{base})
2053 The @code{strtoull} function is like @code{strtoul} except that it
2054 returns an @code{unsigned long long int}.  The value returned on overflow
2055 is @code{ULONG_LONG_MAX} (@pxref{Range of Type}).
2056
2057 The @code{strtoull} function was introduced in @w{ISO C99}.
2058 @end deftypefun
2059
2060 @comment stdlib.h
2061 @comment BSD
2062 @deftypefun {unsigned long long int} strtouq (const char *@var{string}, char **@var{tailptr}, int @var{base})
2063 @code{strtouq} is the BSD name for @code{strtoull}.
2064 @end deftypefun
2065
2066 @comment stdlib.h
2067 @comment ISO
2068 @deftypefun {long int} atol (const char *@var{string})
2069 This function is similar to the @code{strtol} function with a @var{base}
2070 argument of @code{10}, except that it need not detect overflow errors.
2071 The @code{atol} function is provided mostly for compatibility with
2072 existing code; using @code{strtol} is more robust.
2073 @end deftypefun
2074
2075 @comment stdlib.h
2076 @comment ISO
2077 @deftypefun int atoi (const char *@var{string})
2078 This function is like @code{atol}, except that it returns an @code{int}.
2079 The @code{atoi} function is also considered obsolete; use @code{strtol}
2080 instead.
2081 @end deftypefun
2082
2083 @comment stdlib.h
2084 @comment ISO
2085 @deftypefun {long long int} atoll (const char *@var{string})
2086 This function is similar to @code{atol}, except it returns a @code{long
2087 long int}.
2088
2089 The @code{atoll} function was introduced in @w{ISO C99}.  It too is
2090 obsolete (despite having just been added); use @code{strtoll} instead.
2091 @end deftypefun
2092
2093 @c !!! please fact check this paragraph -zw
2094 @findex strtol_l
2095 @findex strtoul_l
2096 @findex strtoll_l
2097 @findex strtoull_l
2098 @cindex parsing numbers and locales
2099 @cindex locales, parsing numbers and
2100 Some locales specify a printed syntax for numbers other than the one
2101 that these functions understand.  If you need to read numbers formatted
2102 in some other locale, you can use the @code{strtoX_l} functions.  Each
2103 of the @code{strtoX} functions has a counterpart with @samp{_l} added to
2104 its name.  The @samp{_l} counterparts take an additional argument: a
2105 pointer to an @code{locale_t} structure, which describes how the numbers
2106 to be read are formatted.  @xref{Locales}.
2107
2108 @strong{Portability Note:} These functions are all GNU extensions.  You
2109 can also use @code{scanf} or its relatives, which have the @samp{'} flag
2110 for parsing numeric input according to the current locale
2111 (@pxref{Numeric Input Conversions}).  This feature is standard.
2112
2113 Here is a function which parses a string as a sequence of integers and
2114 returns the sum of them:
2115
2116 @smallexample
2117 int
2118 sum_ints_from_string (char *string)
2119 @{
2120   int sum = 0;
2121
2122   while (1) @{
2123     char *tail;
2124     int next;
2125
2126     /* @r{Skip whitespace by hand, to detect the end.}  */
2127     while (isspace (*string)) string++;
2128     if (*string == 0)
2129       break;
2130
2131     /* @r{There is more nonwhitespace,}  */
2132     /* @r{so it ought to be another number.}  */
2133     errno = 0;
2134     /* @r{Parse it.}  */
2135     next = strtol (string, &tail, 0);
2136     /* @r{Add it in, if not overflow.}  */
2137     if (errno)
2138       printf ("Overflow\n");
2139     else
2140       sum += next;
2141     /* @r{Advance past it.}  */
2142     string = tail;
2143   @}
2144
2145   return sum;
2146 @}
2147 @end smallexample
2148
2149 @node Parsing of Floats
2150 @subsection Parsing of Floats
2151
2152 @pindex stdlib.h
2153 These functions are declared in @file{stdlib.h}.
2154
2155 @comment stdlib.h
2156 @comment ISO
2157 @deftypefun double strtod (const char *@var{string}, char **@var{tailptr})
2158 The @code{strtod} (``string-to-double'') function converts the initial
2159 part of @var{string} to a floating-point number, which is returned as a
2160 value of type @code{double}.
2161
2162 This function attempts to decompose @var{string} as follows:
2163
2164 @itemize @bullet
2165 @item
2166 A (possibly empty) sequence of whitespace characters.  Which characters
2167 are whitespace is determined by the @code{isspace} function
2168 (@pxref{Classification of Characters}).  These are discarded.
2169
2170 @item
2171 An optional plus or minus sign (@samp{+} or @samp{-}).
2172
2173 @item A floating point number in decimal or hexadecimal format.  The
2174 decimal format is:
2175 @itemize @minus
2176
2177 @item
2178 A nonempty sequence of digits optionally containing a decimal-point
2179 character---normally @samp{.}, but it depends on the locale
2180 (@pxref{General Numeric}).
2181
2182 @item
2183 An optional exponent part, consisting of a character @samp{e} or
2184 @samp{E}, an optional sign, and a sequence of digits.
2185
2186 @end itemize
2187
2188 The hexadecimal format is as follows:
2189 @itemize @minus
2190
2191 @item
2192 A 0x or 0X followed by a nonempty sequence of hexadecimal digits
2193 optionally containing a decimal-point character---normally @samp{.}, but
2194 it depends on the locale (@pxref{General Numeric}).
2195
2196 @item
2197 An optional binary-exponent part, consisting of a character @samp{p} or
2198 @samp{P}, an optional sign, and a sequence of digits.
2199
2200 @end itemize
2201
2202 @item
2203 Any remaining characters in the string.  If @var{tailptr} is not a null
2204 pointer, a pointer to this tail of the string is stored in
2205 @code{*@var{tailptr}}.
2206 @end itemize
2207
2208 If the string is empty, contains only whitespace, or does not contain an
2209 initial substring that has the expected syntax for a floating-point
2210 number, no conversion is performed.  In this case, @code{strtod} returns
2211 a value of zero and the value returned in @code{*@var{tailptr}} is the
2212 value of @var{string}.
2213
2214 In a locale other than the standard @code{"C"} or @code{"POSIX"} locales,
2215 this function may recognize additional locale-dependent syntax.
2216
2217 If the string has valid syntax for a floating-point number but the value
2218 is outside the range of a @code{double}, @code{strtod} will signal
2219 overflow or underflow as described in @ref{Math Error Reporting}.
2220
2221 @code{strtod} recognizes four special input strings.  The strings
2222 @code{"inf"} and @code{"infinity"} are converted to @math{@infinity{}},
2223 or to the largest representable value if the floating-point format
2224 doesn't support infinities.  You can prepend a @code{"+"} or @code{"-"}
2225 to specify the sign.  Case is ignored when scanning these strings.
2226
2227 The strings @code{"nan"} and @code{"nan(@var{chars...})"} are converted
2228 to NaN.  Again, case is ignored.  If @var{chars...} are provided, they
2229 are used in some unspecified fashion to select a particular
2230 representation of NaN (there can be several).
2231
2232 Since zero is a valid result as well as the value returned on error, you
2233 should check for errors in the same way as for @code{strtol}, by
2234 examining @var{errno} and @var{tailptr}.
2235 @end deftypefun
2236
2237 @comment stdlib.h
2238 @comment ISO
2239 @deftypefun float strtof (const char *@var{string}, char **@var{tailptr})
2240 @comment stdlib.h
2241 @comment ISO
2242 @deftypefunx {long double} strtold (const char *@var{string}, char **@var{tailptr})
2243 These functions are analogous to @code{strtod}, but return @code{float}
2244 and @code{long double} values respectively.  They report errors in the
2245 same way as @code{strtod}.  @code{strtof} can be substantially faster
2246 than @code{strtod}, but has less precision; conversely, @code{strtold}
2247 can be much slower but has more precision (on systems where @code{long
2248 double} is a separate type).
2249
2250 These functions have been GNU extensions and are new to @w{ISO C99}.
2251 @end deftypefun
2252
2253 @comment stdlib.h
2254 @comment ISO
2255 @deftypefun double atof (const char *@var{string})
2256 This function is similar to the @code{strtod} function, except that it
2257 need not detect overflow and underflow errors.  The @code{atof} function
2258 is provided mostly for compatibility with existing code; using
2259 @code{strtod} is more robust.
2260 @end deftypefun
2261
2262 The GNU C library also provides @samp{_l} versions of thse functions,
2263 which take an additional argument, the locale to use in conversion.
2264 @xref{Parsing of Integers}.
2265
2266 @node System V Number Conversion
2267 @section Old-fashioned System V number-to-string functions
2268
2269 The old @w{System V} C library provided three functions to convert
2270 numbers to strings, with unusual and hard-to-use semantics.  The GNU C
2271 library also provides these functions and some natural extensions.
2272
2273 These functions are only available in glibc and on systems descended
2274 from AT&T Unix.  Therefore, unless these functions do precisely what you
2275 need, it is better to use @code{sprintf}, which is standard.
2276
2277 All these functions are defined in @file{stdlib.h}.
2278
2279 @comment stdlib.h
2280 @comment SVID, Unix98
2281 @deftypefun {char *} ecvt (double @var{value}, int @var{ndigit}, int *@var{decpt}, int *@var{neg})
2282 The function @code{ecvt} converts the floating-point number @var{value}
2283 to a string with at most @var{ndigit} decimal digits.  The
2284 returned string contains no decimal point or sign. The first digit of
2285 the string is non-zero (unless @var{value} is actually zero) and the
2286 last digit is rounded to nearest.  @code{*@var{decpt}} is set to the
2287 index in the string of the first digit after the decimal point.
2288 @code{*@var{neg}} is set to a nonzero value if @var{value} is negative,
2289 zero otherwise.
2290
2291 If @var{ndigit} decimal digits would exceed the precision of a
2292 @code{double} it is reduced to a system-specific value.
2293
2294 The returned string is statically allocated and overwritten by each call
2295 to @code{ecvt}.
2296
2297 If @var{value} is zero, it is implementation defined whether
2298 @code{*@var{decpt}} is @code{0} or @code{1}.
2299
2300 For example: @code{ecvt (12.3, 5, &d, &n)} returns @code{"12300"}
2301 and sets @var{d} to @code{2} and @var{n} to @code{0}.
2302 @end deftypefun
2303
2304 @comment stdlib.h
2305 @comment SVID, Unix98
2306 @deftypefun {char *} fcvt (double @var{value}, int @var{ndigit}, int *@var{decpt}, int *@var{neg})
2307 The function @code{fcvt} is like @code{ecvt}, but @var{ndigit} specifies
2308 the number of digits after the decimal point.  If @var{ndigit} is less
2309 than zero, @var{value} is rounded to the @math{@var{ndigit}+1}'th place to the
2310 left of the decimal point.  For example, if @var{ndigit} is @code{-1},
2311 @var{value} will be rounded to the nearest 10.  If @var{ndigit} is
2312 negative and larger than the number of digits to the left of the decimal
2313 point in @var{value}, @var{value} will be rounded to one significant digit.
2314
2315 If @var{ndigit} decimal digits would exceed the precision of a
2316 @code{double} it is reduced to a system-specific value.
2317
2318 The returned string is statically allocated and overwritten by each call
2319 to @code{fcvt}.
2320 @end deftypefun
2321
2322 @comment stdlib.h
2323 @comment SVID, Unix98
2324 @deftypefun {char *} gcvt (double @var{value}, int @var{ndigit}, char *@var{buf})
2325 @code{gcvt} is functionally equivalent to @samp{sprintf(buf, "%*g",
2326 ndigit, value}.  It is provided only for compatibility's sake.  It
2327 returns @var{buf}.
2328
2329 If @var{ndigit} decimal digits would exceed the precision of a
2330 @code{double} it is reduced to a system-specific value.
2331 @end deftypefun
2332
2333 As extensions, the GNU C library provides versions of these three
2334 functions that take @code{long double} arguments.
2335
2336 @comment stdlib.h
2337 @comment GNU
2338 @deftypefun {char *} qecvt (long double @var{value}, int @var{ndigit}, int *@var{decpt}, int *@var{neg})
2339 This function is equivalent to @code{ecvt} except that it takes a
2340 @code{long double} for the first parameter and that @var{ndigit} is
2341 restricted by the precision of a @code{long double}.
2342 @end deftypefun
2343
2344 @comment stdlib.h
2345 @comment GNU
2346 @deftypefun {char *} qfcvt (long double @var{value}, int @var{ndigit}, int *@var{decpt}, int *@var{neg})
2347 This function is equivalent to @code{fcvt} except that it
2348 takes a @code{long double} for the first parameter and that @var{ndigit} is
2349 restricted by the precision of a @code{long double}.
2350 @end deftypefun
2351
2352 @comment stdlib.h
2353 @comment GNU
2354 @deftypefun {char *} qgcvt (long double @var{value}, int @var{ndigit}, char *@var{buf})
2355 This function is equivalent to @code{gcvt} except that it takes a
2356 @code{long double} for the first parameter and that @var{ndigit} is
2357 restricted by the precision of a @code{long double}.
2358 @end deftypefun
2359
2360
2361 @cindex gcvt_r
2362 The @code{ecvt} and @code{fcvt} functions, and their @code{long double}
2363 equivalents, all return a string located in a static buffer which is
2364 overwritten by the next call to the function.  The GNU C library
2365 provides another set of extended functions which write the converted
2366 string into a user-supplied buffer.  These have the conventional
2367 @code{_r} suffix.
2368
2369 @code{gcvt_r} is not necessary, because @code{gcvt} already uses a
2370 user-supplied buffer.
2371
2372 @comment stdlib.h
2373 @comment GNU
2374 @deftypefun {char *} ecvt_r (double @var{value}, int @var{ndigit}, int *@var{decpt}, int *@var{neg}, char *@var{buf}, size_t @var{len})
2375 The @code{ecvt_r} function is the same as @code{ecvt}, except
2376 that it places its result into the user-specified buffer pointed to by
2377 @var{buf}, with length @var{len}.
2378
2379 This function is a GNU extension.
2380 @end deftypefun
2381
2382 @comment stdlib.h
2383 @comment SVID, Unix98
2384 @deftypefun {char *} fcvt_r (double @var{value}, int @var{ndigit}, int *@var{decpt}, int *@var{neg}, char *@var{buf}, size_t @var{len})
2385 The @code{fcvt_r} function is the same as @code{fcvt}, except
2386 that it places its result into the user-specified buffer pointed to by
2387 @var{buf}, with length @var{len}.
2388
2389 This function is a GNU extension.
2390 @end deftypefun
2391
2392 @comment stdlib.h
2393 @comment GNU
2394 @deftypefun {char *} qecvt_r (long double @var{value}, int @var{ndigit}, int *@var{decpt}, int *@var{neg}, char *@var{buf}, size_t @var{len})
2395 The @code{qecvt_r} function is the same as @code{qecvt}, except
2396 that it places its result into the user-specified buffer pointed to by
2397 @var{buf}, with length @var{len}.
2398
2399 This function is a GNU extension.
2400 @end deftypefun
2401
2402 @comment stdlib.h
2403 @comment GNU
2404 @deftypefun {char *} qfcvt_r (long double @var{value}, int @var{ndigit}, int *@var{decpt}, int *@var{neg}, char *@var{buf}, size_t @var{len})
2405 The @code{qfcvt_r} function is the same as @code{qfcvt}, except
2406 that it places its result into the user-specified buffer pointed to by
2407 @var{buf}, with length @var{len}.
2408
2409 This function is a GNU extension.
2410 @end deftypefun