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