]> www.ginac.de Git - cln.git/blob - doc/cln.tex
* doc/cln.tex (Building the library): Update recommendations for
[cln.git] / doc / cln.tex
1 \input texinfo  @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename cln.info
4 @settitle CLN, a Class Library for Numbers
5 @c @setchapternewpage off
6 @c For `info' only.
7 @paragraphindent 0
8 @c For TeX only.
9 @iftex
10 @c I hate putting "@noindent" in front of every paragraph.
11 @parindent=0pt
12 @end iftex
13 @c %**end of header
14
15 @direntry
16 * CLN: (cln).                       Class Library for Numbers (C++).
17 @end direntry
18
19 @c My own index.
20 @defindex my
21 @c Don't need the other types of indices.
22 @synindex cp my
23 @synindex fn my
24 @synindex vr my
25 @synindex ky my
26 @synindex pg my
27 @synindex tp my
28
29
30 @c For `info' only.
31 @ifinfo
32 This file documents @sc{cln}, a Class Library for Numbers.
33
34 Published by Bruno Haible, @code{<haible@@clisp.cons.org>} and
35 Richard Kreckel, @code{<kreckel@@ginac.de>}.
36
37 Copyright (C)  Bruno Haible 1995, 1996, 1997, 1998, 1999, 2000, 2001.
38 Copyright (C)  Richard Kreckel 2000, 2001, 2002.
39
40 Permission is granted to make and distribute verbatim copies of
41 this manual provided the copyright notice and this permission notice
42 are preserved on all copies.
43
44 @ignore
45 Permission is granted to process this file through TeX and print the
46 results, provided the printed document carries copying permission
47 notice identical to this one except for the removal of this paragraph
48 (this paragraph not being relevant to the printed manual).
49
50 @end ignore
51 Permission is granted to copy and distribute modified versions of this
52 manual under the conditions for verbatim copying, provided that the entire
53 resulting derived work is distributed under the terms of a permission
54 notice identical to this one.
55
56 Permission is granted to copy and distribute translations of this manual
57 into another language, under the above conditions for modified versions,
58 except that this permission notice may be stated in a translation approved
59 by the author.
60 @end ifinfo
61
62
63 @c For TeX only.
64 @c prevent ugly black rectangles on overfull hbox lines:
65 @finalout
66 @titlepage
67 @title CLN, a Class Library for Numbers
68
69 @author by Bruno Haible
70 @page
71 @vskip 0pt plus 1filll
72 Copyright @copyright{} Bruno Haible 1995, 1996, 1997, 1998, 1999, 2000, 2001.
73 @sp 0
74 Copyright @copyright{} Richard Kreckel 2000, 2001.
75
76 @sp 2
77 Published by Bruno Haible, @code{<haible@@clisp.cons.org>} and
78 Richard Kreckel, @code{<kreckel@@ginac.de>}.
79
80 Permission is granted to make and distribute verbatim copies of
81 this manual provided the copyright notice and this permission notice
82 are preserved on all copies.
83
84 Permission is granted to copy and distribute modified versions of this
85 manual under the conditions for verbatim copying, provided that the entire
86 resulting derived work is distributed under the terms of a permission
87 notice identical to this one.
88
89 Permission is granted to copy and distribute translations of this manual
90 into another language, under the above conditions for modified versions,
91 except that this permission notice may be stated in a translation approved
92 by the author.
93
94 @end titlepage
95 @page
96
97
98 @node Top, Introduction, (dir), (dir)
99
100 @c @menu
101 @c * Introduction::                Introduction
102 @c @end menu
103
104
105 @node Introduction, Top, Top, Top
106 @comment node-name, next, previous, up
107 @chapter Introduction
108
109 @noindent
110 CLN is a library for computations with all kinds of numbers.
111 It has a rich set of number classes:
112
113 @itemize @bullet
114 @item
115 Integers (with unlimited precision),
116
117 @item
118 Rational numbers,
119
120 @item
121 Floating-point numbers:
122
123 @itemize @minus
124 @item
125 Short float,
126 @item
127 Single float,
128 @item
129 Double float,
130 @item
131 Long float (with unlimited precision),
132 @end itemize
133
134 @item
135 Complex numbers,
136
137 @item
138 Modular integers (integers modulo a fixed integer),
139
140 @item
141 Univariate polynomials.
142 @end itemize
143
144 @noindent
145 The subtypes of the complex numbers among these are exactly the
146 types of numbers known to the Common Lisp language. Therefore
147 @code{CLN} can be used for Common Lisp implementations, giving
148 @samp{CLN} another meaning: it becomes an abbreviation of
149 ``Common Lisp Numbers''.
150
151 @noindent
152 The CLN package implements
153
154 @itemize @bullet
155 @item
156 Elementary functions (@code{+}, @code{-}, @code{*}, @code{/}, @code{sqrt},
157 comparisons, @dots{}),
158
159 @item
160 Logical functions (logical @code{and}, @code{or}, @code{not}, @dots{}),
161
162 @item
163 Transcendental functions (exponential, logarithmic, trigonometric, hyperbolic
164 functions and their inverse functions).
165 @end itemize
166
167 @noindent
168 CLN is a C++ library. Using C++ as an implementation language provides
169
170 @itemize @bullet
171 @item
172 efficiency: it compiles to machine code,
173 @item
174 type safety: the C++ compiler knows about the number types and complains
175 if, for example, you try to assign a float to an integer variable.
176 @item
177 algebraic syntax: You can use the @code{+}, @code{-}, @code{*}, @code{=},
178 @code{==}, @dots{} operators as in C or C++.
179 @end itemize
180
181 @noindent
182 CLN is memory efficient:
183
184 @itemize @bullet
185 @item
186 Small integers and short floats are immediate, not heap allocated.
187 @item
188 Heap-allocated memory is reclaimed through an automatic, non-interruptive
189 garbage collection.
190 @end itemize
191
192 @noindent
193 CLN is speed efficient:
194
195 @itemize @bullet
196 @item
197 The kernel of CLN has been written in assembly language for some CPUs
198 (@code{i386}, @code{m68k}, @code{sparc}, @code{mips}, @code{arm}).
199 @item
200 @cindex GMP
201 On all CPUs, CLN may be configured to use the superefficient low-level
202 routines from GNU GMP version 3.
203 @item
204 It uses Karatsuba multiplication, which is significantly faster
205 for large numbers than the standard multiplication algorithm.
206 @item
207 For very large numbers (more than 12000 decimal digits), it uses
208 @iftex
209 Sch{@"o}nhage-Strassen
210 @cindex Sch{@"o}nhage-Strassen multiplication
211 @end iftex
212 @ifinfo
213 Schönhage-Strassen
214 @cindex Schönhage-Strassen multiplication
215 @end ifinfo
216 multiplication, which is an asymptotically optimal multiplication
217 algorithm, for multiplication, division and radix conversion.
218 @end itemize
219
220 @noindent
221 CLN aims at being easily integrated into larger software packages:
222
223 @itemize @bullet
224 @item
225 The garbage collection imposes no burden on the main application.
226 @item
227 The library provides hooks for memory allocation and exceptions.
228 @item
229 @cindex namespace
230 All non-macro identifiers are hidden in namespace @code{cln} in 
231 order to avoid name clashes.
232 @end itemize
233
234
235 @chapter Installation
236
237 This section describes how to install the CLN package on your system.
238
239
240 @section Prerequisites
241
242 @subsection C++ compiler
243
244 To build CLN, you need a C++ compiler.
245 Actually, you need GNU @code{g++ 2.95} or newer.
246
247 The following C++ features are used:
248 classes, member functions, overloading of functions and operators,
249 constructors and destructors, inline, const, multiple inheritance,
250 templates and namespaces.
251
252 The following C++ features are not used:
253 @code{new}, @code{delete}, virtual inheritance, exceptions.
254
255 CLN relies on semi-automatic ordering of initializations
256 of static and global variables, a feature which I could
257 implement for GNU g++ only.
258
259 @ignore
260 @comment cl_modules.h requires g++
261 Therefore nearly any C++ compiler will do.
262
263 The following C++ compilers are known to compile CLN:
264 @itemize @minus
265 @item
266 GNU @code{g++ 2.7.0}, @code{g++ 2.7.2}
267 @item
268 SGI @code{CC 4}
269 @end itemize
270
271 The following C++ compilers are known to be unusable for CLN:
272 @itemize @minus
273 @item
274 On SunOS 4, @code{CC 2.1}, because it doesn't grok @code{//} comments
275 in lines containing @code{#if} or @code{#elif} preprocessor commands.
276 @item
277 On AIX 3.2.5, @code{xlC}, because it doesn't grok the template syntax
278 in @code{cl_SV.h} and @code{cl_GV.h}, because it forces most class types
279 to have default constructors, and because it probably miscompiles the
280 integer multiplication routines.
281 @item
282 On AIX 4.1.4.0, @code{xlC}, because when optimizing, it sometimes converts
283 @code{short}s to @code{int}s by zero-extend.
284 @item
285 GNU @code{g++ 2.5.8}
286 @item
287 On HPPA, GNU @code{g++ 2.7.x}, because the semi-automatic ordering of
288 initializations will not work.
289 @end itemize
290 @end ignore
291
292 @subsection Make utility
293 @cindex @code{make}
294
295 To build CLN, you also need to have GNU @code{make} installed.
296
297 Only GNU @code{make} 3.77 is unusable for CLN; other versions work fine.
298
299 @subsection Sed utility
300 @cindex @code{sed}
301
302 To build CLN on HP-UX, you also need to have GNU @code{sed} installed.
303 This is because the libtool script, which creates the CLN library, relies
304 on @code{sed}, and the vendor's @code{sed} utility on these systems is too
305 limited.
306
307
308 @section Building the library
309
310 As with any autoconfiguring GNU software, installation is as easy as this:
311
312 @example
313 $ ./configure
314 $ make
315 $ make check
316 @end example
317
318 If on your system, @samp{make} is not GNU @code{make}, you have to use
319 @samp{gmake} instead of @samp{make} above.
320
321 The @code{configure} command checks out some features of your system and
322 C++ compiler and builds the @code{Makefile}s. The @code{make} command
323 builds the library. This step may take about an hour on an average workstation.
324 The @code{make check} runs some test to check that no important subroutine
325 has been miscompiled.
326
327 The @code{configure} command accepts options. To get a summary of them, try
328
329 @example
330 $ ./configure --help
331 @end example
332
333 Some of the options are explained in detail in the @samp{INSTALL.generic} file.
334
335 You can specify the C compiler, the C++ compiler and their options through
336 the following environment variables when running @code{configure}:
337
338 @table @code
339 @item CC
340 Specifies the C compiler.
341
342 @item CFLAGS
343 Flags to be given to the C compiler when compiling programs (not when linking).
344
345 @item CXX
346 Specifies the C++ compiler.
347
348 @item CXXFLAGS
349 Flags to be given to the C++ compiler when compiling programs (not when linking).
350 @end table
351
352 Examples:
353
354 @example
355 $ CC="gcc" CFLAGS="-O" CXX="g++" CXXFLAGS="-O" ./configure
356 $ CC="gcc -V egcs-2.91.60" CFLAGS="-O -g" \
357   CXX="g++ -V egcs-2.91.60" CXXFLAGS="-O -g" ./configure
358 $ CC="gcc -V 2.95.2" CFLAGS="-O2 -fno-exceptions" \
359   CXX="g++ -V 2.95.2" CFLAGS="-O2 -fno-exceptions" ./configure
360 $ CC="gcc -V 3.0.4" CFLAGS="-O2 -finline-limit=1000 -fno-exceptions" \
361   CXX="g++ -V 3.0.4" CFLAGS="-O2 -finline-limit=1000 -fno-exceptions" \
362   ./configure
363 @end example
364 @ignore
365 @comment cl_modules.h requires g++
366 You should not mix GNU and non-GNU compilers. So, if @code{CXX} is a non-GNU
367 compiler, @code{CC} should be set to a non-GNU compiler as well. Examples:
368
369 @example
370 $ CC="cc" CFLAGS="-O" CXX="CC" CXXFLAGS="-O" ./configure
371 $ CC="gcc -V 2.7.0" CFLAGS="-g" CXX="g++ -V 2.7.0" CXXFLAGS="-g" ./configure
372 @end example
373
374 On SGI Irix 5, if you wish not to use @code{g++}:
375
376 @example
377 $ CC="cc" CFLAGS="-O" CXX="CC" CXXFLAGS="-O -Olimit 16000" ./configure
378 @end example
379
380 On SGI Irix 6, if you wish not to use @code{g++}:
381
382 @example
383 $ CC="cc -32" CFLAGS="-O" CXX="CC -32" CXXFLAGS="-O -Olimit 34000" \
384   ./configure --without-gmp
385 $ CC="cc -n32" CFLAGS="-O" CXX="CC -n32" CXXFLAGS="-O \
386   -OPT:const_copy_limit=32400 -OPT:global_limit=32400 -OPT:fprop_limit=4000" \
387   ./configure --without-gmp
388 @end example
389 @end ignore
390
391 Note that for these environment variables to take effect, you have to set
392 them (assuming a Bourne-compatible shell) on the same line as the
393 @code{configure} command. If you made the settings in earlier shell
394 commands, you have to @code{export} the environment variables before
395 calling @code{configure}. In a @code{csh} shell, you have to use the
396 @samp{setenv} command for setting each of the environment variables.
397
398 Currently CLN works only with the GNU @code{g++} compiler, and only in
399 optimizing mode. So you should specify at least @code{-O} in the CXXFLAGS,
400 or no CXXFLAGS at all. (If CXXFLAGS is not set, CLN will use @code{-O}.)
401
402 If you use @code{g++} 3.0.x or 3.1, I recommend adding
403 @samp{-finline-limit=1000} to the CXXFLAGS. This is essential for good code.
404
405 If you use @code{g++} gcc-2.95.x or gcc-3.0.x , I recommend adding
406 @samp{-fno-exceptions} to the CXXFLAGS. This will likely generate better code.
407
408 If you use @code{g++} from gcc-2.95.x on Sparc, add either @samp{-O},
409 @samp{-O1} or @samp{-O2 -fno-schedule-insns} to the CXXFLAGS. With full
410 @samp{-O2}, @code{g++} miscompiles the division routines. If you use 
411 @code{g++} older than 2.95.3 on Sparc you should also specify 
412 @samp{--disable-shared} because of bad code produced in the shared 
413 library. 
414
415 If you use @code{g++} on OSF/1 or Tru64 using gcc-2.95.x, you should
416 specify @samp{--disable-shared} because of linker problems with
417 duplicate symbols in shared libraries.  If you use @code{g++} from
418 gcc-3.0.n, with n larger than 1, you should @emph{not} add
419 @samp{-fno-exceptions} to the CXXFLAGS, since that will generate wrong
420 code (gcc-3.1.0 is okay again, as is gcc-3.0.0).
421
422 If you use @code{g++} from gcc-3.1, it will need 235 MB of virtual memory.
423 You might need some swap space if your machine doesn't have 512 MB of RAM.
424
425 By default, both a shared and a static library are built.  You can build
426 CLN as a static (or shared) library only, by calling @code{configure} with
427 the option @samp{--disable-shared} (or @samp{--disable-static}).  While
428 shared libraries are usually more convenient to use, they may not work
429 on all architectures.  Try disabling them if you run into linker
430 problems.  Also, they are generally somewhat slower than static
431 libraries so runtime-critical applications should be linked statically.
432
433 If you use @code{g++} from gcc-3.1 with option @samp{-g}, you will need
434 some disk space: 335 MB for building as both a shared and a static library,
435 or 130 MB when building as a shared library only.
436
437
438 @subsection Using the GNU MP Library
439 @cindex GMP
440
441 Starting with version 1.1, CLN may be configured to make use of a
442 preinstalled @code{gmp} library.  Please make sure that you have at
443 least @code{gmp} version 3.0 installed since earlier versions are
444 unsupported and likely not to work.  Enabling this feature by calling
445 @code{configure} with the option @samp{--with-gmp} is known to be quite
446 a boost for CLN's performance.
447
448 If you have installed the @code{gmp} library and its header file in
449 some place where your compiler cannot find it by default, you must help
450 @code{configure} by setting @code{CPPFLAGS} and @code{LDFLAGS}.  Here is
451 an example:
452
453 @example
454 $ CC="gcc" CFLAGS="-O2" CXX="g++" CXXFLAGS="-O2 -fno-exceptions" \
455   CPPFLAGS="-I/opt/gmp/include" LDFLAGS="-L/opt/gmp/lib" ./configure --with-gmp
456 @end example
457
458
459 @section Installing the library
460 @cindex installation
461
462 As with any autoconfiguring GNU software, installation is as easy as this:
463
464 @example
465 $ make install
466 @end example
467
468 The @samp{make install} command installs the library and the include files
469 into public places (@file{/usr/local/lib/} and @file{/usr/local/include/},
470 if you haven't specified a @code{--prefix} option to @code{configure}).
471 This step may require superuser privileges.
472
473 If you have already built the library and wish to install it, but didn't
474 specify @code{--prefix=@dots{}} at configure time, just re-run
475 @code{configure}, giving it the same options as the first time, plus
476 the @code{--prefix=@dots{}} option.
477
478
479 @section Cleaning up
480
481 You can remove system-dependent files generated by @code{make} through
482
483 @example
484 $ make clean
485 @end example
486
487 You can remove all files generated by @code{make}, thus reverting to a
488 virgin distribution of CLN, through
489
490 @example
491 $ make distclean
492 @end example
493
494
495 @chapter Ordinary number types
496
497 CLN implements the following class hierarchy:
498
499 @example
500                         Number
501                       cl_number
502                     <cln/number.h>
503                           |
504                           |
505                  Real or complex number
506                         cl_N
507                     <cln/complex.h>
508                           |
509                           |
510                      Real number
511                         cl_R
512                      <cln/real.h>
513                           |
514       +-------------------+-------------------+
515       |                                       |
516 Rational number                     Floating-point number
517     cl_RA                                   cl_F
518 <cln/rational.h>                         <cln/float.h>
519       |                                       |
520       |                +--------------+--------------+--------------+
521    Integer             |              |              |              |
522     cl_I          Short-Float    Single-Float   Double-Float    Long-Float
523 <cln/integer.h>      cl_SF          cl_FF          cl_DF          cl_LF
524                  <cln/sfloat.h> <cln/ffloat.h> <cln/dfloat.h> <cln/lfloat.h>
525 @end example
526
527 @cindex @code{cl_number}
528 @cindex abstract class
529 The base class @code{cl_number} is an abstract base class.
530 It is not useful to declare a variable of this type except if you want
531 to completely disable compile-time type checking and use run-time type
532 checking instead.
533
534 @cindex @code{cl_N}
535 @cindex real number
536 @cindex complex number
537 The class @code{cl_N} comprises real and complex numbers. There is
538 no special class for complex numbers since complex numbers with imaginary
539 part @code{0} are automatically converted to real numbers.
540
541 @cindex @code{cl_R}
542 The class @code{cl_R} comprises real numbers of different kinds. It is an
543 abstract class.
544
545 @cindex @code{cl_RA}
546 @cindex rational number
547 @cindex integer
548 The class @code{cl_RA} comprises exact real numbers: rational numbers, including
549 integers. There is no special class for non-integral rational numbers
550 since rational numbers with denominator @code{1} are automatically converted
551 to integers.
552
553 @cindex @code{cl_F}
554 The class @code{cl_F} implements floating-point approximations to real numbers.
555 It is an abstract class.
556
557
558 @section Exact numbers
559 @cindex exact number
560
561 Some numbers are represented as exact numbers: there is no loss of information
562 when such a number is converted from its mathematical value to its internal
563 representation. On exact numbers, the elementary operations (@code{+},
564 @code{-}, @code{*}, @code{/}, comparisons, @dots{}) compute the completely
565 correct result.
566
567 In CLN, the exact numbers are:
568
569 @itemize @bullet
570 @item
571 rational numbers (including integers),
572 @item
573 complex numbers whose real and imaginary parts are both rational numbers.
574 @end itemize
575
576 Rational numbers are always normalized to the form
577 @code{@var{numerator}/@var{denominator}} where the numerator and denominator
578 are coprime integers and the denominator is positive. If the resulting
579 denominator is @code{1}, the rational number is converted to an integer.
580
581 @cindex immediate numbers
582 Small integers (typically in the range @code{-2^29}@dots{}@code{2^29-1},
583 for 32-bit machines) are especially efficient, because they consume no heap
584 allocation. Otherwise the distinction between these immediate integers
585 (called ``fixnums'') and heap allocated integers (called ``bignums'')
586 is completely transparent.
587
588
589 @section Floating-point numbers
590 @cindex floating-point number
591
592 Not all real numbers can be represented exactly. (There is an easy mathematical
593 proof for this: Only a countable set of numbers can be stored exactly in
594 a computer, even if one assumes that it has unlimited storage. But there
595 are uncountably many real numbers.) So some approximation is needed.
596 CLN implements ordinary floating-point numbers, with mantissa and exponent.
597
598 @cindex rounding error
599 The elementary operations (@code{+}, @code{-}, @code{*}, @code{/}, @dots{})
600 only return approximate results. For example, the value of the expression
601 @code{(cl_F) 0.3 + (cl_F) 0.4} prints as @samp{0.70000005}, not as
602 @samp{0.7}. Rounding errors like this one are inevitable when computing
603 with floating-point numbers.
604
605 Nevertheless, CLN rounds the floating-point results of the operations @code{+},
606 @code{-}, @code{*}, @code{/}, @code{sqrt} according to the ``round-to-even''
607 rule: It first computes the exact mathematical result and then returns the
608 floating-point number which is nearest to this. If two floating-point numbers
609 are equally distant from the ideal result, the one with a @code{0} in its least
610 significant mantissa bit is chosen.
611
612 Similarly, testing floating point numbers for equality @samp{x == y}
613 is gambling with random errors. Better check for @samp{abs(x - y) < epsilon}
614 for some well-chosen @code{epsilon}.
615
616 Floating point numbers come in four flavors:
617
618 @itemize @bullet
619 @item
620 @cindex @code{cl_SF}
621 Short floats, type @code{cl_SF}.
622 They have 1 sign bit, 8 exponent bits (including the exponent's sign),
623 and 17 mantissa bits (including the ``hidden'' bit).
624 They don't consume heap allocation.
625
626 @item
627 @cindex @code{cl_FF}
628 Single floats, type @code{cl_FF}.
629 They have 1 sign bit, 8 exponent bits (including the exponent's sign),
630 and 24 mantissa bits (including the ``hidden'' bit).
631 In CLN, they are represented as IEEE single-precision floating point numbers.
632 This corresponds closely to the C/C++ type @samp{float}.
633
634 @item
635 @cindex @code{cl_DF}
636 Double floats, type @code{cl_DF}.
637 They have 1 sign bit, 11 exponent bits (including the exponent's sign),
638 and 53 mantissa bits (including the ``hidden'' bit).
639 In CLN, they are represented as IEEE double-precision floating point numbers.
640 This corresponds closely to the C/C++ type @samp{double}.
641
642 @item
643 @cindex @code{cl_LF}
644 Long floats, type @code{cl_LF}.
645 They have 1 sign bit, 32 exponent bits (including the exponent's sign),
646 and n mantissa bits (including the ``hidden'' bit), where n >= 64.
647 The precision of a long float is unlimited, but once created, a long float
648 has a fixed precision. (No ``lazy recomputation''.)
649 @end itemize
650
651 Of course, computations with long floats are more expensive than those
652 with smaller floating-point formats.
653
654 CLN does not implement features like NaNs, denormalized numbers and
655 gradual underflow. If the exponent range of some floating-point type
656 is too limited for your application, choose another floating-point type
657 with larger exponent range.
658
659 @cindex @code{cl_F}
660 As a user of CLN, you can forget about the differences between the
661 four floating-point types and just declare all your floating-point
662 variables as being of type @code{cl_F}. This has the advantage that
663 when you change the precision of some computation (say, from @code{cl_DF}
664 to @code{cl_LF}), you don't have to change the code, only the precision
665 of the initial values. Also, many transcendental functions have been
666 declared as returning a @code{cl_F} when the argument is a @code{cl_F},
667 but such declarations are missing for the types @code{cl_SF}, @code{cl_FF},
668 @code{cl_DF}, @code{cl_LF}. (Such declarations would be wrong if
669 the floating point contagion rule happened to change in the future.)
670
671
672 @section Complex numbers
673 @cindex complex number
674
675 Complex numbers, as implemented by the class @code{cl_N}, have a real
676 part and an imaginary part, both real numbers. A complex number whose
677 imaginary part is the exact number @code{0} is automatically converted
678 to a real number.
679
680 Complex numbers can arise from real numbers alone, for example
681 through application of @code{sqrt} or transcendental functions.
682
683
684 @section Conversions
685 @cindex conversion
686
687 Conversions from any class to any its superclasses (``base classes'' in
688 C++ terminology) is done automatically.
689
690 Conversions from the C built-in types @samp{long} and @samp{unsigned long}
691 are provided for the classes @code{cl_I}, @code{cl_RA}, @code{cl_R},
692 @code{cl_N} and @code{cl_number}.
693
694 Conversions from the C built-in types @samp{int} and @samp{unsigned int}
695 are provided for the classes @code{cl_I}, @code{cl_RA}, @code{cl_R},
696 @code{cl_N} and @code{cl_number}. However, these conversions emphasize
697 efficiency. Their range is therefore limited:
698
699 @itemize @minus
700 @item
701 The conversion from @samp{int} works only if the argument is < 2^29 and > -2^29.
702 @item
703 The conversion from @samp{unsigned int} works only if the argument is < 2^29.
704 @end itemize
705
706 In a declaration like @samp{cl_I x = 10;} the C++ compiler is able to
707 do the conversion of @code{10} from @samp{int} to @samp{cl_I} at compile time
708 already. On the other hand, code like @samp{cl_I x = 1000000000;} is
709 in error.
710 So, if you want to be sure that an @samp{int} whose magnitude is not guaranteed
711 to be < 2^29 is correctly converted to a @samp{cl_I}, first convert it to a
712 @samp{long}. Similarly, if a large @samp{unsigned int} is to be converted to a
713 @samp{cl_I}, first convert it to an @samp{unsigned long}.
714
715 Conversions from the C built-in type @samp{float} are provided for the classes
716 @code{cl_FF}, @code{cl_F}, @code{cl_R}, @code{cl_N} and @code{cl_number}.
717
718 Conversions from the C built-in type @samp{double} are provided for the classes
719 @code{cl_DF}, @code{cl_F}, @code{cl_R}, @code{cl_N} and @code{cl_number}.
720
721 Conversions from @samp{const char *} are provided for the classes
722 @code{cl_I}, @code{cl_RA},
723 @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}, @code{cl_F},
724 @code{cl_R}, @code{cl_N}.
725 The easiest way to specify a value which is outside of the range of the
726 C++ built-in types is therefore to specify it as a string, like this:
727 @cindex Rubik's cube
728 @example
729    cl_I order_of_rubiks_cube_group = "43252003274489856000";
730 @end example
731 Note that this conversion is done at runtime, not at compile-time.
732
733 Conversions from @code{cl_I} to the C built-in types @samp{int},
734 @samp{unsigned int}, @samp{long}, @samp{unsigned long} are provided through
735 the functions
736
737 @table @code
738 @item int cl_I_to_int (const cl_I& x)
739 @cindex @code{cl_I_to_int ()}
740 @itemx unsigned int cl_I_to_uint (const cl_I& x)
741 @cindex @code{cl_I_to_uint ()}
742 @itemx long cl_I_to_long (const cl_I& x)
743 @cindex @code{cl_I_to_long ()}
744 @itemx unsigned long cl_I_to_ulong (const cl_I& x)
745 @cindex @code{cl_I_to_ulong ()}
746 Returns @code{x} as element of the C type @var{ctype}. If @code{x} is not
747 representable in the range of @var{ctype}, a runtime error occurs.
748 @end table
749
750 Conversions from the classes @code{cl_I}, @code{cl_RA},
751 @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}, @code{cl_F} and
752 @code{cl_R}
753 to the C built-in types @samp{float} and @samp{double} are provided through
754 the functions
755
756 @table @code
757 @item float float_approx (const @var{type}& x)
758 @cindex @code{float_approx ()}
759 @itemx double double_approx (const @var{type}& x)
760 @cindex @code{double_approx ()}
761 Returns an approximation of @code{x} of C type @var{ctype}.
762 If @code{abs(x)} is too close to 0 (underflow), 0 is returned.
763 If @code{abs(x)} is too large (overflow), an IEEE infinity is returned.
764 @end table
765
766 Conversions from any class to any of its subclasses (``derived classes'' in
767 C++ terminology) are not provided. Instead, you can assert and check
768 that a value belongs to a certain subclass, and return it as element of that
769 class, using the @samp{As} and @samp{The} macros.
770 @cindex @code{As()()}
771 @code{As(@var{type})(@var{value})} checks that @var{value} belongs to
772 @var{type} and returns it as such.
773 @cindex @code{The()()}
774 @code{The(@var{type})(@var{value})} assumes that @var{value} belongs to
775 @var{type} and returns it as such. It is your responsibility to ensure
776 that this assumption is valid.  Since macros and namespaces don't go
777 together well, there is an equivalent to @samp{The}: the template
778 @samp{the}.
779
780 Example:
781
782 @example
783 @group
784    cl_I x = @dots{};
785    if (!(x >= 0)) abort();
786    cl_I ten_x_a = The(cl_I)(expt(10,x)); // If x >= 0, 10^x is an integer.
787                 // In general, it would be a rational number.
788    cl_I ten_x_b = the<cl_I>(expt(10,x)); // The same as above.
789 @end group
790 @end example
791
792
793 @chapter Functions on numbers
794
795 Each of the number classes declares its mathematical operations in the
796 corresponding include file. For example, if your code operates with
797 objects of type @code{cl_I}, it should @code{#include <cln/integer.h>}.
798
799
800 @section Constructing numbers
801
802 Here is how to create number objects ``from nothing''.
803
804
805 @subsection Constructing integers
806
807 @code{cl_I} objects are most easily constructed from C integers and from
808 strings. See @ref{Conversions}.
809
810
811 @subsection Constructing rational numbers
812
813 @code{cl_RA} objects can be constructed from strings. The syntax
814 for rational numbers is described in @ref{Internal and printed representation}.
815 Another standard way to produce a rational number is through application
816 of @samp{operator /} or @samp{recip} on integers.
817
818
819 @subsection Constructing floating-point numbers
820
821 @code{cl_F} objects with low precision are most easily constructed from
822 C @samp{float} and @samp{double}. See @ref{Conversions}.
823
824 To construct a @code{cl_F} with high precision, you can use the conversion
825 from @samp{const char *}, but you have to specify the desired precision
826 within the string. (See @ref{Internal and printed representation}.)
827 Example:
828 @example
829    cl_F e = "0.271828182845904523536028747135266249775724709369996e+1_40";
830 @end example
831 will set @samp{e} to the given value, with a precision of 40 decimal digits.
832
833 The programmatic way to construct a @code{cl_F} with high precision is
834 through the @code{cl_float} conversion function, see
835 @ref{Conversion to floating-point numbers}. For example, to compute
836 @code{e} to 40 decimal places, first construct 1.0 to 40 decimal places
837 and then apply the exponential function:
838 @example
839    float_format_t precision = float_format(40);
840    cl_F e = exp(cl_float(1,precision));
841 @end example
842
843
844 @subsection Constructing complex numbers
845
846 Non-real @code{cl_N} objects are normally constructed through the function
847 @example
848    cl_N complex (const cl_R& realpart, const cl_R& imagpart)
849 @end example
850 See @ref{Elementary complex functions}.
851
852
853 @section Elementary functions
854
855 Each of the classes @code{cl_N}, @code{cl_R}, @code{cl_RA}, @code{cl_I},
856 @code{cl_F}, @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}
857 defines the following operations:
858
859 @table @code
860 @item @var{type} operator + (const @var{type}&, const @var{type}&)
861 @cindex @code{operator + ()}
862 Addition.
863
864 @item @var{type} operator - (const @var{type}&, const @var{type}&)
865 @cindex @code{operator - ()}
866 Subtraction.
867
868 @item @var{type} operator - (const @var{type}&)
869 Returns the negative of the argument.
870
871 @item @var{type} plus1 (const @var{type}& x)
872 @cindex @code{plus1 ()}
873 Returns @code{x + 1}.
874
875 @item @var{type} minus1 (const @var{type}& x)
876 @cindex @code{minus1 ()}
877 Returns @code{x - 1}.
878
879 @item @var{type} operator * (const @var{type}&, const @var{type}&)
880 @cindex @code{operator * ()}
881 Multiplication.
882
883 @item @var{type} square (const @var{type}& x)
884 @cindex @code{square ()}
885 Returns @code{x * x}.
886 @end table
887
888 Each of the classes @code{cl_N}, @code{cl_R}, @code{cl_RA},
889 @code{cl_F}, @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}
890 defines the following operations:
891
892 @table @code
893 @item @var{type} operator / (const @var{type}&, const @var{type}&)
894 @cindex @code{operator / ()}
895 Division.
896
897 @item @var{type} recip (const @var{type}&)
898 @cindex @code{recip ()}
899 Returns the reciprocal of the argument.
900 @end table
901
902 The class @code{cl_I} doesn't define a @samp{/} operation because
903 in the C/C++ language this operator, applied to integral types,
904 denotes the @samp{floor} or @samp{truncate} operation (which one of these,
905 is implementation dependent). (@xref{Rounding functions}.)
906 Instead, @code{cl_I} defines an ``exact quotient'' function:
907
908 @table @code
909 @item cl_I exquo (const cl_I& x, const cl_I& y)
910 @cindex @code{exquo ()}
911 Checks that @code{y} divides @code{x}, and returns the quotient @code{x}/@code{y}.
912 @end table
913
914 The following exponentiation functions are defined:
915
916 @table @code
917 @item cl_I expt_pos (const cl_I& x, const cl_I& y)
918 @cindex @code{expt_pos ()}
919 @itemx cl_RA expt_pos (const cl_RA& x, const cl_I& y)
920 @code{y} must be > 0. Returns @code{x^y}.
921
922 @item cl_RA expt (const cl_RA& x, const cl_I& y)
923 @cindex @code{expt ()}
924 @itemx cl_R expt (const cl_R& x, const cl_I& y)
925 @itemx cl_N expt (const cl_N& x, const cl_I& y)
926 Returns @code{x^y}.
927 @end table
928
929 Each of the classes @code{cl_R}, @code{cl_RA}, @code{cl_I},
930 @code{cl_F}, @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}
931 defines the following operation:
932
933 @table @code
934 @item @var{type} abs (const @var{type}& x)
935 @cindex @code{abs ()}
936 Returns the absolute value of @code{x}.
937 This is @code{x} if @code{x >= 0}, and @code{-x} if @code{x <= 0}.
938 @end table
939
940 The class @code{cl_N} implements this as follows:
941
942 @table @code
943 @item cl_R abs (const cl_N x)
944 Returns the absolute value of @code{x}.
945 @end table
946
947 Each of the classes @code{cl_N}, @code{cl_R}, @code{cl_RA}, @code{cl_I},
948 @code{cl_F}, @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}
949 defines the following operation:
950
951 @table @code
952 @item @var{type} signum (const @var{type}& x)
953 @cindex @code{signum ()}
954 Returns the sign of @code{x}, in the same number format as @code{x}.
955 This is defined as @code{x / abs(x)} if @code{x} is non-zero, and
956 @code{x} if @code{x} is zero. If @code{x} is real, the value is either
957 0 or 1 or -1.
958 @end table
959
960
961 @section Elementary rational functions
962
963 Each of the classes @code{cl_RA}, @code{cl_I} defines the following operations:
964
965 @table @code
966 @item cl_I numerator (const @var{type}& x)
967 @cindex @code{numerator ()}
968 Returns the numerator of @code{x}.
969
970 @item cl_I denominator (const @var{type}& x)
971 @cindex @code{denominator ()}
972 Returns the denominator of @code{x}.
973 @end table
974
975 The numerator and denominator of a rational number are normalized in such
976 a way that they have no factor in common and the denominator is positive.
977
978
979 @section Elementary complex functions
980
981 The class @code{cl_N} defines the following operation:
982
983 @table @code
984 @item cl_N complex (const cl_R& a, const cl_R& b)
985 @cindex @code{complex ()}
986 Returns the complex number @code{a+bi}, that is, the complex number with
987 real part @code{a} and imaginary part @code{b}.
988 @end table
989
990 Each of the classes @code{cl_N}, @code{cl_R} defines the following operations:
991
992 @table @code
993 @item cl_R realpart (const @var{type}& x)
994 @cindex @code{realpart ()}
995 Returns the real part of @code{x}.
996
997 @item cl_R imagpart (const @var{type}& x)
998 @cindex @code{imagpart ()}
999 Returns the imaginary part of @code{x}.
1000
1001 @item @var{type} conjugate (const @var{type}& x)
1002 @cindex @code{conjugate ()}
1003 Returns the complex conjugate of @code{x}.
1004 @end table
1005
1006 We have the relations
1007
1008 @itemize @asis
1009 @item
1010 @code{x = complex(realpart(x), imagpart(x))}
1011 @item
1012 @code{conjugate(x) = complex(realpart(x), -imagpart(x))}
1013 @end itemize
1014
1015
1016 @section Comparisons
1017 @cindex comparison
1018
1019 Each of the classes @code{cl_N}, @code{cl_R}, @code{cl_RA}, @code{cl_I},
1020 @code{cl_F}, @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}
1021 defines the following operations:
1022
1023 @table @code
1024 @item bool operator == (const @var{type}&, const @var{type}&)
1025 @cindex @code{operator == ()}
1026 @itemx bool operator != (const @var{type}&, const @var{type}&)
1027 @cindex @code{operator != ()}
1028 Comparison, as in C and C++.
1029
1030 @item uint32 equal_hashcode (const @var{type}&)
1031 @cindex @code{equal_hashcode ()}
1032 Returns a 32-bit hash code that is the same for any two numbers which are
1033 the same according to @code{==}. This hash code depends on the number's value,
1034 not its type or precision.
1035
1036 @item cl_boolean zerop (const @var{type}& x)
1037 @cindex @code{zerop ()}
1038 Compare against zero: @code{x == 0}
1039 @end table
1040
1041 Each of the classes @code{cl_R}, @code{cl_RA}, @code{cl_I},
1042 @code{cl_F}, @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}
1043 defines the following operations:
1044
1045 @table @code
1046 @item cl_signean compare (const @var{type}& x, const @var{type}& y)
1047 @cindex @code{compare ()}
1048 Compares @code{x} and @code{y}. Returns +1 if @code{x}>@code{y},
1049 -1 if @code{x}<@code{y}, 0 if @code{x}=@code{y}.
1050
1051 @item bool operator <= (const @var{type}&, const @var{type}&)
1052 @cindex @code{operator <= ()}
1053 @itemx bool operator < (const @var{type}&, const @var{type}&)
1054 @cindex @code{operator < ()}
1055 @itemx bool operator >= (const @var{type}&, const @var{type}&)
1056 @cindex @code{operator >= ()}
1057 @itemx bool operator > (const @var{type}&, const @var{type}&)
1058 @cindex @code{operator > ()}
1059 Comparison, as in C and C++.
1060
1061 @item cl_boolean minusp (const @var{type}& x)
1062 @cindex @code{minusp ()}
1063 Compare against zero: @code{x < 0}
1064
1065 @item cl_boolean plusp (const @var{type}& x)
1066 @cindex @code{plusp ()}
1067 Compare against zero: @code{x > 0}
1068
1069 @item @var{type} max (const @var{type}& x, const @var{type}& y)
1070 @cindex @code{max ()}
1071 Return the maximum of @code{x} and @code{y}.
1072
1073 @item @var{type} min (const @var{type}& x, const @var{type}& y)
1074 @cindex @code{min ()}
1075 Return the minimum of @code{x} and @code{y}.
1076 @end table
1077
1078 When a floating point number and a rational number are compared, the float
1079 is first converted to a rational number using the function @code{rational}.
1080 Since a floating point number actually represents an interval of real numbers,
1081 the result might be surprising.
1082 For example, @code{(cl_F)(cl_R)"1/3" == (cl_R)"1/3"} returns false because
1083 there is no floating point number whose value is exactly @code{1/3}.
1084
1085
1086 @section Rounding functions
1087 @cindex rounding
1088
1089 When a real number is to be converted to an integer, there is no ``best''
1090 rounding. The desired rounding function depends on the application.
1091 The Common Lisp and ISO Lisp standards offer four rounding functions:
1092
1093 @table @code
1094 @item floor(x)
1095 This is the largest integer <=@code{x}.
1096
1097 @item ceiling(x)
1098 This is the smallest integer >=@code{x}.
1099
1100 @item truncate(x)
1101 Among the integers between 0 and @code{x} (inclusive) the one nearest to @code{x}.
1102
1103 @item round(x)
1104 The integer nearest to @code{x}. If @code{x} is exactly halfway between two
1105 integers, choose the even one.
1106 @end table
1107
1108 These functions have different advantages:
1109
1110 @code{floor} and @code{ceiling} are translation invariant:
1111 @code{floor(x+n) = floor(x) + n} and @code{ceiling(x+n) = ceiling(x) + n}
1112 for every @code{x} and every integer @code{n}.
1113
1114 On the other hand, @code{truncate} and @code{round} are symmetric:
1115 @code{truncate(-x) = -truncate(x)} and @code{round(-x) = -round(x)},
1116 and furthermore @code{round} is unbiased: on the ``average'', it rounds
1117 down exactly as often as it rounds up.
1118
1119 The functions are related like this:
1120
1121 @itemize @asis
1122 @item
1123 @code{ceiling(m/n) = floor((m+n-1)/n) = floor((m-1)/n)+1}
1124 for rational numbers @code{m/n} (@code{m}, @code{n} integers, @code{n}>0), and
1125 @item
1126 @code{truncate(x) = sign(x) * floor(abs(x))}
1127 @end itemize
1128
1129 Each of the classes @code{cl_R}, @code{cl_RA},
1130 @code{cl_F}, @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}
1131 defines the following operations:
1132
1133 @table @code
1134 @item cl_I floor1 (const @var{type}& x)
1135 @cindex @code{floor1 ()}
1136 Returns @code{floor(x)}.
1137 @item cl_I ceiling1 (const @var{type}& x)
1138 @cindex @code{ceiling1 ()}
1139 Returns @code{ceiling(x)}.
1140 @item cl_I truncate1 (const @var{type}& x)
1141 @cindex @code{truncate1 ()}
1142 Returns @code{truncate(x)}.
1143 @item cl_I round1 (const @var{type}& x)
1144 @cindex @code{round1 ()}
1145 Returns @code{round(x)}.
1146 @end table
1147
1148 Each of the classes @code{cl_R}, @code{cl_RA}, @code{cl_I},
1149 @code{cl_F}, @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}
1150 defines the following operations:
1151
1152 @table @code
1153 @item cl_I floor1 (const @var{type}& x, const @var{type}& y)
1154 Returns @code{floor(x/y)}.
1155 @item cl_I ceiling1 (const @var{type}& x, const @var{type}& y)
1156 Returns @code{ceiling(x/y)}.
1157 @item cl_I truncate1 (const @var{type}& x, const @var{type}& y)
1158 Returns @code{truncate(x/y)}.
1159 @item cl_I round1 (const @var{type}& x, const @var{type}& y)
1160 Returns @code{round(x/y)}.
1161 @end table
1162
1163 These functions are called @samp{floor1}, @dots{} here instead of
1164 @samp{floor}, @dots{}, because on some systems, system dependent include
1165 files define @samp{floor} and @samp{ceiling} as macros.
1166
1167 In many cases, one needs both the quotient and the remainder of a division.
1168 It is more efficient to compute both at the same time than to perform
1169 two divisions, one for quotient and the next one for the remainder.
1170 The following functions therefore return a structure containing both
1171 the quotient and the remainder. The suffix @samp{2} indicates the number
1172 of ``return values''. The remainder is defined as follows:
1173
1174 @itemize @bullet
1175 @item
1176 for the computation of @code{quotient = floor(x)},
1177 @code{remainder = x - quotient},
1178 @item
1179 for the computation of @code{quotient = floor(x,y)},
1180 @code{remainder = x - quotient*y},
1181 @end itemize
1182
1183 and similarly for the other three operations.
1184
1185 Each of the classes @code{cl_R}, @code{cl_RA},
1186 @code{cl_F}, @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}
1187 defines the following operations:
1188
1189 @table @code
1190 @item struct @var{type}_div_t @{ cl_I quotient; @var{type} remainder; @};
1191 @itemx @var{type}_div_t floor2 (const @var{type}& x)
1192 @itemx @var{type}_div_t ceiling2 (const @var{type}& x)
1193 @itemx @var{type}_div_t truncate2 (const @var{type}& x)
1194 @itemx @var{type}_div_t round2 (const @var{type}& x)
1195 @end table
1196
1197 Each of the classes @code{cl_R}, @code{cl_RA}, @code{cl_I},
1198 @code{cl_F}, @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}
1199 defines the following operations:
1200
1201 @table @code
1202 @item struct @var{type}_div_t @{ cl_I quotient; @var{type} remainder; @};
1203 @itemx @var{type}_div_t floor2 (const @var{type}& x, const @var{type}& y)
1204 @cindex @code{floor2 ()}
1205 @itemx @var{type}_div_t ceiling2 (const @var{type}& x, const @var{type}& y)
1206 @cindex @code{ceiling2 ()}
1207 @itemx @var{type}_div_t truncate2 (const @var{type}& x, const @var{type}& y)
1208 @cindex @code{truncate2 ()}
1209 @itemx @var{type}_div_t round2 (const @var{type}& x, const @var{type}& y)
1210 @cindex @code{round2 ()}
1211 @end table
1212
1213 Sometimes, one wants the quotient as a floating-point number (of the
1214 same format as the argument, if the argument is a float) instead of as
1215 an integer. The prefix @samp{f} indicates this.
1216
1217 Each of the classes
1218 @code{cl_F}, @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}
1219 defines the following operations:
1220
1221 @table @code
1222 @item @var{type} ffloor (const @var{type}& x)
1223 @cindex @code{ffloor ()}
1224 @itemx @var{type} fceiling (const @var{type}& x)
1225 @cindex @code{fceiling ()}
1226 @itemx @var{type} ftruncate (const @var{type}& x)
1227 @cindex @code{ftruncate ()}
1228 @itemx @var{type} fround (const @var{type}& x)
1229 @cindex @code{fround ()}
1230 @end table
1231
1232 and similarly for class @code{cl_R}, but with return type @code{cl_F}.
1233
1234 The class @code{cl_R} defines the following operations:
1235
1236 @table @code
1237 @item cl_F ffloor (const @var{type}& x, const @var{type}& y)
1238 @itemx cl_F fceiling (const @var{type}& x, const @var{type}& y)
1239 @itemx cl_F ftruncate (const @var{type}& x, const @var{type}& y)
1240 @itemx cl_F fround (const @var{type}& x, const @var{type}& y)
1241 @end table
1242
1243 These functions also exist in versions which return both the quotient
1244 and the remainder. The suffix @samp{2} indicates this.
1245
1246 Each of the classes
1247 @code{cl_F}, @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}
1248 defines the following operations:
1249 @cindex @code{cl_F_fdiv_t}
1250 @cindex @code{cl_SF_fdiv_t}
1251 @cindex @code{cl_FF_fdiv_t}
1252 @cindex @code{cl_DF_fdiv_t}
1253 @cindex @code{cl_LF_fdiv_t}
1254
1255 @table @code
1256 @item struct @var{type}_fdiv_t @{ @var{type} quotient; @var{type} remainder; @};
1257 @itemx @var{type}_fdiv_t ffloor2 (const @var{type}& x)
1258 @cindex @code{ffloor2 ()}
1259 @itemx @var{type}_fdiv_t fceiling2 (const @var{type}& x)
1260 @cindex @code{fceiling2 ()}
1261 @itemx @var{type}_fdiv_t ftruncate2 (const @var{type}& x)
1262 @cindex @code{ftruncate2 ()}
1263 @itemx @var{type}_fdiv_t fround2 (const @var{type}& x)
1264 @cindex @code{fround2 ()}
1265 @end table
1266 and similarly for class @code{cl_R}, but with quotient type @code{cl_F}.
1267 @cindex @code{cl_R_fdiv_t}
1268
1269 The class @code{cl_R} defines the following operations:
1270
1271 @table @code
1272 @item struct @var{type}_fdiv_t @{ cl_F quotient; cl_R remainder; @};
1273 @itemx @var{type}_fdiv_t ffloor2 (const @var{type}& x, const @var{type}& y)
1274 @itemx @var{type}_fdiv_t fceiling2 (const @var{type}& x, const @var{type}& y)
1275 @itemx @var{type}_fdiv_t ftruncate2 (const @var{type}& x, const @var{type}& y)
1276 @itemx @var{type}_fdiv_t fround2 (const @var{type}& x, const @var{type}& y)
1277 @end table
1278
1279 Other applications need only the remainder of a division.
1280 The remainder of @samp{floor} and @samp{ffloor} is called @samp{mod}
1281 (abbreviation of ``modulo''). The remainder @samp{truncate} and
1282 @samp{ftruncate} is called @samp{rem} (abbreviation of ``remainder'').
1283
1284 @itemize @bullet
1285 @item
1286 @code{mod(x,y) = floor2(x,y).remainder = x - floor(x/y)*y}
1287 @item
1288 @code{rem(x,y) = truncate2(x,y).remainder = x - truncate(x/y)*y}
1289 @end itemize
1290
1291 If @code{x} and @code{y} are both >= 0, @code{mod(x,y) = rem(x,y) >= 0}.
1292 In general, @code{mod(x,y)} has the sign of @code{y} or is zero,
1293 and @code{rem(x,y)} has the sign of @code{x} or is zero.
1294
1295 The classes @code{cl_R}, @code{cl_I} define the following operations:
1296
1297 @table @code
1298 @item @var{type} mod (const @var{type}& x, const @var{type}& y)
1299 @cindex @code{mod ()}
1300 @itemx @var{type} rem (const @var{type}& x, const @var{type}& y)
1301 @cindex @code{rem ()}
1302 @end table
1303
1304
1305 @section Roots
1306
1307 Each of the classes @code{cl_R},
1308 @code{cl_F}, @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}
1309 defines the following operation:
1310
1311 @table @code
1312 @item @var{type} sqrt (const @var{type}& x)
1313 @cindex @code{sqrt ()}
1314 @code{x} must be >= 0. This function returns the square root of @code{x},
1315 normalized to be >= 0. If @code{x} is the square of a rational number,
1316 @code{sqrt(x)} will be a rational number, else it will return a
1317 floating-point approximation.
1318 @end table
1319
1320 The classes @code{cl_RA}, @code{cl_I} define the following operation:
1321
1322 @table @code
1323 @item cl_boolean sqrtp (const @var{type}& x, @var{type}* root)
1324 @cindex @code{sqrtp ()}
1325 This tests whether @code{x} is a perfect square. If so, it returns true
1326 and the exact square root in @code{*root}, else it returns false.
1327 @end table
1328
1329 Furthermore, for integers, similarly:
1330
1331 @table @code
1332 @item cl_boolean isqrt (const @var{type}& x, @var{type}* root)
1333 @cindex @code{isqrt ()}
1334 @code{x} should be >= 0. This function sets @code{*root} to
1335 @code{floor(sqrt(x))} and returns the same value as @code{sqrtp}:
1336 the boolean value @code{(expt(*root,2) == x)}.
1337 @end table
1338
1339 For @code{n}th roots, the classes @code{cl_RA}, @code{cl_I}
1340 define the following operation:
1341
1342 @table @code
1343 @item cl_boolean rootp (const @var{type}& x, const cl_I& n, @var{type}* root)
1344 @cindex @code{rootp ()}
1345 @code{x} must be >= 0. @code{n} must be > 0.
1346 This tests whether @code{x} is an @code{n}th power of a rational number.
1347 If so, it returns true and the exact root in @code{*root}, else it returns
1348 false.
1349 @end table
1350
1351 The only square root function which accepts negative numbers is the one
1352 for class @code{cl_N}:
1353
1354 @table @code
1355 @item cl_N sqrt (const cl_N& z)
1356 @cindex @code{sqrt ()}
1357 Returns the square root of @code{z}, as defined by the formula
1358 @code{sqrt(z) = exp(log(z)/2)}. Conversion to a floating-point type
1359 or to a complex number are done if necessary. The range of the result is the
1360 right half plane @code{realpart(sqrt(z)) >= 0}
1361 including the positive imaginary axis and 0, but excluding
1362 the negative imaginary axis.
1363 The result is an exact number only if @code{z} is an exact number.
1364 @end table
1365
1366
1367 @section Transcendental functions
1368 @cindex transcendental functions
1369
1370 The transcendental functions return an exact result if the argument
1371 is exact and the result is exact as well. Otherwise they must return
1372 inexact numbers even if the argument is exact.
1373 For example, @code{cos(0) = 1} returns the rational number @code{1}.
1374
1375
1376 @subsection Exponential and logarithmic functions
1377
1378 @table @code
1379 @item cl_R exp (const cl_R& x)
1380 @cindex @code{exp ()}
1381 @itemx cl_N exp (const cl_N& x)
1382 Returns the exponential function of @code{x}. This is @code{e^x} where
1383 @code{e} is the base of the natural logarithms. The range of the result
1384 is the entire complex plane excluding 0.
1385
1386 @item cl_R ln (const cl_R& x)
1387 @cindex @code{ln ()}
1388 @code{x} must be > 0. Returns the (natural) logarithm of x.
1389
1390 @item cl_N log (const cl_N& x)
1391 @cindex @code{log ()}
1392 Returns the (natural) logarithm of x. If @code{x} is real and positive,
1393 this is @code{ln(x)}. In general, @code{log(x) = log(abs(x)) + i*phase(x)}.
1394 The range of the result is the strip in the complex plane
1395 @code{-pi < imagpart(log(x)) <= pi}.
1396
1397 @item cl_R phase (const cl_N& x)
1398 @cindex @code{phase ()}
1399 Returns the angle part of @code{x} in its polar representation as a
1400 complex number. That is, @code{phase(x) = atan(realpart(x),imagpart(x))}.
1401 This is also the imaginary part of @code{log(x)}.
1402 The range of the result is the interval @code{-pi < phase(x) <= pi}.
1403 The result will be an exact number only if @code{zerop(x)} or
1404 if @code{x} is real and positive.
1405
1406 @item cl_R log (const cl_R& a, const cl_R& b)
1407 @code{a} and @code{b} must be > 0. Returns the logarithm of @code{a} with
1408 respect to base @code{b}. @code{log(a,b) = ln(a)/ln(b)}.
1409 The result can be exact only if @code{a = 1} or if @code{a} and @code{b}
1410 are both rational.
1411
1412 @item cl_N log (const cl_N& a, const cl_N& b)
1413 Returns the logarithm of @code{a} with respect to base @code{b}.
1414 @code{log(a,b) = log(a)/log(b)}.
1415
1416 @item cl_N expt (const cl_N& x, const cl_N& y)
1417 @cindex @code{expt ()}
1418 Exponentiation: Returns @code{x^y = exp(y*log(x))}.
1419 @end table
1420
1421 The constant e = exp(1) = 2.71828@dots{} is returned by the following functions:
1422
1423 @table @code
1424 @item cl_F exp1 (float_format_t f)
1425 @cindex @code{exp1 ()}
1426 Returns e as a float of format @code{f}.
1427
1428 @item cl_F exp1 (const cl_F& y)
1429 Returns e in the float format of @code{y}.
1430
1431 @item cl_F exp1 (void)
1432 Returns e as a float of format @code{default_float_format}.
1433 @end table
1434
1435
1436 @subsection Trigonometric functions
1437
1438 @table @code
1439 @item cl_R sin (const cl_R& x)
1440 @cindex @code{sin ()}
1441 Returns @code{sin(x)}. The range of the result is the interval
1442 @code{-1 <= sin(x) <= 1}.
1443
1444 @item cl_N sin (const cl_N& z)
1445 Returns @code{sin(z)}. The range of the result is the entire complex plane.
1446
1447 @item cl_R cos (const cl_R& x)
1448 @cindex @code{cos ()}
1449 Returns @code{cos(x)}. The range of the result is the interval
1450 @code{-1 <= cos(x) <= 1}.
1451
1452 @item cl_N cos (const cl_N& x)
1453 Returns @code{cos(z)}. The range of the result is the entire complex plane.
1454
1455 @item struct cos_sin_t @{ cl_R cos; cl_R sin; @};
1456 @cindex @code{cos_sin_t}
1457 @itemx cos_sin_t cos_sin (const cl_R& x)
1458 Returns both @code{sin(x)} and @code{cos(x)}. This is more efficient than
1459 @cindex @code{cos_sin ()}
1460 computing them separately. The relation @code{cos^2 + sin^2 = 1} will
1461 hold only approximately.
1462
1463 @item cl_R tan (const cl_R& x)
1464 @cindex @code{tan ()}
1465 @itemx cl_N tan (const cl_N& x)
1466 Returns @code{tan(x) = sin(x)/cos(x)}.
1467
1468 @item cl_N cis (const cl_R& x)
1469 @cindex @code{cis ()}
1470 @itemx cl_N cis (const cl_N& x)
1471 Returns @code{exp(i*x)}. The name @samp{cis} means ``cos + i sin'', because
1472 @code{e^(i*x) = cos(x) + i*sin(x)}.
1473
1474 @cindex @code{asin}
1475 @cindex @code{asin ()}
1476 @item cl_N asin (const cl_N& z)
1477 Returns @code{arcsin(z)}. This is defined as
1478 @code{arcsin(z) = log(iz+sqrt(1-z^2))/i} and satisfies
1479 @code{arcsin(-z) = -arcsin(z)}.
1480 The range of the result is the strip in the complex domain
1481 @code{-pi/2 <= realpart(arcsin(z)) <= pi/2}, excluding the numbers
1482 with @code{realpart = -pi/2} and @code{imagpart < 0} and the numbers
1483 with @code{realpart = pi/2} and @code{imagpart > 0}.
1484 @ignore
1485 Proof: This follows from arcsin(z) = arsinh(iz)/i and the corresponding
1486 results for arsinh.
1487 @end ignore
1488
1489 @item cl_N acos (const cl_N& z)
1490 @cindex @code{acos ()}
1491 Returns @code{arccos(z)}. This is defined as
1492 @code{arccos(z) = pi/2 - arcsin(z) = log(z+i*sqrt(1-z^2))/i}
1493 @ignore
1494  Kahan's formula:
1495  @code{arccos(z) = 2*log(sqrt((1+z)/2)+i*sqrt((1-z)/2))/i}
1496 @end ignore
1497 and satisfies @code{arccos(-z) = pi - arccos(z)}.
1498 The range of the result is the strip in the complex domain
1499 @code{0 <= realpart(arcsin(z)) <= pi}, excluding the numbers
1500 with @code{realpart = 0} and @code{imagpart < 0} and the numbers
1501 with @code{realpart = pi} and @code{imagpart > 0}.
1502 @ignore
1503 Proof: This follows from the results about arcsin.
1504 @end ignore
1505
1506 @cindex @code{atan}
1507 @cindex @code{atan ()}
1508 @item cl_R atan (const cl_R& x, const cl_R& y)
1509 Returns the angle of the polar representation of the complex number
1510 @code{x+iy}. This is @code{atan(y/x)} if @code{x>0}. The range of
1511 the result is the interval @code{-pi < atan(x,y) <= pi}. The result will
1512 be an exact number only if @code{x > 0} and @code{y} is the exact @code{0}.
1513 WARNING: In Common Lisp, this function is called as @code{(atan y x)},
1514 with reversed order of arguments.
1515
1516 @item cl_R atan (const cl_R& x)
1517 Returns @code{arctan(x)}. This is the same as @code{atan(1,x)}. The range
1518 of the result is the interval @code{-pi/2 < atan(x) < pi/2}. The result
1519 will be an exact number only if @code{x} is the exact @code{0}.
1520
1521 @item cl_N atan (const cl_N& z)
1522 Returns @code{arctan(z)}. This is defined as
1523 @code{arctan(z) = (log(1+iz)-log(1-iz)) / 2i} and satisfies
1524 @code{arctan(-z) = -arctan(z)}. The range of the result is
1525 the strip in the complex domain
1526 @code{-pi/2 <= realpart(arctan(z)) <= pi/2}, excluding the numbers
1527 with @code{realpart = -pi/2} and @code{imagpart >= 0} and the numbers
1528 with @code{realpart = pi/2} and @code{imagpart <= 0}.
1529 @ignore
1530 Proof: arctan(z) = artanh(iz)/i, we know the range of the artanh function.
1531 @end ignore
1532
1533 @end table
1534
1535 @cindex pi
1536 @cindex Archimedes' constant
1537 Archimedes' constant pi = 3.14@dots{} is returned by the following functions:
1538
1539 @table @code
1540 @item cl_F pi (float_format_t f)
1541 @cindex @code{pi ()}
1542 Returns pi as a float of format @code{f}.
1543
1544 @item cl_F pi (const cl_F& y)
1545 Returns pi in the float format of @code{y}.
1546
1547 @item cl_F pi (void)
1548 Returns pi as a float of format @code{default_float_format}.
1549 @end table
1550
1551
1552 @subsection Hyperbolic functions
1553
1554 @table @code
1555 @item cl_R sinh (const cl_R& x)
1556 @cindex @code{sinh ()}
1557 Returns @code{sinh(x)}.
1558
1559 @item cl_N sinh (const cl_N& z)
1560 Returns @code{sinh(z)}. The range of the result is the entire complex plane.
1561
1562 @item cl_R cosh (const cl_R& x)
1563 @cindex @code{cosh ()}
1564 Returns @code{cosh(x)}. The range of the result is the interval
1565 @code{cosh(x) >= 1}.
1566
1567 @item cl_N cosh (const cl_N& z)
1568 Returns @code{cosh(z)}. The range of the result is the entire complex plane.
1569
1570 @item struct cosh_sinh_t @{ cl_R cosh; cl_R sinh; @};
1571 @cindex @code{cosh_sinh_t}
1572 @itemx cosh_sinh_t cosh_sinh (const cl_R& x)
1573 @cindex @code{cosh_sinh ()}
1574 Returns both @code{sinh(x)} and @code{cosh(x)}. This is more efficient than
1575 computing them separately. The relation @code{cosh^2 - sinh^2 = 1} will
1576 hold only approximately.
1577
1578 @item cl_R tanh (const cl_R& x)
1579 @cindex @code{tanh ()}
1580 @itemx cl_N tanh (const cl_N& x)
1581 Returns @code{tanh(x) = sinh(x)/cosh(x)}.
1582
1583 @item cl_N asinh (const cl_N& z)
1584 @cindex @code{asinh ()}
1585 Returns @code{arsinh(z)}. This is defined as
1586 @code{arsinh(z) = log(z+sqrt(1+z^2))} and satisfies
1587 @code{arsinh(-z) = -arsinh(z)}.
1588 @ignore
1589 Proof: Knowing the range of log, we know -pi < imagpart(arsinh(z)) <= pi.
1590 Actually, z+sqrt(1+z^2) can never be real and <0, so
1591 -pi < imagpart(arsinh(z)) < pi.
1592 We have (z+sqrt(1+z^2))*(-z+sqrt(1+(-z)^2)) = (1+z^2)-z^2 = 1, hence the
1593 logs of both factors sum up to 0 mod 2*pi*i, hence to 0.
1594 @end ignore
1595 The range of the result is the strip in the complex domain
1596 @code{-pi/2 <= imagpart(arsinh(z)) <= pi/2}, excluding the numbers
1597 with @code{imagpart = -pi/2} and @code{realpart > 0} and the numbers
1598 with @code{imagpart = pi/2} and @code{realpart < 0}.
1599 @ignore
1600 Proof: Write z = x+iy. Because of arsinh(-z) = -arsinh(z), we may assume
1601 that z is in Range(sqrt), that is, x>=0 and, if x=0, then y>=0.
1602 If x > 0, then Re(z+sqrt(1+z^2)) = x + Re(sqrt(1+z^2)) >= x > 0,
1603 so -pi/2 < imagpart(log(z+sqrt(1+z^2))) < pi/2.
1604 If x = 0 and y >= 0, arsinh(z) = log(i*y+sqrt(1-y^2)).
1605   If y <= 1, the realpart is 0 and the imagpart is >= 0 and <= pi/2.
1606   If y >= 1, the imagpart is pi/2 and the realpart is
1607              log(y+sqrt(y^2-1)) >= log(y) >= 0.
1608 @end ignore
1609 @ignore
1610 Moreover, if z is in Range(sqrt),
1611 log(sqrt(1+z^2)+z) = 2 artanh(z/(1+sqrt(1+z^2)))
1612 (for a proof, see file src/cl_C_asinh.cc).
1613 @end ignore
1614
1615 @item cl_N acosh (const cl_N& z)
1616 @cindex @code{acosh ()}
1617 Returns @code{arcosh(z)}. This is defined as
1618 @code{arcosh(z) = 2*log(sqrt((z+1)/2)+sqrt((z-1)/2))}.
1619 The range of the result is the half-strip in the complex domain
1620 @code{-pi < imagpart(arcosh(z)) <= pi, realpart(arcosh(z)) >= 0},
1621 excluding the numbers with @code{realpart = 0} and @code{-pi < imagpart < 0}.
1622 @ignore
1623 Proof: sqrt((z+1)/2) and sqrt((z-1)/2)) lie in Range(sqrt), hence does
1624 their sum, hence its log has an imagpart <= pi/2 and > -pi/2.
1625 If z is in Range(sqrt), we have
1626   sqrt(z+1)*sqrt(z-1) = sqrt(z^2-1)
1627   ==> (sqrt((z+1)/2)+sqrt((z-1)/2))^2 = (z+1)/2 + sqrt(z^2-1) + (z-1)/2
1628                                       = z + sqrt(z^2-1)
1629   ==> arcosh(z) = log(z+sqrt(z^2-1)) mod 2*pi*i
1630   and since the imagpart of both expressions is > -pi, <= pi
1631   ==> arcosh(z) = log(z+sqrt(z^2-1))
1632   To prove that the realpart of this is >= 0, write z = x+iy with x>=0,
1633   z^2-1 = u+iv with u = x^2-y^2-1, v = 2xy,
1634   sqrt(z^2-1) = p+iq with p = sqrt((sqrt(u^2+v^2)+u)/2) >= 0,
1635                           q = sqrt((sqrt(u^2+v^2)-u)/2) * sign(v),
1636   then |z+sqrt(z^2-1)|^2 = |x+iy + p+iq|^2
1637           = (x+p)^2 + (y+q)^2
1638           = x^2 + 2xp + p^2 + y^2 + 2yq + q^2
1639           >= x^2 + p^2 + y^2 + q^2                 (since x>=0, p>=0, yq>=0)
1640           = x^2 + y^2 + sqrt(u^2+v^2)
1641           >= x^2 + y^2 + |u|
1642           >= x^2 + y^2 - u
1643           = 1 + 2*y^2
1644           >= 1
1645   hence realpart(log(z+sqrt(z^2-1))) = log(|z+sqrt(z^2-1)|) >= 0.
1646   Equality holds only if y = 0 and u <= 0, i.e. 0 <= x < 1.
1647   In this case arcosh(z) = log(x+i*sqrt(1-x^2)) has imagpart >=0.
1648 Otherwise, -z is in Range(sqrt).
1649   If y != 0, sqrt((z+1)/2) = i^sign(y) * sqrt((-z-1)/2),
1650              sqrt((z-1)/2) = i^sign(y) * sqrt((-z+1)/2),
1651              hence arcosh(z) = sign(y)*pi/2*i + arcosh(-z),
1652              and this has realpart > 0.
1653   If y = 0 and -1<=x<=0, we still have sqrt(z+1)*sqrt(z-1) = sqrt(z^2-1),
1654              ==> arcosh(z) = log(z+sqrt(z^2-1)) = log(x+i*sqrt(1-x^2))
1655              has realpart = 0 and imagpart > 0.
1656   If y = 0 and x<=-1, however, sqrt(z+1)*sqrt(z-1) = - sqrt(z^2-1),
1657              ==> arcosh(z) = log(z-sqrt(z^2-1)) = pi*i + arcosh(-z).
1658              This has realpart >= 0 and imagpart = pi.
1659 @end ignore
1660
1661 @item cl_N atanh (const cl_N& z)
1662 @cindex @code{atanh ()}
1663 Returns @code{artanh(z)}. This is defined as
1664 @code{artanh(z) = (log(1+z)-log(1-z)) / 2} and satisfies
1665 @code{artanh(-z) = -artanh(z)}. The range of the result is
1666 the strip in the complex domain
1667 @code{-pi/2 <= imagpart(artanh(z)) <= pi/2}, excluding the numbers
1668 with @code{imagpart = -pi/2} and @code{realpart <= 0} and the numbers
1669 with @code{imagpart = pi/2} and @code{realpart >= 0}.
1670 @ignore
1671 Proof: Write z = x+iy. Examine
1672   imagpart(artanh(z)) = (atan(1+x,y) - atan(1-x,-y))/2.
1673   Case 1: y = 0.
1674           x > 1 ==> imagpart = -pi/2, realpart = 1/2 log((x+1)/(x-1)) > 0,
1675           x < -1 ==> imagpart = pi/2, realpart = 1/2 log((-x-1)/(-x+1)) < 0,
1676           |x| < 1 ==> imagpart = 0
1677   Case 2: y > 0.
1678           imagpart(artanh(z))
1679               = (atan(1+x,y) - atan(1-x,-y))/2
1680               = ((pi/2 - atan((1+x)/y)) - (-pi/2 - atan((1-x)/-y)))/2
1681               = (pi - atan((1+x)/y) - atan((1-x)/y))/2
1682               > (pi -     pi/2      -     pi/2     )/2 = 0
1683           and (1+x)/y > (1-x)/y
1684               ==> atan((1+x)/y) > atan((-1+x)/y) = - atan((1-x)/y)
1685               ==> imagpart < pi/2.
1686           Hence 0 < imagpart < pi/2.
1687   Case 3: y < 0.
1688           By artanh(z) = -artanh(-z) and case 2, -pi/2 < imagpart < 0.
1689 @end ignore
1690 @end table
1691
1692
1693 @subsection Euler gamma
1694 @cindex Euler's constant
1695
1696 Euler's constant C = 0.577@dots{} is returned by the following functions:
1697
1698 @table @code
1699 @item cl_F eulerconst (float_format_t f)
1700 @cindex @code{eulerconst ()}
1701 Returns Euler's constant as a float of format @code{f}.
1702
1703 @item cl_F eulerconst (const cl_F& y)
1704 Returns Euler's constant in the float format of @code{y}.
1705
1706 @item cl_F eulerconst (void)
1707 Returns Euler's constant as a float of format @code{default_float_format}.
1708 @end table
1709
1710 Catalan's constant G = 0.915@dots{} is returned by the following functions:
1711 @cindex Catalan's constant
1712
1713 @table @code
1714 @item cl_F catalanconst (float_format_t f)
1715 @cindex @code{catalanconst ()}
1716 Returns Catalan's constant as a float of format @code{f}.
1717
1718 @item cl_F catalanconst (const cl_F& y)
1719 Returns Catalan's constant in the float format of @code{y}.
1720
1721 @item cl_F catalanconst (void)
1722 Returns Catalan's constant as a float of format @code{default_float_format}.
1723 @end table
1724
1725
1726 @subsection Riemann zeta
1727 @cindex Riemann's zeta
1728
1729 Riemann's zeta function at an integral point @code{s>1} is returned by the
1730 following functions:
1731
1732 @table @code
1733 @item cl_F zeta (int s, float_format_t f)
1734 @cindex @code{zeta ()}
1735 Returns Riemann's zeta function at @code{s} as a float of format @code{f}.
1736
1737 @item cl_F zeta (int s, const cl_F& y)
1738 Returns Riemann's zeta function at @code{s} in the float format of @code{y}.
1739
1740 @item cl_F zeta (int s)
1741 Returns Riemann's zeta function at @code{s} as a float of format
1742 @code{default_float_format}.
1743 @end table
1744
1745
1746 @section Functions on integers
1747
1748 @subsection Logical functions
1749
1750 Integers, when viewed as in two's complement notation, can be thought as
1751 infinite bit strings where the bits' values eventually are constant.
1752 For example,
1753 @example
1754     17 = ......00010001
1755     -6 = ......11111010
1756 @end example
1757
1758 The logical operations view integers as such bit strings and operate
1759 on each of the bit positions in parallel.
1760
1761 @table @code
1762 @item cl_I lognot (const cl_I& x)
1763 @cindex @code{lognot ()}
1764 @itemx cl_I operator ~ (const cl_I& x)
1765 @cindex @code{operator ~ ()}
1766 Logical not, like @code{~x} in C. This is the same as @code{-1-x}.
1767
1768 @item cl_I logand (const cl_I& x, const cl_I& y)
1769 @cindex @code{logand ()}
1770 @itemx cl_I operator & (const cl_I& x, const cl_I& y)
1771 @cindex @code{operator & ()}
1772 Logical and, like @code{x & y} in C.
1773
1774 @item cl_I logior (const cl_I& x, const cl_I& y)
1775 @cindex @code{logior ()}
1776 @itemx cl_I operator | (const cl_I& x, const cl_I& y)
1777 @cindex @code{operator | ()}
1778 Logical (inclusive) or, like @code{x | y} in C.
1779
1780 @item cl_I logxor (const cl_I& x, const cl_I& y)
1781 @cindex @code{logxor ()}
1782 @itemx cl_I operator ^ (const cl_I& x, const cl_I& y)
1783 @cindex @code{operator ^ ()}
1784 Exclusive or, like @code{x ^ y} in C.
1785
1786 @item cl_I logeqv (const cl_I& x, const cl_I& y)
1787 @cindex @code{logeqv ()}
1788 Bitwise equivalence, like @code{~(x ^ y)} in C.
1789
1790 @item cl_I lognand (const cl_I& x, const cl_I& y)
1791 @cindex @code{lognand ()}
1792 Bitwise not and, like @code{~(x & y)} in C.
1793
1794 @item cl_I lognor (const cl_I& x, const cl_I& y)
1795 @cindex @code{lognor ()}
1796 Bitwise not or, like @code{~(x | y)} in C.
1797
1798 @item cl_I logandc1 (const cl_I& x, const cl_I& y)
1799 @cindex @code{logandc1 ()}
1800 Logical and, complementing the first argument, like @code{~x & y} in C.
1801
1802 @item cl_I logandc2 (const cl_I& x, const cl_I& y)
1803 @cindex @code{logandc2 ()}
1804 Logical and, complementing the second argument, like @code{x & ~y} in C.
1805
1806 @item cl_I logorc1 (const cl_I& x, const cl_I& y)
1807 @cindex @code{logorc1 ()}
1808 Logical or, complementing the first argument, like @code{~x | y} in C.
1809
1810 @item cl_I logorc2 (const cl_I& x, const cl_I& y)
1811 @cindex @code{logorc2 ()}
1812 Logical or, complementing the second argument, like @code{x | ~y} in C.
1813 @end table
1814
1815 These operations are all available though the function
1816 @table @code
1817 @item cl_I boole (cl_boole op, const cl_I& x, const cl_I& y)
1818 @cindex @code{boole ()}
1819 @end table
1820 where @code{op} must have one of the 16 values (each one stands for a function
1821 which combines two bits into one bit): @code{boole_clr}, @code{boole_set},
1822 @code{boole_1}, @code{boole_2}, @code{boole_c1}, @code{boole_c2},
1823 @code{boole_and}, @code{boole_ior}, @code{boole_xor}, @code{boole_eqv},
1824 @code{boole_nand}, @code{boole_nor}, @code{boole_andc1}, @code{boole_andc2},
1825 @code{boole_orc1}, @code{boole_orc2}.
1826 @cindex @code{boole_clr}
1827 @cindex @code{boole_set}
1828 @cindex @code{boole_1}
1829 @cindex @code{boole_2}
1830 @cindex @code{boole_c1}
1831 @cindex @code{boole_c2}
1832 @cindex @code{boole_and}
1833 @cindex @code{boole_xor}
1834 @cindex @code{boole_eqv}
1835 @cindex @code{boole_nand}
1836 @cindex @code{boole_nor}
1837 @cindex @code{boole_andc1}
1838 @cindex @code{boole_andc2}
1839 @cindex @code{boole_orc1}
1840 @cindex @code{boole_orc2}
1841
1842
1843 Other functions that view integers as bit strings:
1844
1845 @table @code
1846 @item cl_boolean logtest (const cl_I& x, const cl_I& y)
1847 @cindex @code{logtest ()}
1848 Returns true if some bit is set in both @code{x} and @code{y}, i.e. if
1849 @code{logand(x,y) != 0}.
1850
1851 @item cl_boolean logbitp (const cl_I& n, const cl_I& x)
1852 @cindex @code{logbitp ()}
1853 Returns true if the @code{n}th bit (from the right) of @code{x} is set.
1854 Bit 0 is the least significant bit.
1855
1856 @item uintL logcount (const cl_I& x)
1857 @cindex @code{logcount ()}
1858 Returns the number of one bits in @code{x}, if @code{x} >= 0, or
1859 the number of zero bits in @code{x}, if @code{x} < 0.
1860 @end table
1861
1862 The following functions operate on intervals of bits in integers. 
1863 The type
1864 @example
1865 struct cl_byte @{ uintL size; uintL position; @};
1866 @end example
1867 @cindex @code{cl_byte}
1868 represents the bit interval containing the bits
1869 @code{position}@dots{}@code{position+size-1} of an integer.
1870 The constructor @code{cl_byte(size,position)} constructs a @code{cl_byte}.
1871
1872 @table @code
1873 @item cl_I ldb (const cl_I& n, const cl_byte& b)
1874 @cindex @code{ldb ()}
1875 extracts the bits of @code{n} described by the bit interval @code{b}
1876 and returns them as a nonnegative integer with @code{b.size} bits.
1877
1878 @item cl_boolean ldb_test (const cl_I& n, const cl_byte& b)
1879 @cindex @code{ldb_test ()}
1880 Returns true if some bit described by the bit interval @code{b} is set in
1881 @code{n}.
1882
1883 @item cl_I dpb (const cl_I& newbyte, const cl_I& n, const cl_byte& b)
1884 @cindex @code{dpb ()}
1885 Returns @code{n}, with the bits described by the bit interval @code{b}
1886 replaced by @code{newbyte}. Only the lowest @code{b.size} bits of
1887 @code{newbyte} are relevant.
1888 @end table
1889
1890 The functions @code{ldb} and @code{dpb} implicitly shift. The following
1891 functions are their counterparts without shifting:
1892
1893 @table @code
1894 @item cl_I mask_field (const cl_I& n, const cl_byte& b)
1895 @cindex @code{mask_field ()}
1896 returns an integer with the bits described by the bit interval @code{b}
1897 copied from the corresponding bits in @code{n}, the other bits zero.
1898
1899 @item cl_I deposit_field (const cl_I& newbyte, const cl_I& n, const cl_byte& b)
1900 @cindex @code{deposit_field ()}
1901 returns an integer where the bits described by the bit interval @code{b}
1902 come from @code{newbyte} and the other bits come from @code{n}.
1903 @end table
1904
1905 The following relations hold:
1906
1907 @itemize @asis
1908 @item
1909 @code{ldb (n, b) = mask_field(n, b) >> b.position},
1910 @item
1911 @code{dpb (newbyte, n, b) = deposit_field (newbyte << b.position, n, b)},
1912 @item
1913 @code{deposit_field(newbyte,n,b) = n ^ mask_field(n,b) ^ mask_field(new_byte,b)}.
1914 @end itemize
1915
1916 The following operations on integers as bit strings are efficient shortcuts
1917 for common arithmetic operations:
1918
1919 @table @code
1920 @item cl_boolean oddp (const cl_I& x)
1921 @cindex @code{oddp ()}
1922 Returns true if the least significant bit of @code{x} is 1. Equivalent to
1923 @code{mod(x,2) != 0}.
1924
1925 @item cl_boolean evenp (const cl_I& x)
1926 @cindex @code{evenp ()}
1927 Returns true if the least significant bit of @code{x} is 0. Equivalent to
1928 @code{mod(x,2) == 0}.
1929
1930 @item cl_I operator << (const cl_I& x, const cl_I& n)
1931 @cindex @code{operator << ()}
1932 Shifts @code{x} by @code{n} bits to the left. @code{n} should be >=0.
1933 Equivalent to @code{x * expt(2,n)}.
1934
1935 @item cl_I operator >> (const cl_I& x, const cl_I& n)
1936 @cindex @code{operator >> ()}
1937 Shifts @code{x} by @code{n} bits to the right. @code{n} should be >=0.
1938 Bits shifted out to the right are thrown away.
1939 Equivalent to @code{floor(x / expt(2,n))}.
1940
1941 @item cl_I ash (const cl_I& x, const cl_I& y)
1942 @cindex @code{ash ()}
1943 Shifts @code{x} by @code{y} bits to the left (if @code{y}>=0) or
1944 by @code{-y} bits to the right (if @code{y}<=0). In other words, this
1945 returns @code{floor(x * expt(2,y))}.
1946
1947 @item uintL integer_length (const cl_I& x)
1948 @cindex @code{integer_length ()}
1949 Returns the number of bits (excluding the sign bit) needed to represent @code{x}
1950 in two's complement notation. This is the smallest n >= 0 such that
1951 -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
1952 2^(n-1) <= x < 2^n.
1953
1954 @item uintL ord2 (const cl_I& x)
1955 @cindex @code{ord2 ()}
1956 @code{x} must be non-zero. This function returns the number of 0 bits at the
1957 right of @code{x} in two's complement notation. This is the largest n >= 0
1958 such that 2^n divides @code{x}.
1959
1960 @item uintL power2p (const cl_I& x)
1961 @cindex @code{power2p ()}
1962 @code{x} must be > 0. This function checks whether @code{x} is a power of 2.
1963 If @code{x} = 2^(n-1), it returns n. Else it returns 0.
1964 (See also the function @code{logp}.)
1965 @end table
1966
1967
1968 @subsection Number theoretic functions
1969
1970 @table @code
1971 @item uint32 gcd (uint32 a, uint32 b)
1972 @cindex @code{gcd ()}
1973 @itemx cl_I gcd (const cl_I& a, const cl_I& b)
1974 This function returns the greatest common divisor of @code{a} and @code{b},
1975 normalized to be >= 0.
1976
1977 @item cl_I xgcd (const cl_I& a, const cl_I& b, cl_I* u, cl_I* v)
1978 @cindex @code{xgcd ()}
1979 This function (``extended gcd'') returns the greatest common divisor @code{g} of
1980 @code{a} and @code{b} and at the same time the representation of @code{g}
1981 as an integral linear combination of @code{a} and @code{b}:
1982 @code{u} and @code{v} with @code{u*a+v*b = g}, @code{g} >= 0.
1983 @code{u} and @code{v} will be normalized to be of smallest possible absolute
1984 value, in the following sense: If @code{a} and @code{b} are non-zero, and
1985 @code{abs(a) != abs(b)}, @code{u} and @code{v} will satisfy the inequalities
1986 @code{abs(u) <= abs(b)/(2*g)}, @code{abs(v) <= abs(a)/(2*g)}.
1987
1988 @item cl_I lcm (const cl_I& a, const cl_I& b)
1989 @cindex @code{lcm ()}
1990 This function returns the least common multiple of @code{a} and @code{b},
1991 normalized to be >= 0.
1992
1993 @item cl_boolean logp (const cl_I& a, const cl_I& b, cl_RA* l)
1994 @cindex @code{logp ()}
1995 @itemx cl_boolean logp (const cl_RA& a, const cl_RA& b, cl_RA* l)
1996 @code{a} must be > 0. @code{b} must be >0 and != 1. If log(a,b) is
1997 rational number, this function returns true and sets *l = log(a,b), else
1998 it returns false.
1999 @end table
2000
2001
2002 @subsection Combinatorial functions
2003
2004 @table @code
2005 @item cl_I factorial (uintL n)
2006 @cindex @code{factorial ()}
2007 @code{n} must be a small integer >= 0. This function returns the factorial
2008 @code{n}! = @code{1*2*@dots{}*n}.
2009
2010 @item cl_I doublefactorial (uintL n)
2011 @cindex @code{doublefactorial ()}
2012 @code{n} must be a small integer >= 0. This function returns the 
2013 doublefactorial @code{n}!! = @code{1*3*@dots{}*n} or 
2014 @code{n}!! = @code{2*4*@dots{}*n}, respectively.
2015
2016 @item cl_I binomial (uintL n, uintL k)
2017 @cindex @code{binomial ()}
2018 @code{n} and @code{k} must be small integers >= 0. This function returns the
2019 binomial coefficient
2020 @tex
2021 ${n \choose k} = {n! \over n! (n-k)!}$
2022 @end tex
2023 @ifinfo
2024 (@code{n} choose @code{k}) = @code{n}! / @code{k}! @code{(n-k)}!
2025 @end ifinfo
2026 for 0 <= k <= n, 0 else.
2027 @end table
2028
2029
2030 @section Functions on floating-point numbers
2031
2032 Recall that a floating-point number consists of a sign @code{s}, an
2033 exponent @code{e} and a mantissa @code{m}. The value of the number is
2034 @code{(-1)^s * 2^e * m}.
2035
2036 Each of the classes
2037 @code{cl_F}, @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}
2038 defines the following operations.
2039
2040 @table @code
2041 @item @var{type} scale_float (const @var{type}& x, sintL delta)
2042 @cindex @code{scale_float ()}
2043 @itemx @var{type} scale_float (const @var{type}& x, const cl_I& delta)
2044 Returns @code{x*2^delta}. This is more efficient than an explicit multiplication
2045 because it copies @code{x} and modifies the exponent.
2046 @end table
2047
2048 The following functions provide an abstract interface to the underlying
2049 representation of floating-point numbers.
2050
2051 @table @code
2052 @item sintL float_exponent (const @var{type}& x)
2053 @cindex @code{float_exponent ()}
2054 Returns the exponent @code{e} of @code{x}.
2055 For @code{x = 0.0}, this is 0. For @code{x} non-zero, this is the unique
2056 integer with @code{2^(e-1) <= abs(x) < 2^e}.
2057
2058 @item sintL float_radix (const @var{type}& x)
2059 @cindex @code{float_radix ()}
2060 Returns the base of the floating-point representation. This is always @code{2}.
2061
2062 @item @var{type} float_sign (const @var{type}& x)
2063 @cindex @code{float_sign ()}
2064 Returns the sign @code{s} of @code{x} as a float. The value is 1 for
2065 @code{x} >= 0, -1 for @code{x} < 0.
2066
2067 @item uintL float_digits (const @var{type}& x)
2068 @cindex @code{float_digits ()}
2069 Returns the number of mantissa bits in the floating-point representation
2070 of @code{x}, including the hidden bit. The value only depends on the type
2071 of @code{x}, not on its value.
2072
2073 @item uintL float_precision (const @var{type}& x)
2074 @cindex @code{float_precision ()}
2075 Returns the number of significant mantissa bits in the floating-point
2076 representation of @code{x}. Since denormalized numbers are not supported,
2077 this is the same as @code{float_digits(x)} if @code{x} is non-zero, and
2078 0 if @code{x} = 0.
2079 @end table
2080
2081 The complete internal representation of a float is encoded in the type
2082 @cindex @code{decoded_float}
2083 @cindex @code{decoded_sfloat}
2084 @cindex @code{decoded_ffloat}
2085 @cindex @code{decoded_dfloat}
2086 @cindex @code{decoded_lfloat}
2087 @code{decoded_float} (or @code{decoded_sfloat}, @code{decoded_ffloat},
2088 @code{decoded_dfloat}, @code{decoded_lfloat}, respectively), defined by
2089 @example
2090 struct decoded_@var{type}float @{
2091         @var{type} mantissa; cl_I exponent; @var{type} sign;
2092 @};
2093 @end example
2094
2095 and returned by the function
2096
2097 @table @code
2098 @item decoded_@var{type}float decode_float (const @var{type}& x)
2099 @cindex @code{decode_float ()}
2100 For @code{x} non-zero, this returns @code{(-1)^s}, @code{e}, @code{m} with
2101 @code{x = (-1)^s * 2^e * m} and @code{0.5 <= m < 1.0}. For @code{x} = 0,
2102 it returns @code{(-1)^s}=1, @code{e}=0, @code{m}=0.
2103 @code{e} is the same as returned by the function @code{float_exponent}.
2104 @end table
2105
2106 A complete decoding in terms of integers is provided as type
2107 @cindex @code{cl_idecoded_float}
2108 @example
2109 struct cl_idecoded_float @{
2110         cl_I mantissa; cl_I exponent; cl_I sign;
2111 @};
2112 @end example
2113 by the following function:
2114
2115 @table @code
2116 @item cl_idecoded_float integer_decode_float (const @var{type}& x)
2117 @cindex @code{integer_decode_float ()}
2118 For @code{x} non-zero, this returns @code{(-1)^s}, @code{e}, @code{m} with
2119 @code{x = (-1)^s * 2^e * m} and @code{m} an integer with @code{float_digits(x)}
2120 bits. For @code{x} = 0, it returns @code{(-1)^s}=1, @code{e}=0, @code{m}=0.
2121 WARNING: The exponent @code{e} is not the same as the one returned by
2122 the functions @code{decode_float} and @code{float_exponent}.
2123 @end table
2124
2125 Some other function, implemented only for class @code{cl_F}:
2126
2127 @table @code
2128 @item cl_F float_sign (const cl_F& x, const cl_F& y)
2129 @cindex @code{float_sign ()}
2130 This returns a floating point number whose precision and absolute value
2131 is that of @code{y} and whose sign is that of @code{x}. If @code{x} is
2132 zero, it is treated as positive. Same for @code{y}.
2133 @end table
2134
2135
2136 @section Conversion functions
2137 @cindex conversion
2138
2139 @subsection Conversion to floating-point numbers
2140
2141 The type @code{float_format_t} describes a floating-point format.
2142 @cindex @code{float_format_t}
2143
2144 @table @code
2145 @item float_format_t float_format (uintL n)
2146 @cindex @code{float_format ()}
2147 Returns the smallest float format which guarantees at least @code{n}
2148 decimal digits in the mantissa (after the decimal point).
2149
2150 @item float_format_t float_format (const cl_F& x)
2151 Returns the floating point format of @code{x}.
2152
2153 @item float_format_t default_float_format
2154 @cindex @code{default_float_format}
2155 Global variable: the default float format used when converting rational numbers
2156 to floats.
2157 @end table
2158
2159 To convert a real number to a float, each of the types
2160 @code{cl_R}, @code{cl_F}, @code{cl_I}, @code{cl_RA},
2161 @code{int}, @code{unsigned int}, @code{float}, @code{double}
2162 defines the following operations:
2163
2164 @table @code
2165 @item cl_F cl_float (const @var{type}&x, float_format_t f)
2166 @cindex @code{cl_float ()}
2167 Returns @code{x} as a float of format @code{f}.
2168 @item cl_F cl_float (const @var{type}&x, const cl_F& y)
2169 Returns @code{x} in the float format of @code{y}.
2170 @item cl_F cl_float (const @var{type}&x)
2171 Returns @code{x} as a float of format @code{default_float_format} if
2172 it is an exact number, or @code{x} itself if it is already a float.
2173 @end table
2174
2175 Of course, converting a number to a float can lose precision.
2176
2177 Every floating-point format has some characteristic numbers:
2178
2179 @table @code
2180 @item cl_F most_positive_float (float_format_t f)
2181 @cindex @code{most_positive_float ()}
2182 Returns the largest (most positive) floating point number in float format @code{f}.
2183
2184 @item cl_F most_negative_float (float_format_t f)
2185 @cindex @code{most_negative_float ()}
2186 Returns the smallest (most negative) floating point number in float format @code{f}.
2187
2188 @item cl_F least_positive_float (float_format_t f)
2189 @cindex @code{least_positive_float ()}
2190 Returns the least positive floating point number (i.e. > 0 but closest to 0)
2191 in float format @code{f}.
2192
2193 @item cl_F least_negative_float (float_format_t f)
2194 @cindex @code{least_negative_float ()}
2195 Returns the least negative floating point number (i.e. < 0 but closest to 0)
2196 in float format @code{f}.
2197
2198 @item cl_F float_epsilon (float_format_t f)
2199 @cindex @code{float_epsilon ()}
2200 Returns the smallest floating point number e > 0 such that @code{1+e != 1}.
2201
2202 @item cl_F float_negative_epsilon (float_format_t f)
2203 @cindex @code{float_negative_epsilon ()}
2204 Returns the smallest floating point number e > 0 such that @code{1-e != 1}.
2205 @end table
2206
2207
2208 @subsection Conversion to rational numbers
2209
2210 Each of the classes @code{cl_R}, @code{cl_RA}, @code{cl_F}
2211 defines the following operation:
2212
2213 @table @code
2214 @item cl_RA rational (const @var{type}& x)
2215 @cindex @code{rational ()}
2216 Returns the value of @code{x} as an exact number. If @code{x} is already
2217 an exact number, this is @code{x}. If @code{x} is a floating-point number,
2218 the value is a rational number whose denominator is a power of 2.
2219 @end table
2220
2221 In order to convert back, say, @code{(cl_F)(cl_R)"1/3"} to @code{1/3}, there is
2222 the function
2223
2224 @table @code
2225 @item cl_RA rationalize (const cl_R& x)
2226 @cindex @code{rationalize ()}
2227 If @code{x} is a floating-point number, it actually represents an interval
2228 of real numbers, and this function returns the rational number with
2229 smallest denominator (and smallest numerator, in magnitude)
2230 which lies in this interval.
2231 If @code{x} is already an exact number, this function returns @code{x}.
2232 @end table
2233
2234 If @code{x} is any float, one has
2235
2236 @itemize @asis
2237 @item
2238 @code{cl_float(rational(x),x) = x}
2239 @item
2240 @code{cl_float(rationalize(x),x) = x}
2241 @end itemize
2242
2243
2244 @section Random number generators
2245
2246
2247 A random generator is a machine which produces (pseudo-)random numbers.
2248 The include file @code{<cln/random.h>} defines a class @code{random_state}
2249 which contains the state of a random generator. If you make a copy
2250 of the random number generator, the original one and the copy will produce
2251 the same sequence of random numbers.
2252
2253 The following functions return (pseudo-)random numbers in different formats.
2254 Calling one of these modifies the state of the random number generator in
2255 a complicated but deterministic way.
2256
2257 The global variable
2258 @cindex @code{random_state}
2259 @cindex @code{default_random_state}
2260 @example
2261 random_state default_random_state
2262 @end example
2263 contains a default random number generator. It is used when the functions
2264 below are called without @code{random_state} argument.
2265
2266 @table @code
2267 @item uint32 random32 (random_state& randomstate)
2268 @itemx uint32 random32 ()
2269 @cindex @code{random32 ()}
2270 Returns a random unsigned 32-bit number. All bits are equally random.
2271
2272 @item cl_I random_I (random_state& randomstate, const cl_I& n)
2273 @itemx cl_I random_I (const cl_I& n)
2274 @cindex @code{random_I ()}
2275 @code{n} must be an integer > 0. This function returns a random integer @code{x}
2276 in the range @code{0 <= x < n}.
2277
2278 @item cl_F random_F (random_state& randomstate, const cl_F& n)
2279 @itemx cl_F random_F (const cl_F& n)
2280 @cindex @code{random_F ()}
2281 @code{n} must be a float > 0. This function returns a random floating-point
2282 number of the same format as @code{n} in the range @code{0 <= x < n}.
2283
2284 @item cl_R random_R (random_state& randomstate, const cl_R& n)
2285 @itemx cl_R random_R (const cl_R& n)
2286 @cindex @code{random_R ()}
2287 Behaves like @code{random_I} if @code{n} is an integer and like @code{random_F}
2288 if @code{n} is a float.
2289 @end table
2290
2291
2292 @section Obfuscating operators
2293 @cindex modifying operators
2294
2295 The modifying C/C++ operators @code{+=}, @code{-=}, @code{*=}, @code{/=},
2296 @code{&=}, @code{|=}, @code{^=}, @code{<<=}, @code{>>=}
2297 are not available by default because their
2298 use tends to make programs unreadable. It is trivial to get away without
2299 them. However, if you feel that you absolutely need these operators
2300 to get happy, then add
2301 @example
2302 #define WANT_OBFUSCATING_OPERATORS
2303 @end example
2304 @cindex @code{WANT_OBFUSCATING_OPERATORS}
2305 to the beginning of your source files, before the inclusion of any CLN
2306 include files. This flag will enable the following operators:
2307
2308 For the classes @code{cl_N}, @code{cl_R}, @code{cl_RA},
2309 @code{cl_F}, @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}:
2310
2311 @table @code
2312 @item @var{type}& operator += (@var{type}&, const @var{type}&)
2313 @cindex @code{operator += ()}
2314 @itemx @var{type}& operator -= (@var{type}&, const @var{type}&)
2315 @cindex @code{operator -= ()}
2316 @itemx @var{type}& operator *= (@var{type}&, const @var{type}&)
2317 @cindex @code{operator *= ()}
2318 @itemx @var{type}& operator /= (@var{type}&, const @var{type}&)
2319 @cindex @code{operator /= ()}
2320 @end table
2321
2322 For the class @code{cl_I}:
2323
2324 @table @code
2325 @item @var{type}& operator += (@var{type}&, const @var{type}&)
2326 @itemx @var{type}& operator -= (@var{type}&, const @var{type}&)
2327 @itemx @var{type}& operator *= (@var{type}&, const @var{type}&)
2328 @itemx @var{type}& operator &= (@var{type}&, const @var{type}&)
2329 @cindex @code{operator &= ()}
2330 @itemx @var{type}& operator |= (@var{type}&, const @var{type}&)
2331 @cindex @code{operator |= ()}
2332 @itemx @var{type}& operator ^= (@var{type}&, const @var{type}&)
2333 @cindex @code{operator ^= ()}
2334 @itemx @var{type}& operator <<= (@var{type}&, const @var{type}&)
2335 @cindex @code{operator <<= ()}
2336 @itemx @var{type}& operator >>= (@var{type}&, const @var{type}&)
2337 @cindex @code{operator >>= ()}
2338 @end table
2339
2340 For the classes @code{cl_N}, @code{cl_R}, @code{cl_RA}, @code{cl_I},
2341 @code{cl_F}, @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}:
2342
2343 @table @code
2344 @item @var{type}& operator ++ (@var{type}& x)
2345 @cindex @code{operator ++ ()}
2346 The prefix operator @code{++x}.
2347
2348 @item void operator ++ (@var{type}& x, int)
2349 The postfix operator @code{x++}.
2350
2351 @item @var{type}& operator -- (@var{type}& x)
2352 @cindex @code{operator -- ()}
2353 The prefix operator @code{--x}.
2354
2355 @item void operator -- (@var{type}& x, int)
2356 The postfix operator @code{x--}.
2357 @end table
2358
2359 Note that by using these obfuscating operators, you wouldn't gain efficiency:
2360 In CLN @samp{x += y;} is exactly the same as  @samp{x = x+y;}, not more
2361 efficient.
2362
2363
2364 @chapter Input/Output
2365 @cindex Input/Output
2366
2367 @section Internal and printed representation
2368 @cindex representation
2369
2370 All computations deal with the internal representations of the numbers.
2371
2372 Every number has an external representation as a sequence of ASCII characters.
2373 Several external representations may denote the same number, for example,
2374 "20.0" and "20.000".
2375
2376 Converting an internal to an external representation is called ``printing'',
2377 @cindex printing
2378 converting an external to an internal representation is called ``reading''.
2379 @cindex reading
2380 In CLN, it is always true that conversion of an internal to an external
2381 representation and then back to an internal representation will yield the
2382 same internal representation. Symbolically: @code{read(print(x)) == x}.
2383 This is called ``print-read consistency''. 
2384
2385 Different types of numbers have different external representations (case
2386 is insignificant):
2387
2388 @table @asis
2389 @item Integers
2390 External representation: @var{sign}@{@var{digit}@}+. The reader also accepts the
2391 Common Lisp syntaxes @var{sign}@{@var{digit}@}+@code{.} with a trailing dot
2392 for decimal integers
2393 and the @code{#@var{n}R}, @code{#b}, @code{#o}, @code{#x} prefixes.
2394
2395 @item Rational numbers
2396 External representation: @var{sign}@{@var{digit}@}+@code{/}@{@var{digit}@}+.
2397 The @code{#@var{n}R}, @code{#b}, @code{#o}, @code{#x} prefixes are allowed
2398 here as well.
2399
2400 @item Floating-point numbers
2401 External representation: @var{sign}@{@var{digit}@}*@var{exponent} or
2402 @var{sign}@{@var{digit}@}*@code{.}@{@var{digit}@}*@var{exponent} or
2403 @var{sign}@{@var{digit}@}*@code{.}@{@var{digit}@}+. A precision specifier
2404 of the form _@var{prec} may be appended. There must be at least
2405 one digit in the non-exponent part. The exponent has the syntax
2406 @var{expmarker} @var{expsign} @{@var{digit}@}+.
2407 The exponent marker is
2408
2409 @itemize @asis
2410 @item
2411 @samp{s} for short-floats,
2412 @item
2413 @samp{f} for single-floats,
2414 @item
2415 @samp{d} for double-floats,
2416 @item
2417 @samp{L} for long-floats,
2418 @end itemize
2419
2420 or @samp{e}, which denotes a default float format. The precision specifying
2421 suffix has the syntax _@var{prec} where @var{prec} denotes the number of
2422 valid mantissa digits (in decimal, excluding leading zeroes), cf. also
2423 function @samp{float_format}.
2424
2425 @item Complex numbers
2426 External representation:
2427 @itemize @asis
2428 @item
2429 In algebraic notation: @code{@var{realpart}+@var{imagpart}i}. Of course,
2430 if @var{imagpart} is negative, its printed representation begins with
2431 a @samp{-}, and the @samp{+} between @var{realpart} and @var{imagpart}
2432 may be omitted. Note that this notation cannot be used when the @var{imagpart}
2433 is rational and the rational number's base is >18, because the @samp{i}
2434 is then read as a digit.
2435 @item
2436 In Common Lisp notation: @code{#C(@var{realpart} @var{imagpart})}.
2437 @end itemize
2438 @end table
2439
2440
2441 @section Input functions
2442
2443 Including @code{<cln/io.h>} defines a number of simple input functions
2444 that read from @code{std::istream&}:
2445
2446 @table @code
2447 @item int freadchar (std::istream& stream)
2448 Reads a character from @code{stream}. Returns @code{cl_EOF} (not a @samp{char}!)
2449 if the end of stream was encountered or an error occurred.
2450
2451 @item int funreadchar (std::istream& stream, int c)
2452 Puts back @code{c} onto @code{stream}. @code{c} must be the result of the
2453 last @code{freadchar} operation on @code{stream}.
2454 @end table
2455
2456 Each of the classes @code{cl_N}, @code{cl_R}, @code{cl_RA}, @code{cl_I},
2457 @code{cl_F}, @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}
2458 defines, in @code{<cln/@var{type}_io.h>}, the following input function:
2459
2460 @table @code
2461 @item std::istream& operator>> (std::istream& stream, @var{type}& result)
2462 Reads a number from @code{stream} and stores it in the @code{result}.
2463 @end table
2464
2465 The most flexible input functions, defined in @code{<cln/@var{type}_io.h>},
2466 are the following:
2467
2468 @table @code
2469 @item cl_N read_complex (std::istream& stream, const cl_read_flags& flags)
2470 @itemx cl_R read_real (std::istream& stream, const cl_read_flags& flags)
2471 @itemx cl_F read_float (std::istream& stream, const cl_read_flags& flags)
2472 @itemx cl_RA read_rational (std::istream& stream, const cl_read_flags& flags)
2473 @itemx cl_I read_integer (std::istream& stream, const cl_read_flags& flags)
2474 Reads a number from @code{stream}. The @code{flags} are parameters which
2475 affect the input syntax. Whitespace before the number is silently skipped.
2476
2477 @item cl_N read_complex (const cl_read_flags& flags, const char * string, const char * string_limit, const char * * end_of_parse)
2478 @itemx cl_R read_real (const cl_read_flags& flags, const char * string, const char * string_limit, const char * * end_of_parse)
2479 @itemx cl_F read_float (const cl_read_flags& flags, const char * string, const char * string_limit, const char * * end_of_parse)
2480 @itemx cl_RA read_rational (const cl_read_flags& flags, const char * string, const char * string_limit, const char * * end_of_parse)
2481 @itemx cl_I read_integer (const cl_read_flags& flags, const char * string, const char * string_limit, const char * * end_of_parse)
2482 Reads a number from a string in memory. The @code{flags} are parameters which
2483 affect the input syntax. The string starts at @code{string} and ends at
2484 @code{string_limit} (exclusive limit). @code{string_limit} may also be
2485 @code{NULL}, denoting the entire string, i.e. equivalent to
2486 @code{string_limit = string + strlen(string)}. If @code{end_of_parse} is
2487 @code{NULL}, the string in memory must contain exactly one number and nothing
2488 more, else a fatal error will be signalled. If @code{end_of_parse}
2489 is not @code{NULL}, @code{*end_of_parse} will be assigned a pointer past
2490 the last parsed character (i.e. @code{string_limit} if nothing came after
2491 the number). Whitespace is not allowed.
2492 @end table
2493
2494 The structure @code{cl_read_flags} contains the following fields:
2495
2496 @table @code
2497 @item cl_read_syntax_t syntax
2498 The possible results of the read operation. Possible values are
2499 @code{syntax_number}, @code{syntax_real}, @code{syntax_rational},
2500 @code{syntax_integer}, @code{syntax_float}, @code{syntax_sfloat},
2501 @code{syntax_ffloat}, @code{syntax_dfloat}, @code{syntax_lfloat}.
2502
2503 @item cl_read_lsyntax_t lsyntax
2504 Specifies the language-dependent syntax variant for the read operation.
2505 Possible values are
2506
2507 @table @code
2508 @item lsyntax_standard
2509 accept standard algebraic notation only, no complex numbers,
2510 @item lsyntax_algebraic
2511 accept the algebraic notation @code{@var{x}+@var{y}i} for complex numbers,
2512 @item lsyntax_commonlisp
2513 accept the @code{#b}, @code{#o}, @code{#x} syntaxes for binary, octal,
2514 hexadecimal numbers,
2515 @code{#@var{base}R} for rational numbers in a given base,
2516 @code{#c(@var{realpart} @var{imagpart})} for complex numbers,
2517 @item lsyntax_all
2518 accept all of these extensions.
2519 @end table
2520
2521 @item unsigned int rational_base
2522 The base in which rational numbers are read.
2523
2524 @item float_format_t float_flags.default_float_format
2525 The float format used when reading floats with exponent marker @samp{e}.
2526
2527 @item float_format_t float_flags.default_lfloat_format
2528 The float format used when reading floats with exponent marker @samp{l}.
2529
2530 @item cl_boolean float_flags.mantissa_dependent_float_format
2531 When this flag is true, floats specified with more digits than corresponding
2532 to the exponent marker they contain, but without @var{_nnn} suffix, will get a
2533 precision corresponding to their number of significant digits.
2534 @end table
2535
2536
2537 @section Output functions
2538
2539 Including @code{<cln/io.h>} defines a number of simple output functions
2540 that write to @code{std::ostream&}:
2541
2542 @table @code
2543 @item void fprintchar (std::ostream& stream, char c)
2544 Prints the character @code{x} literally on the @code{stream}.
2545
2546 @item void fprint (std::ostream& stream, const char * string)
2547 Prints the @code{string} literally on the @code{stream}.
2548
2549 @item void fprintdecimal (std::ostream& stream, int x)
2550 @itemx void fprintdecimal (std::ostream& stream, const cl_I& x)
2551 Prints the integer @code{x} in decimal on the @code{stream}.
2552
2553 @item void fprintbinary (std::ostream& stream, const cl_I& x)
2554 Prints the integer @code{x} in binary (base 2, without prefix)
2555 on the @code{stream}.
2556
2557 @item void fprintoctal (std::ostream& stream, const cl_I& x)
2558 Prints the integer @code{x} in octal (base 8, without prefix)
2559 on the @code{stream}.
2560
2561 @item void fprinthexadecimal (std::ostream& stream, const cl_I& x)
2562 Prints the integer @code{x} in hexadecimal (base 16, without prefix)
2563 on the @code{stream}.
2564 @end table
2565
2566 Each of the classes @code{cl_N}, @code{cl_R}, @code{cl_RA}, @code{cl_I},
2567 @code{cl_F}, @code{cl_SF}, @code{cl_FF}, @code{cl_DF}, @code{cl_LF}
2568 defines, in @code{<cln/@var{type}_io.h>}, the following output functions:
2569
2570 @table @code
2571 @item void fprint (std::ostream& stream, const @var{type}& x)
2572 @itemx std::ostream& operator<< (std::ostream& stream, const @var{type}& x)
2573 Prints the number @code{x} on the @code{stream}. The output may depend
2574 on the global printer settings in the variable @code{default_print_flags}.
2575 The @code{ostream} flags and settings (flags, width and locale) are
2576 ignored.
2577 @end table
2578
2579 The most flexible output function, defined in @code{<cln/@var{type}_io.h>},
2580 are the following:
2581 @example
2582 void print_complex  (std::ostream& stream, const cl_print_flags& flags,
2583                      const cl_N& z);
2584 void print_real     (std::ostream& stream, const cl_print_flags& flags,
2585                      const cl_R& z);
2586 void print_float    (std::ostream& stream, const cl_print_flags& flags,
2587                      const cl_F& z);
2588 void print_rational (std::ostream& stream, const cl_print_flags& flags,
2589                      const cl_RA& z);
2590 void print_integer  (std::ostream& stream, const cl_print_flags& flags,
2591                      const cl_I& z);
2592 @end example
2593 Prints the number @code{x} on the @code{stream}. The @code{flags} are
2594 parameters which affect the output.
2595
2596 The structure type @code{cl_print_flags} contains the following fields:
2597
2598 @table @code
2599 @item unsigned int rational_base
2600 The base in which rational numbers are printed. Default is @code{10}.
2601
2602 @item cl_boolean rational_readably
2603 If this flag is true, rational numbers are printed with radix specifiers in
2604 Common Lisp syntax (@code{#@var{n}R} or @code{#b} or @code{#o} or @code{#x}
2605 prefixes, trailing dot). Default is false.
2606
2607 @item cl_boolean float_readably
2608 If this flag is true, type specific exponent markers have precedence over 'E'.
2609 Default is false.
2610
2611 @item float_format_t default_float_format
2612 Floating point numbers of this format will be printed using the 'E' exponent
2613 marker. Default is @code{float_format_ffloat}.
2614
2615 @item cl_boolean complex_readably
2616 If this flag is true, complex numbers will be printed using the Common Lisp
2617 syntax @code{#C(@var{realpart} @var{imagpart})}. Default is false.
2618
2619 @item cl_string univpoly_varname
2620 Univariate polynomials with no explicit indeterminate name will be printed
2621 using this variable name. Default is @code{"x"}.
2622 @end table
2623
2624 The global variable @code{default_print_flags} contains the default values,
2625 used by the function @code{fprint}.
2626
2627
2628 @chapter Rings
2629
2630 CLN has a class of abstract rings.
2631
2632 @example
2633                          Ring
2634                        cl_ring
2635                      <cln/ring.h>
2636 @end example
2637
2638 Rings can be compared for equality:
2639
2640 @table @code
2641 @item bool operator== (const cl_ring&, const cl_ring&)
2642 @itemx bool operator!= (const cl_ring&, const cl_ring&)
2643 These compare two rings for equality.
2644 @end table
2645
2646 Given a ring @code{R}, the following members can be used.
2647
2648 @table @code
2649 @item void R->fprint (std::ostream& stream, const cl_ring_element& x)
2650 @cindex @code{fprint ()}
2651 @itemx cl_boolean R->equal (const cl_ring_element& x, const cl_ring_element& y)
2652 @cindex @code{equal ()}
2653 @itemx cl_ring_element R->zero ()
2654 @cindex @code{zero ()}
2655 @itemx cl_boolean R->zerop (const cl_ring_element& x)
2656 @cindex @code{zerop ()}
2657 @itemx cl_ring_element R->plus (const cl_ring_element& x, const cl_ring_element& y)
2658 @cindex @code{plus ()}
2659 @itemx cl_ring_element R->minus (const cl_ring_element& x, const cl_ring_element& y)
2660 @cindex @code{minus ()}
2661 @itemx cl_ring_element R->uminus (const cl_ring_element& x)
2662 @cindex @code{uminus ()}
2663 @itemx cl_ring_element R->one ()
2664 @cindex @code{one ()}
2665 @itemx cl_ring_element R->canonhom (const cl_I& x)
2666 @cindex @code{canonhom ()}
2667 @itemx cl_ring_element R->mul (const cl_ring_element& x, const cl_ring_element& y)
2668 @cindex @code{mul ()}
2669 @itemx cl_ring_element R->square (const cl_ring_element& x)
2670 @cindex @code{square ()}
2671 @itemx cl_ring_element R->expt_pos (const cl_ring_element& x, const cl_I& y)
2672 @cindex @code{expt_pos ()}
2673 @end table
2674
2675 The following rings are built-in.
2676
2677 @table @code
2678 @item cl_null_ring cl_0_ring
2679 The null ring, containing only zero.
2680
2681 @item cl_complex_ring cl_C_ring
2682 The ring of complex numbers. This corresponds to the type @code{cl_N}.
2683
2684 @item cl_real_ring cl_R_ring
2685 The ring of real numbers. This corresponds to the type @code{cl_R}.
2686
2687 @item cl_rational_ring cl_RA_ring
2688 The ring of rational numbers. This corresponds to the type @code{cl_RA}.
2689
2690 @item cl_integer_ring cl_I_ring
2691 The ring of integers. This corresponds to the type @code{cl_I}.
2692 @end table
2693
2694 Type tests can be performed for any of @code{cl_C_ring}, @code{cl_R_ring},
2695 @code{cl_RA_ring}, @code{cl_I_ring}:
2696
2697 @table @code
2698 @item cl_boolean instanceof (const cl_number& x, const cl_number_ring& R)
2699 @cindex @code{instanceof ()}
2700 Tests whether the given number is an element of the number ring R.
2701 @end table
2702
2703
2704 @chapter Modular integers
2705 @cindex modular integer
2706
2707 @section Modular integer rings
2708 @cindex ring
2709
2710 CLN implements modular integers, i.e. integers modulo a fixed integer N.
2711 The modulus is explicitly part of every modular integer. CLN doesn't
2712 allow you to (accidentally) mix elements of different modular rings,
2713 e.g. @code{(3 mod 4) + (2 mod 5)} will result in a runtime error.
2714 (Ideally one would imagine a generic data type @code{cl_MI(N)}, but C++
2715 doesn't have generic types. So one has to live with runtime checks.)
2716
2717 The class of modular integer rings is
2718
2719 @example
2720                          Ring
2721                        cl_ring
2722                      <cln/ring.h>
2723                           |
2724                           |
2725                  Modular integer ring
2726                     cl_modint_ring
2727                   <cln/modinteger.h>
2728 @end example
2729 @cindex @code{cl_modint_ring}
2730
2731 and the class of all modular integers (elements of modular integer rings) is
2732
2733 @example
2734                     Modular integer
2735                          cl_MI
2736                    <cln/modinteger.h>
2737 @end example
2738
2739 Modular integer rings are constructed using the function
2740
2741 @table @code
2742 @item cl_modint_ring find_modint_ring (const cl_I& N)
2743 @cindex @code{find_modint_ring ()}
2744 This function returns the modular ring @samp{Z/NZ}. It takes care
2745 of finding out about special cases of @code{N}, like powers of two
2746 and odd numbers for which Montgomery multiplication will be a win,
2747 @cindex Montgomery multiplication
2748 and precomputes any necessary auxiliary data for computing modulo @code{N}.
2749 There is a cache table of rings, indexed by @code{N} (or, more precisely,
2750 by @code{abs(N)}). This ensures that the precomputation costs are reduced
2751 to a minimum.
2752 @end table
2753
2754 Modular integer rings can be compared for equality:
2755
2756 @table @code
2757 @item bool operator== (const cl_modint_ring&, const cl_modint_ring&)
2758 @cindex @code{operator == ()}
2759 @itemx bool operator!= (const cl_modint_ring&, const cl_modint_ring&)
2760 @cindex @code{operator != ()}
2761 These compare two modular integer rings for equality. Two different calls
2762 to @code{find_modint_ring} with the same argument necessarily return the
2763 same ring because it is memoized in the cache table.
2764 @end table
2765
2766 @section Functions on modular integers
2767
2768 Given a modular integer ring @code{R}, the following members can be used.
2769
2770 @table @code
2771 @item cl_I R->modulus
2772 @cindex @code{modulus}
2773 This is the ring's modulus, normalized to be nonnegative: @code{abs(N)}.
2774
2775 @item cl_MI R->zero()
2776 @cindex @code{zero ()}
2777 This returns @code{0 mod N}.
2778
2779 @item cl_MI R->one()
2780 @cindex @code{one ()}
2781 This returns @code{1 mod N}.
2782
2783 @item cl_MI R->canonhom (const cl_I& x)
2784 @cindex @code{canonhom ()}
2785 This returns @code{x mod N}.
2786
2787 @item cl_I R->retract (const cl_MI& x)
2788 @cindex @code{retract ()}
2789 This is a partial inverse function to @code{R->canonhom}. It returns the
2790 standard representative (@code{>=0}, @code{<N}) of @code{x}.
2791
2792 @item cl_MI R->random(random_state& randomstate)
2793 @itemx cl_MI R->random()
2794 @cindex @code{random ()}
2795 This returns a random integer modulo @code{N}.
2796 @end table
2797
2798 The following operations are defined on modular integers.
2799
2800 @table @code
2801 @item cl_modint_ring x.ring ()
2802 @cindex @code{ring ()}
2803 Returns the ring to which the modular integer @code{x} belongs.
2804
2805 @item cl_MI operator+ (const cl_MI&, const cl_MI&)
2806 @cindex @code{operator + ()}
2807 Returns the sum of two modular integers. One of the arguments may also
2808 be a plain integer.
2809
2810 @item cl_MI operator- (const cl_MI&, const cl_MI&)
2811 @cindex @code{operator - ()}
2812 Returns the difference of two modular integers. One of the arguments may also
2813 be a plain integer.
2814
2815 @item cl_MI operator- (const cl_MI&)
2816 Returns the negative of a modular integer.
2817
2818 @item cl_MI operator* (const cl_MI&, const cl_MI&)
2819 @cindex @code{operator * ()}
2820 Returns the product of two modular integers. One of the arguments may also
2821 be a plain integer.
2822
2823 @item cl_MI square (const cl_MI&)
2824 @cindex @code{square ()}
2825 Returns the square of a modular integer.
2826
2827 @item cl_MI recip (const cl_MI& x)
2828 @cindex @code{recip ()}
2829 Returns the reciprocal @code{x^-1} of a modular integer @code{x}. @code{x}
2830 must be coprime to the modulus, otherwise an error message is issued.
2831
2832 @item cl_MI div (const cl_MI& x, const cl_MI& y)
2833 @cindex @code{div ()}
2834 Returns the quotient @code{x*y^-1} of two modular integers @code{x}, @code{y}.
2835 @code{y} must be coprime to the modulus, otherwise an error message is issued.
2836
2837 @item cl_MI expt_pos (const cl_MI& x, const cl_I& y)
2838 @cindex @code{expt_pos ()}
2839 @code{y} must be > 0. Returns @code{x^y}.
2840
2841 @item cl_MI expt (const cl_MI& x, const cl_I& y)
2842 @cindex @code{expt ()}
2843 Returns @code{x^y}. If @code{y} is negative, @code{x} must be coprime to the
2844 modulus, else an error message is issued.
2845
2846 @item cl_MI operator<< (const cl_MI& x, const cl_I& y)
2847 @cindex @code{operator << ()}
2848 Returns @code{x*2^y}.
2849
2850 @item cl_MI operator>> (const cl_MI& x, const cl_I& y)
2851 @cindex @code{operator >> ()}
2852 Returns @code{x*2^-y}. When @code{y} is positive, the modulus must be odd,
2853 or an error message is issued.
2854
2855 @item bool operator== (const cl_MI&, const cl_MI&)
2856 @cindex @code{operator == ()}
2857 @itemx bool operator!= (const cl_MI&, const cl_MI&)
2858 @cindex @code{operator != ()}
2859 Compares two modular integers, belonging to the same modular integer ring,
2860 for equality.
2861
2862 @item cl_boolean zerop (const cl_MI& x)
2863 @cindex @code{zerop ()}
2864 Returns true if @code{x} is @code{0 mod N}.
2865 @end table
2866
2867 The following output functions are defined (see also the chapter on
2868 input/output).
2869
2870 @table @code
2871 @item void fprint (std::ostream& stream, const cl_MI& x)
2872 @cindex @code{fprint ()}
2873 @itemx std::ostream& operator<< (std::ostream& stream, const cl_MI& x)
2874 @cindex @code{operator << ()}
2875 Prints the modular integer @code{x} on the @code{stream}. The output may depend
2876 on the global printer settings in the variable @code{default_print_flags}.
2877 @end table
2878
2879
2880 @chapter Symbolic data types
2881 @cindex symbolic type
2882
2883 CLN implements two symbolic (non-numeric) data types: strings and symbols.
2884
2885 @section Strings
2886 @cindex string
2887 @cindex @code{cl_string}
2888
2889 The class
2890
2891 @example
2892                       String
2893                      cl_string
2894                    <cln/string.h>
2895 @end example
2896
2897 implements immutable strings.
2898
2899 Strings are constructed through the following constructors:
2900
2901 @table @code
2902 @item cl_string (const char * s)
2903 Returns an immutable copy of the (zero-terminated) C string @code{s}.
2904
2905 @item cl_string (const char * ptr, unsigned long len)
2906 Returns an immutable copy of the @code{len} characters at
2907 @code{ptr[0]}, @dots{}, @code{ptr[len-1]}. NUL characters are allowed.
2908 @end table
2909
2910 The following functions are available on strings:
2911
2912 @table @code
2913 @item operator =
2914 Assignment from @code{cl_string} and @code{const char *}.
2915
2916 @item s.length()
2917 @cindex @code{length ()}
2918 @itemx strlen(s)
2919 @cindex @code{strlen ()}
2920 Returns the length of the string @code{s}.
2921
2922 @item s[i]
2923 @cindex @code{operator [] ()}
2924 Returns the @code{i}th character of the string @code{s}.
2925 @code{i} must be in the range @code{0 <= i < s.length()}.
2926
2927 @item bool equal (const cl_string& s1, const cl_string& s2)
2928 @cindex @code{equal ()}
2929 Compares two strings for equality. One of the arguments may also be a
2930 plain @code{const char *}.
2931 @end table
2932
2933 @section Symbols
2934 @cindex symbol
2935 @cindex @code{cl_symbol}
2936
2937 Symbols are uniquified strings: all symbols with the same name are shared.
2938 This means that comparison of two symbols is fast (effectively just a pointer
2939 comparison), whereas comparison of two strings must in the worst case walk
2940 both strings until their end.
2941 Symbols are used, for example, as tags for properties, as names of variables
2942 in polynomial rings, etc.
2943
2944 Symbols are constructed through the following constructor:
2945
2946 @table @code
2947 @item cl_symbol (const cl_string& s)
2948 Looks up or creates a new symbol with a given name.
2949 @end table
2950
2951 The following operations are available on symbols:
2952
2953 @table @code
2954 @item cl_string (const cl_symbol& sym)
2955 Conversion to @code{cl_string}: Returns the string which names the symbol
2956 @code{sym}.
2957
2958 @item bool equal (const cl_symbol& sym1, const cl_symbol& sym2)
2959 @cindex @code{equal ()}
2960 Compares two symbols for equality. This is very fast.
2961 @end table
2962
2963
2964 @chapter Univariate polynomials
2965 @cindex polynomial
2966 @cindex univariate polynomial
2967
2968 @section Univariate polynomial rings
2969
2970 CLN implements univariate polynomials (polynomials in one variable) over an
2971 arbitrary ring. The indeterminate variable may be either unnamed (and will be
2972 printed according to @code{default_print_flags.univpoly_varname}, which
2973 defaults to @samp{x}) or carry a given name. The base ring and the
2974 indeterminate are explicitly part of every polynomial. CLN doesn't allow you to
2975 (accidentally) mix elements of different polynomial rings, e.g.
2976 @code{(a^2+1) * (b^3-1)} will result in a runtime error. (Ideally this should
2977 return a multivariate polynomial, but they are not yet implemented in CLN.)
2978
2979 The classes of univariate polynomial rings are
2980
2981 @example
2982                            Ring
2983                          cl_ring
2984                        <cln/ring.h>
2985                             |
2986                             |
2987                  Univariate polynomial ring
2988                       cl_univpoly_ring
2989                       <cln/univpoly.h>
2990                             |
2991            +----------------+-------------------+
2992            |                |                   |
2993  Complex polynomial ring    |    Modular integer polynomial ring
2994  cl_univpoly_complex_ring   |        cl_univpoly_modint_ring
2995  <cln/univpoly_complex.h>   |        <cln/univpoly_modint.h>
2996                             |
2997            +----------------+
2998            |                |
2999    Real polynomial ring     |
3000    cl_univpoly_real_ring    |
3001    <cln/univpoly_real.h>    |
3002                             |
3003            +----------------+
3004            |                |
3005  Rational polynomial ring   |
3006  cl_univpoly_rational_ring  |
3007  <cln/univpoly_rational.h>  |
3008                             |
3009            +----------------+
3010            |
3011  Integer polynomial ring
3012  cl_univpoly_integer_ring
3013  <cln/univpoly_integer.h>
3014 @end example
3015
3016 and the corresponding classes of univariate polynomials are
3017
3018 @example
3019                    Univariate polynomial
3020                           cl_UP
3021                       <cln/univpoly.h>
3022                             |
3023            +----------------+-------------------+
3024            |                |                   |
3025    Complex polynomial       |      Modular integer polynomial
3026         cl_UP_N             |                cl_UP_MI
3027  <cln/univpoly_complex.h>   |        <cln/univpoly_modint.h>
3028                             |
3029            +----------------+
3030            |                |
3031      Real polynomial        |
3032         cl_UP_R             |
3033   <cln/univpoly_real.h>     |
3034                             |
3035            +----------------+
3036            |                |
3037    Rational polynomial      |
3038         cl_UP_RA            |
3039  <cln/univpoly_rational.h>  |
3040                             |
3041            +----------------+
3042            |
3043    Integer polynomial
3044         cl_UP_I
3045  <cln/univpoly_integer.h>
3046 @end example
3047
3048 Univariate polynomial rings are constructed using the functions
3049
3050 @table @code
3051 @item cl_univpoly_ring find_univpoly_ring (const cl_ring& R)
3052 @itemx cl_univpoly_ring find_univpoly_ring (const cl_ring& R, const cl_symbol& varname)
3053 This function returns the polynomial ring @samp{R[X]}, unnamed or named.
3054 @code{R} may be an arbitrary ring. This function takes care of finding out
3055 about special cases of @code{R}, such as the rings of complex numbers,
3056 real numbers, rational numbers, integers, or modular integer rings.
3057 There is a cache table of rings, indexed by @code{R} and @code{varname}.
3058 This ensures that two calls of this function with the same arguments will
3059 return the same polynomial ring.
3060
3061 @itemx cl_univpoly_complex_ring find_univpoly_ring (const cl_complex_ring& R)
3062 @cindex @code{find_univpoly_ring ()}
3063 @itemx cl_univpoly_complex_ring find_univpoly_ring (const cl_complex_ring& R, const cl_symbol& varname)
3064 @itemx cl_univpoly_real_ring find_univpoly_ring (const cl_real_ring& R)
3065 @itemx cl_univpoly_real_ring find_univpoly_ring (const cl_real_ring& R, const cl_symbol& varname)
3066 @itemx cl_univpoly_rational_ring find_univpoly_ring (const cl_rational_ring& R)
3067 @itemx cl_univpoly_rational_ring find_univpoly_ring (const cl_rational_ring& R, const cl_symbol& varname)
3068 @itemx cl_univpoly_integer_ring find_univpoly_ring (const cl_integer_ring& R)
3069 @itemx cl_univpoly_integer_ring find_univpoly_ring (const cl_integer_ring& R, const cl_symbol& varname)
3070 @itemx cl_univpoly_modint_ring find_univpoly_ring (const cl_modint_ring& R)
3071 @itemx cl_univpoly_modint_ring find_univpoly_ring (const cl_modint_ring& R, const cl_symbol& varname)
3072 These functions are equivalent to the general @code{find_univpoly_ring},
3073 only the return type is more specific, according to the base ring's type.
3074 @end table
3075
3076 @section Functions on univariate polynomials
3077
3078 Given a univariate polynomial ring @code{R}, the following members can be used.
3079
3080 @table @code
3081 @item cl_ring R->basering()
3082 @cindex @code{basering ()}
3083 This returns the base ring, as passed to @samp{find_univpoly_ring}.
3084
3085 @item cl_UP R->zero()
3086 @cindex @code{zero ()}
3087 This returns @code{0 in R}, a polynomial of degree -1.
3088
3089 @item cl_UP R->one()
3090 @cindex @code{one ()}
3091 This returns @code{1 in R}, a polynomial of degree <= 0.
3092
3093 @item cl_UP R->canonhom (const cl_I& x)
3094 @cindex @code{canonhom ()}
3095 This returns @code{x in R}, a polynomial of degree <= 0.
3096
3097 @item cl_UP R->monomial (const cl_ring_element& x, uintL e)
3098 @cindex @code{monomial ()}
3099 This returns a sparse polynomial: @code{x * X^e}, where @code{X} is the
3100 indeterminate.
3101
3102 @item cl_UP R->create (sintL degree)
3103 @cindex @code{create ()}
3104 Creates a new polynomial with a given degree. The zero polynomial has degree
3105 @code{-1}. After creating the polynomial, you should put in the coefficients,
3106 using the @code{set_coeff} member function, and then call the @code{finalize}
3107 member function.
3108 @end table
3109
3110 The following are the only destructive operations on univariate polynomials.
3111
3112 @table @code
3113 @item void set_coeff (cl_UP& x, uintL index, const cl_ring_element& y)
3114 @cindex @code{set_coeff ()}
3115 This changes the coefficient of @code{X^index} in @code{x} to be @code{y}.
3116 After changing a polynomial and before applying any "normal" operation on it,
3117 you should call its @code{finalize} member function.
3118
3119 @item void finalize (cl_UP& x)
3120 @cindex @code{finalize ()}
3121 This function marks the endpoint of destructive modifications of a polynomial.
3122 It normalizes the internal representation so that subsequent computations have
3123 less overhead. Doing normal computations on unnormalized polynomials may
3124 produce wrong results or crash the program.
3125 @end table
3126
3127 The following operations are defined on univariate polynomials.
3128
3129 @table @code
3130 @item cl_univpoly_ring x.ring ()
3131 @cindex @code{ring ()}
3132 Returns the ring to which the univariate polynomial @code{x} belongs.
3133
3134 @item cl_UP operator+ (const cl_UP&, const cl_UP&)
3135 @cindex @code{operator + ()}
3136 Returns the sum of two univariate polynomials.
3137
3138 @item cl_UP operator- (const cl_UP&, const cl_UP&)
3139 @cindex @code{operator - ()}
3140 Returns the difference of two univariate polynomials.
3141
3142 @item cl_UP operator- (const cl_UP&)
3143 Returns the negative of a univariate polynomial.
3144
3145 @item cl_UP operator* (const cl_UP&, const cl_UP&)
3146 @cindex @code{operator * ()}
3147 Returns the product of two univariate polynomials. One of the arguments may
3148 also be a plain integer or an element of the base ring.
3149
3150 @item cl_UP square (const cl_UP&)
3151 @cindex @code{square ()}
3152 Returns the square of a univariate polynomial.
3153
3154 @item cl_UP expt_pos (const cl_UP& x, const cl_I& y)
3155 @cindex @code{expt_pos ()}
3156 @code{y} must be > 0. Returns @code{x^y}.
3157
3158 @item bool operator== (const cl_UP&, const cl_UP&)
3159 @cindex @code{operator == ()}
3160 @itemx bool operator!= (const cl_UP&, const cl_UP&)
3161 @cindex @code{operator != ()}
3162 Compares two univariate polynomials, belonging to the same univariate
3163 polynomial ring, for equality.
3164
3165 @item cl_boolean zerop (const cl_UP& x)
3166 @cindex @code{zerop ()}
3167 Returns true if @code{x} is @code{0 in R}.
3168
3169 @item sintL degree (const cl_UP& x)
3170 @cindex @code{degree ()}
3171 Returns the degree of the polynomial. The zero polynomial has degree @code{-1}.
3172
3173 @item cl_ring_element coeff (const cl_UP& x, uintL index)
3174 @cindex @code{coeff ()}
3175 Returns the coefficient of @code{X^index} in the polynomial @code{x}.
3176
3177 @item cl_ring_element x (const cl_ring_element& y)
3178 @cindex @code{operator () ()}
3179 Evaluation: If @code{x} is a polynomial and @code{y} belongs to the base ring,
3180 then @samp{x(y)} returns the value of the substitution of @code{y} into
3181 @code{x}.
3182
3183 @item cl_UP deriv (const cl_UP& x)
3184 @cindex @code{deriv ()}
3185 Returns the derivative of the polynomial @code{x} with respect to the
3186 indeterminate @code{X}.
3187 @end table
3188
3189 The following output functions are defined (see also the chapter on
3190 input/output).
3191
3192 @table @code
3193 @item void fprint (std::ostream& stream, const cl_UP& x)
3194 @cindex @code{fprint ()}
3195 @itemx std::ostream& operator<< (std::ostream& stream, const cl_UP& x)
3196 @cindex @code{operator << ()}
3197 Prints the univariate polynomial @code{x} on the @code{stream}. The output may
3198 depend on the global printer settings in the variable
3199 @code{default_print_flags}.
3200 @end table
3201
3202 @section Special polynomials
3203
3204 The following functions return special polynomials.
3205
3206 @table @code
3207 @item cl_UP_I tschebychev (sintL n)
3208 @cindex @code{tschebychev ()}
3209 @cindex Chebyshev polynomial
3210 Returns the n-th Chebyshev polynomial (n >= 0).
3211
3212 @item cl_UP_I hermite (sintL n)
3213 @cindex @code{hermite ()}
3214 @cindex Hermite polynomial
3215 Returns the n-th Hermite polynomial (n >= 0).
3216
3217 @item cl_UP_RA legendre (sintL n)
3218 @cindex @code{legendre ()}
3219 @cindex Legende polynomial
3220 Returns the n-th Legendre polynomial (n >= 0).
3221
3222 @item cl_UP_I laguerre (sintL n)
3223 @cindex @code{laguerre ()}
3224 @cindex Laguerre polynomial
3225 Returns the n-th Laguerre polynomial (n >= 0).
3226 @end table
3227
3228 Information how to derive the differential equation satisfied by each
3229 of these polynomials from their definition can be found in the
3230 @code{doc/polynomial/} directory.
3231
3232
3233 @chapter Internals
3234
3235 @section Why C++ ?
3236 @cindex advocacy
3237
3238 Using C++ as an implementation language provides
3239
3240 @itemize @bullet
3241 @item
3242 Efficiency: It compiles to machine code.
3243
3244 @item
3245 @cindex portability
3246 Portability: It runs on all platforms supporting a C++ compiler. Because
3247 of the availability of GNU C++, this includes all currently used 32-bit and
3248 64-bit platforms, independently of the quality of the vendor's C++ compiler.
3249
3250 @item
3251 Type safety: The C++ compilers knows about the number types and complains if,
3252 for example, you try to assign a float to an integer variable. However,
3253 a drawback is that C++ doesn't know about generic types, hence a restriction
3254 like that @code{operator+ (const cl_MI&, const cl_MI&)} requires that both
3255 arguments belong to the same modular ring cannot be expressed as a compile-time
3256 information.
3257
3258 @item
3259 Algebraic syntax: The elementary operations @code{+}, @code{-}, @code{*},
3260 @code{=}, @code{==}, ... can be used in infix notation, which is more
3261 convenient than Lisp notation @samp{(+ x y)} or C notation @samp{add(x,y,&z)}.
3262 @end itemize
3263
3264 With these language features, there is no need for two separate languages,
3265 one for the implementation of the library and one in which the library's users
3266 can program. This means that a prototype implementation of an algorithm
3267 can be integrated into the library immediately after it has been tested and
3268 debugged. No need to rewrite it in a low-level language after having prototyped
3269 in a high-level language.
3270
3271
3272 @section Memory efficiency
3273
3274 In order to save memory allocations, CLN implements:
3275
3276 @itemize @bullet
3277 @item
3278 Object sharing: An operation like @code{x+0} returns @code{x} without copying
3279 it.
3280 @item
3281 @cindex garbage collection
3282 @cindex reference counting
3283 Garbage collection: A reference counting mechanism makes sure that any
3284 number object's storage is freed immediately when the last reference to the
3285 object is gone.
3286 @item
3287 @cindex immediate numbers
3288 Small integers are represented as immediate values instead of pointers
3289 to heap allocated storage. This means that integers @code{> -2^29},
3290 @code{< 2^29} don't consume heap memory, unless they were explicitly allocated
3291 on the heap.
3292 @end itemize
3293
3294
3295 @section Speed efficiency
3296
3297 Speed efficiency is obtained by the combination of the following tricks
3298 and algorithms:
3299
3300 @itemize @bullet
3301 @item
3302 Small integers, being represented as immediate values, don't require
3303 memory access, just a couple of instructions for each elementary operation.
3304 @item
3305 The kernel of CLN has been written in assembly language for some CPUs
3306 (@code{i386}, @code{m68k}, @code{sparc}, @code{mips}, @code{arm}).
3307 @item
3308 On all CPUs, CLN may be configured to use the superefficient low-level
3309 routines from GNU GMP version 3.
3310 @item
3311 For large numbers, CLN uses, instead of the standard @code{O(N^2)}
3312 algorithm, the Karatsuba multiplication, which is an
3313 @iftex
3314 @tex
3315 $O(N^{1.6})$
3316 @end tex
3317 @end iftex
3318 @ifinfo
3319 @code{O(N^1.6)}
3320 @end ifinfo
3321 algorithm.
3322 @item
3323 For very large numbers (more than 12000 decimal digits), CLN uses
3324 @iftex
3325 Sch{@"o}nhage-Strassen
3326 @cindex Sch{@"o}nhage-Strassen multiplication
3327 @end iftex
3328 @ifinfo
3329 Schönhage-Strassen
3330 @cindex Schönhage-Strassen multiplication
3331 @end ifinfo
3332 multiplication, which is an asymptotically optimal multiplication 
3333 algorithm.
3334 @item
3335 These fast multiplication algorithms also give improvements in the speed
3336 of division and radix conversion.
3337 @end itemize
3338
3339
3340 @section Garbage collection
3341 @cindex garbage collection
3342
3343 All the number classes are reference count classes: They only contain a pointer
3344 to an object in the heap. Upon construction, assignment and destruction of
3345 number objects, only the objects' reference count are manipulated.
3346
3347 Memory occupied by number objects are automatically reclaimed as soon as
3348 their reference count drops to zero.
3349
3350 For number rings, another strategy is implemented: There is a cache of,
3351 for example, the modular integer rings. A modular integer ring is destroyed
3352 only if its reference count dropped to zero and the cache is about to be
3353 resized. The effect of this strategy is that recently used rings remain
3354 cached, whereas undue memory consumption through cached rings is avoided.
3355
3356
3357 @chapter Using the library
3358
3359 For the following discussion, we will assume that you have installed
3360 the CLN source in @code{$CLN_DIR} and built it in @code{$CLN_TARGETDIR}.
3361 For example, for me it's @code{CLN_DIR="$HOME/cln"} and
3362 @code{CLN_TARGETDIR="$HOME/cln/linuxelf"}. You might define these as
3363 environment variables, or directly substitute the appropriate values.
3364
3365
3366 @section Compiler options
3367 @cindex compiler options
3368
3369 Until you have installed CLN in a public place, the following options are
3370 needed:
3371
3372 When you compile CLN application code, add the flags
3373 @example
3374    -I$CLN_DIR/include -I$CLN_TARGETDIR/include
3375 @end example
3376 to the C++ compiler's command line (@code{make} variable CFLAGS or CXXFLAGS).
3377 When you link CLN application code to form an executable, add the flags
3378 @example
3379    $CLN_TARGETDIR/src/libcln.a
3380 @end example
3381 to the C/C++ compiler's command line (@code{make} variable LIBS).
3382
3383 If you did a @code{make install}, the include files are installed in a
3384 public directory (normally @code{/usr/local/include}), hence you don't
3385 need special flags for compiling. The library has been installed to a
3386 public directory as well (normally @code{/usr/local/lib}), hence when
3387 linking a CLN application it is sufficient to give the flag @code{-lcln}.
3388
3389 Since CLN version 1.1, there are two tools to make the creation of
3390 software packages that use CLN easier:
3391 @itemize @bullet
3392 @item
3393 @cindex @code{cln-config}
3394 @code{cln-config} is a shell script that you can use to determine the
3395 compiler and linker command line options required to compile and link a
3396 program with CLN.  Start it with @code{--help} to learn about its options
3397 or consult the manpage that comes with it.
3398 @item
3399 @cindex @code{AC_PATH_CLN}
3400 @code{AC_PATH_CLN} is for packages configured using GNU automake.
3401 The synopsis is:
3402 @example
3403 @code{AC_PATH_CLN([@var{MIN-VERSION}, [@var{ACTION-IF-FOUND} [, @var{ACTION-IF-NOT-FOUND}]]])}
3404 @end example
3405 This macro determines the location of CLN using @code{cln-config}, which
3406 is either found in the user's path, or from the environment variable
3407 @code{CLN_CONFIG}.  It tests the installed libraries to make sure that
3408 their version is not earlier than @var{MIN-VERSION} (a default version
3409 will be used if not specified). If the required version was found, sets
3410 the @env{CLN_CPPFLAGS} and the @env{CLN_LIBS} variables. This
3411 macro is in the file @file{cln.m4} which is installed in
3412 @file{$datadir/aclocal}. Note that if automake was installed with a
3413 different @samp{--prefix} than CLN, you will either have to manually
3414 move @file{cln.m4} to automake's @file{$datadir/aclocal}, or give
3415 aclocal the @samp{-I} option when running it. Here is a possible example
3416 to be included in your package's @file{configure.ac}:
3417 @example
3418 AC_PATH_CLN(1.1.0, [
3419   LIBS="$LIBS $CLN_LIBS"
3420   CPPFLAGS="$CPPFLAGS $CLN_CPPFLAGS"
3421 ], AC_MSG_ERROR([No suitable installed version of CLN could be found.]))
3422 @end example
3423 @end itemize
3424
3425
3426 @section Compatibility to old CLN versions
3427 @cindex namespace
3428 @cindex compatibility
3429
3430 As of CLN version 1.1 all non-macro identifiers were hidden in namespace
3431 @code{cln} in order to avoid potential name clashes with other C++
3432 libraries. If you have an old application, you will have to manually
3433 port it to the new scheme. The following principles will help during
3434 the transition:
3435 @itemize @bullet
3436 @item
3437 All headers are now in a separate subdirectory. Instead of including
3438 @code{cl_}@var{something}@code{.h}, include
3439 @code{cln/}@var{something}@code{.h} now.
3440 @item
3441 All public identifiers (typenames and functions) have lost their
3442 @code{cl_} prefix.  Exceptions are all the typenames of number types,
3443 (cl_N, cl_I, cl_MI, @dots{}), rings, symbolic types (cl_string,
3444 cl_symbol) and polynomials (cl_UP_@var{type}).  (This is because their
3445 names would not be mnemonic enough once the namespace @code{cln} is
3446 imported. Even in a namespace we favor @code{cl_N} over @code{N}.)
3447 @item
3448 All public @emph{functions} that had by a @code{cl_} in their name still
3449 carry that @code{cl_} if it is intrinsic part of a typename (as in
3450 @code{cl_I_to_int ()}).
3451 @end itemize
3452 When developing other libraries, please keep in mind not to import the
3453 namespace @code{cln} in one of your public header files by saying
3454 @code{using namespace cln;}. This would propagate to other applications
3455 and can cause name clashes there.
3456
3457
3458 @section Include files
3459 @cindex include files
3460 @cindex header files
3461
3462 Here is a summary of the include files and their contents.
3463
3464 @table @code
3465 @item <cln/object.h>
3466 General definitions, reference counting, garbage collection.
3467 @item <cln/number.h>
3468 The class cl_number.
3469 @item <cln/complex.h>
3470 Functions for class cl_N, the complex numbers.
3471 @item <cln/real.h>
3472 Functions for class cl_R, the real numbers.
3473 @item <cln/float.h>
3474 Functions for class cl_F, the floats.
3475 @item <cln/sfloat.h>
3476 Functions for class cl_SF, the short-floats.
3477 @item <cln/ffloat.h>
3478 Functions for class cl_FF, the single-floats.
3479 @item <cln/dfloat.h>
3480 Functions for class cl_DF, the double-floats.
3481 @item <cln/lfloat.h>
3482 Functions for class cl_LF, the long-floats.
3483 @item <cln/rational.h>
3484 Functions for class cl_RA, the rational numbers.
3485 @item <cln/integer.h>
3486 Functions for class cl_I, the integers.
3487 @item <cln/io.h>
3488 Input/Output.
3489 @item <cln/complex_io.h>
3490 Input/Output for class cl_N, the complex numbers.
3491 @item <cln/real_io.h>
3492 Input/Output for class cl_R, the real numbers.
3493 @item <cln/float_io.h>
3494 Input/Output for class cl_F, the floats.
3495 @item <cln/sfloat_io.h>
3496 Input/Output for class cl_SF, the short-floats.
3497 @item <cln/ffloat_io.h>
3498 Input/Output for class cl_FF, the single-floats.
3499 @item <cln/dfloat_io.h>
3500 Input/Output for class cl_DF, the double-floats.
3501 @item <cln/lfloat_io.h>
3502 Input/Output for class cl_LF, the long-floats.
3503 @item <cln/rational_io.h>
3504 Input/Output for class cl_RA, the rational numbers.
3505 @item <cln/integer_io.h>
3506 Input/Output for class cl_I, the integers.
3507 @item <cln/input.h>
3508 Flags for customizing input operations.
3509 @item <cln/output.h>
3510 Flags for customizing output operations.
3511 @item <cln/malloc.h>
3512 @code{malloc_hook}, @code{free_hook}.
3513 @item <cln/abort.h>
3514 @code{cl_abort}.
3515 @item <cln/condition.h>
3516 Conditions/exceptions.
3517 @item <cln/string.h>
3518 Strings.
3519 @item <cln/symbol.h>
3520 Symbols.
3521 @item <cln/proplist.h>
3522 Property lists.
3523 @item <cln/ring.h>
3524 General rings.
3525 @item <cln/null_ring.h>
3526 The null ring.
3527 @item <cln/complex_ring.h>
3528 The ring of complex numbers.
3529 @item <cln/real_ring.h>
3530 The ring of real numbers.
3531 @item <cln/rational_ring.h>
3532 The ring of rational numbers.
3533 @item <cln/integer_ring.h>
3534 The ring of integers.
3535 @item <cln/numtheory.h>
3536 Number threory functions.
3537 @item <cln/modinteger.h>
3538 Modular integers.
3539 @item <cln/V.h>
3540 Vectors.
3541 @item <cln/GV.h>
3542 General vectors.
3543 @item <cln/GV_number.h>
3544 General vectors over cl_number.
3545 @item <cln/GV_complex.h>
3546 General vectors over cl_N.
3547 @item <cln/GV_real.h>
3548 General vectors over cl_R.
3549 @item <cln/GV_rational.h>
3550 General vectors over cl_RA.
3551 @item <cln/GV_integer.h>
3552 General vectors over cl_I.
3553 @item <cln/GV_modinteger.h>
3554 General vectors of modular integers.
3555 @item <cln/SV.h>
3556 Simple vectors.
3557 @item <cln/SV_number.h>
3558 Simple vectors over cl_number.
3559 @item <cln/SV_complex.h>
3560 Simple vectors over cl_N.
3561 @item <cln/SV_real.h>
3562 Simple vectors over cl_R.
3563 @item <cln/SV_rational.h>
3564 Simple vectors over cl_RA.
3565 @item <cln/SV_integer.h>
3566 Simple vectors over cl_I.
3567 @item <cln/SV_ringelt.h>
3568 Simple vectors of general ring elements.
3569 @item <cln/univpoly.h>
3570 Univariate polynomials.
3571 @item <cln/univpoly_integer.h>
3572 Univariate polynomials over the integers.
3573 @item <cln/univpoly_rational.h>
3574 Univariate polynomials over the rational numbers.
3575 @item <cln/univpoly_real.h>
3576 Univariate polynomials over the real numbers.
3577 @item <cln/univpoly_complex.h>
3578 Univariate polynomials over the complex numbers.
3579 @item <cln/univpoly_modint.h>
3580 Univariate polynomials over modular integer rings.
3581 @item <cln/timing.h>
3582 Timing facilities.
3583 @item <cln/cln.h>
3584 Includes all of the above.
3585 @end table
3586
3587
3588 @section An Example
3589
3590 A function which computes the nth Fibonacci number can be written as follows.
3591 @cindex Fibonacci number
3592
3593 @example
3594 #include <cln/integer.h>
3595 #include <cln/real.h>
3596 using namespace cln;
3597
3598 // Returns F_n, computed as the nearest integer to
3599 // ((1+sqrt(5))/2)^n/sqrt(5). Assume n>=0.
3600 const cl_I fibonacci (int n)
3601 @{
3602         // Need a precision of ((1+sqrt(5))/2)^-n.
3603         float_format_t prec = float_format((int)(0.208987641*n+5));
3604         cl_R sqrt5 = sqrt(cl_float(5,prec));
3605         cl_R phi = (1+sqrt5)/2;
3606         return round1( expt(phi,n)/sqrt5 );
3607 @}
3608 @end example
3609
3610 Let's explain what is going on in detail.
3611
3612 The include file @code{<cln/integer.h>} is necessary because the type
3613 @code{cl_I} is used in the function, and the include file @code{<cln/real.h>}
3614 is needed for the type @code{cl_R} and the floating point number functions.
3615 The order of the include files does not matter.  In order not to write
3616 out @code{cln::}@var{foo} in this simple example we can safely import
3617 the whole namespace @code{cln}.
3618
3619 Then comes the function declaration. The argument is an @code{int}, the
3620 result an integer. The return type is defined as @samp{const cl_I}, not
3621 simply @samp{cl_I}, because that allows the compiler to detect typos like
3622 @samp{fibonacci(n) = 100}. It would be possible to declare the return
3623 type as @code{const cl_R} (real number) or even @code{const cl_N} (complex
3624 number). We use the most specialized possible return type because functions
3625 which call @samp{fibonacci} will be able to profit from the compiler's type
3626 analysis: Adding two integers is slightly more efficient than adding the
3627 same objects declared as complex numbers, because it needs less type
3628 dispatch. Also, when linking to CLN as a non-shared library, this minimizes
3629 the size of the resulting executable program.
3630
3631 The result will be computed as expt(phi,n)/sqrt(5), rounded to the nearest
3632 integer. In order to get a correct result, the absolute error should be less
3633 than 1/2, i.e. the relative error should be less than sqrt(5)/(2*expt(phi,n)).
3634 To this end, the first line computes a floating point precision for sqrt(5)
3635 and phi.
3636
3637 Then sqrt(5) is computed by first converting the integer 5 to a floating point
3638 number and than taking the square root. The converse, first taking the square
3639 root of 5, and then converting to the desired precision, would not work in
3640 CLN: The square root would be computed to a default precision (normally
3641 single-float precision), and the following conversion could not help about
3642 the lacking accuracy. This is because CLN is not a symbolic computer algebra
3643 system and does not represent sqrt(5) in a non-numeric way.
3644
3645 The type @code{cl_R} for sqrt5 and, in the following line, phi is the only
3646 possible choice. You cannot write @code{cl_F} because the C++ compiler can
3647 only infer that @code{cl_float(5,prec)} is a real number. You cannot write
3648 @code{cl_N} because a @samp{round1} does not exist for general complex
3649 numbers.
3650
3651 When the function returns, all the local variables in the function are
3652 automatically reclaimed (garbage collected). Only the result survives and
3653 gets passed to the caller.
3654
3655 The file @code{fibonacci.cc} in the subdirectory @code{examples}
3656 contains this implementation together with an even faster algorithm.
3657
3658 @section Debugging support
3659 @cindex debugging
3660
3661 When debugging a CLN application with GNU @code{gdb}, two facilities are
3662 available from the library:
3663
3664 @itemize @bullet
3665 @item The library does type checks, range checks, consistency checks at
3666 many places. When one of these fails, the function @code{cl_abort()} is
3667 called. Its default implementation is to perform an @code{exit(1)}, so
3668 you won't have a core dump. But for debugging, it is best to set a
3669 breakpoint at this function:
3670 @example
3671 (gdb) break cl_abort
3672 @end example
3673 When this breakpoint is hit, look at the stack's backtrace:
3674 @example
3675 (gdb) where
3676 @end example
3677
3678 @item The debugger's normal @code{print} command doesn't know about
3679 CLN's types and therefore prints mostly useless hexadecimal addresses.
3680 CLN offers a function @code{cl_print}, callable from the debugger,
3681 for printing number objects. In order to get this function, you have
3682 to define the macro @samp{CL_DEBUG} and then include all the header files
3683 for which you want @code{cl_print} debugging support. For example:
3684 @cindex @code{CL_DEBUG}
3685 @example
3686 #define CL_DEBUG
3687 #include <cln/string.h>
3688 @end example
3689 Now, if you have in your program a variable @code{cl_string s}, and
3690 inspect it under @code{gdb}, the output may look like this:
3691 @example
3692 (gdb) print s
3693 $7 = @{<cl_gcpointer> = @{ = @{pointer = 0x8055b60, heappointer = 0x8055b60,
3694   word = 134568800@}@}, @}
3695 (gdb) call cl_print(s)
3696 (cl_string) ""
3697 $8 = 134568800
3698 @end example
3699 Note that the output of @code{cl_print} goes to the program's error output,
3700 not to gdb's standard output.
3701
3702 Note, however, that the above facility does not work with all CLN types,
3703 only with number objects and similar. Therefore CLN offers a member function
3704 @code{debug_print()} on all CLN types. The same macro @samp{CL_DEBUG}
3705 is needed for this member function to be implemented. Under @code{gdb},
3706 you call it like this:
3707 @cindex @code{debug_print ()}
3708 @example
3709 (gdb) print s
3710 $7 = @{<cl_gcpointer> = @{ = @{pointer = 0x8055b60, heappointer = 0x8055b60,
3711   word = 134568800@}@}, @}
3712 (gdb) call s.debug_print()
3713 (cl_string) ""
3714 (gdb) define cprint
3715 >call ($1).debug_print()
3716 >end
3717 (gdb) cprint s
3718 (cl_string) ""
3719 @end example
3720 Unfortunately, this feature does not seem to work under all circumstances.
3721 @end itemize
3722
3723
3724 @chapter Customizing
3725 @cindex customizing
3726
3727 @section Error handling
3728
3729 When a fatal error occurs, an error message is output to the standard error
3730 output stream, and the function @code{cl_abort} is called. The default
3731 version of this function (provided in the library) terminates the application.
3732 To catch such a fatal error, you need to define the function @code{cl_abort}
3733 yourself, with the prototype
3734 @example
3735 #include <cln/abort.h>
3736 void cl_abort (void);
3737 @end example
3738 @cindex @code{cl_abort ()}
3739 This function must not return control to its caller.
3740
3741
3742 @section Floating-point underflow
3743 @cindex underflow
3744
3745 Floating point underflow denotes the situation when a floating-point number
3746 is to be created which is so close to @code{0} that its exponent is too
3747 low to be represented internally. By default, this causes a fatal error.
3748 If you set the global variable
3749 @example
3750 cl_boolean cl_inhibit_floating_point_underflow
3751 @end example
3752 to @code{cl_true}, the error will be inhibited, and a floating-point zero
3753 will be generated instead.  The default value of 
3754 @code{cl_inhibit_floating_point_underflow} is @code{cl_false}.
3755
3756
3757 @section Customizing I/O
3758
3759 The output of the function @code{fprint} may be customized by changing the
3760 value of the global variable @code{default_print_flags}.
3761 @cindex @code{default_print_flags}
3762
3763
3764 @section Customizing the memory allocator
3765
3766 Every memory allocation of CLN is done through the function pointer
3767 @code{malloc_hook}. Freeing of this memory is done through the function
3768 pointer @code{free_hook}. The default versions of these functions,
3769 provided in the library, call @code{malloc} and @code{free} and check
3770 the @code{malloc} result against @code{NULL}.
3771 If you want to provide another memory allocator, you need to define
3772 the variables @code{malloc_hook} and @code{free_hook} yourself,
3773 like this:
3774 @example
3775 #include <cln/malloc.h>
3776 namespace cln @{
3777         void* (*malloc_hook) (size_t size) = @dots{};
3778         void (*free_hook) (void* ptr)      = @dots{};
3779 @}
3780 @end example
3781 @cindex @code{malloc_hook ()}
3782 @cindex @code{free_hook ()}
3783 The @code{cl_malloc_hook} function must not return a @code{NULL} pointer.
3784
3785 It is not possible to change the memory allocator at runtime, because
3786 it is already called at program startup by the constructors of some
3787 global variables.
3788
3789
3790
3791
3792 @c Indices
3793
3794 @unnumbered Index
3795
3796 @printindex my
3797
3798
3799 @c Table of contents
3800 @contents
3801
3802
3803 @bye