]> www.ginac.de Git - ginac.git/blob - doc/tutorial/ginac.texi
- added 'ginac-config' script and 'ginac.m4' macros to help making packages
[ginac.git] / doc / tutorial / ginac.texi
1 \input texinfo  @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename ginac.info
4 @settitle GiNaC, an open framework for symbolic computation within the C++ programming language
5 @setchapternewpage on
6 @afourpaper
7 @c For `info' only.
8 @paragraphindent 0
9 @c For TeX only.
10 @iftex
11 @c I hate putting "@noindent" in front of every paragraph.
12 @parindent=0pt
13 @end iftex
14 @c %**end of header
15
16 @include version.texi
17
18 @direntry
19 * ginac: (ginac).                   C++ library for symbolic computation.
20 @end direntry
21
22 @ifinfo
23 This is a tutorial that documents GiNaC @value{VERSION}, an open
24 framework for symbolic computation within the C++ programming language.
25
26 Copyright (C) 1999 Johannes Gutenberg University Mainz, Germany
27
28 Permission is granted to make and distribute verbatim copies of
29 this manual provided the copyright notice and this permission notice
30 are preserved on all copies.
31
32 @ignore
33 Permission is granted to process this file through TeX and print the
34 results, provided the printed document carries copying permission
35 notice identical to this one except for the removal of this paragraph
36
37 @end ignore
38 Permission is granted to copy and distribute modified versions of this
39 manual under the conditions for verbatim copying, provided that the entire
40 resulting derived work is distributed under the terms of a permission
41 notice identical to this one.
42 @end ifinfo
43
44 @finalout
45 @c finalout prevents ugly black rectangles on overfull hbox lines
46 @titlepage
47 @title GiNaC @value{VERSION}
48 @subtitle An open framework for symbolic computation within the C++ programming language
49 @subtitle @value{UPDATED}
50 @author The GiNaC Group:
51 @author Christian Bauer, Alexander Frink, Richard Kreckel
52
53 @page
54 @vskip 0pt plus 1filll
55 Copyright @copyright{} 1999 Johannes Gutenberg University Mainz, Germany
56 @sp 2
57 Permission is granted to make and distribute verbatim copies of
58 this manual provided the copyright notice and this permission notice
59 are preserved on all copies.
60
61 Permission is granted to copy and distribute modified versions of this
62 manual under the conditions for verbatim copying, provided that the entire
63 resulting derived work is distributed under the terms of a permission
64 notice identical to this one.
65 @end titlepage
66
67 @page
68 @contents
69
70 @page
71
72
73 @node Top, Introduction, (dir), (dir)
74 @c    node-name, next, previous, up
75 @top GiNaC
76
77 This is a tutorial that documents GiNaC @value{VERSION}, an open
78 framework for symbolic computation within the C++ programming language.
79
80 @menu
81 * Introduction::                 GiNaC's purpose.
82 * A Tour of GiNaC::              A quick tour of the library.
83 * Installation::                 How to install the package.
84 * Basic Concepts::               Description of fundamental classes.
85 * Important Algorithms::         Algorithms for symbolic manipulations.
86 * Extending GiNaC::              How to extend the library.
87 * A Comparison With Other CAS::  Compares GiNaC to traditional CAS.
88 * Internal Structures::          Description of some internal structures.
89 * Package Tools::                Configuring packages to work with GiNaC.
90 * Bibliography::
91 * Concept Index::
92 @end menu
93
94
95 @node Introduction, A Tour of GiNaC, Top, Top
96 @c    node-name, next, previous, up
97 @chapter Introduction
98 @cindex history of GiNaC
99
100 The motivation behind GiNaC derives from the observation that most
101 present day computer algebra systems (CAS) are linguistically and
102 semantically impoverished.  Although they are quite powerful tools for
103 learning math and solving particular problems they lack modern
104 linguistical structures that allow for the creation of large-scale
105 projects.  GiNaC is an attempt to overcome this situation by extending a
106 well established and standardized computer language (C++) by some
107 fundamental symbolic capabilities, thus allowing for integrated systems
108 that embed symbolic manipulations together with more established areas
109 of computer science (like computation-intense numeric applications,
110 graphical interfaces, etc.) under one roof.
111
112 The particular problem that led to the writing of the GiNaC framework is
113 still a very active field of research, namely the calculation of higher
114 order corrections to elementary particle interactions.  There,
115 theoretical physicists are interested in matching present day theories
116 against experiments taking place at particle accelerators.  The
117 computations involved are so complex they call for a combined symbolical
118 and numerical approach.  This turned out to be quite difficult to
119 accomplish with the present day CAS we have worked with so far and so we
120 tried to fill the gap by writing GiNaC.  But of course its applications
121 are in no way restricted to theoretical physics.
122
123 This tutorial is intended for the novice user who is new to GiNaC but
124 already has some background in C++ programming.  However, since a
125 hand-made documentation like this one is difficult to keep in sync with
126 the development, the actual documentation is inside the sources in the
127 form of comments.  That documentation may be parsed by one of the many
128 Javadoc-like documentation systems.  If you fail at generating it you
129 may access it from @uref{http://www.ginac.de/reference/, the GiNaC home
130 page}.  It is an invaluable resource not only for the advanced user who
131 wishes to extend the system (or chase bugs) but for everybody who wants
132 to comprehend the inner workings of GiNaC.  This little tutorial on the
133 other hand only covers the basic things that are unlikely to change in
134 the near future.
135
136 @section License
137 The GiNaC framework for symbolic computation within the C++ programming
138 language is Copyright @copyright{} 1999 Johannes Gutenberg University Mainz,
139 Germany.
140
141 This program is free software; you can redistribute it and/or
142 modify it under the terms of the GNU General Public License as
143 published by the Free Software Foundation; either version 2 of the
144 License, or (at your option) any later version.
145
146 This program is distributed in the hope that it will be useful, but
147 WITHOUT ANY WARRANTY; without even the implied warranty of
148 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
149 General Public License for more details.
150
151 You should have received a copy of the GNU General Public License
152 along with this program; see the file COPYING.  If not, write to the
153 Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
154 MA 02111-1307, USA.
155
156
157 @node A Tour of GiNaC, How to use it from within C++, Introduction, Top
158 @c    node-name, next, previous, up
159 @chapter A Tour of GiNaC
160
161 This quick tour of GiNaC wants to arise your interest in the
162 subsequent chapters by showing off a bit.  Please excuse us if it
163 leaves many open questions.
164
165 @menu
166 * How to use it from within C++::  Two simple examples.
167 * What it can do for you::         A Tour of GiNaC's features.
168 @end menu
169
170
171 @node How to use it from within C++, What it can do for you, A Tour of GiNaC, A Tour of GiNaC
172 @c    node-name, next, previous, up
173 @section How to use it from within C++
174
175 The GiNaC open framework for symbolic computation within the C++ programming
176 language does not try to define a language of it's own as conventional
177 CAS do.  Instead, it extends the capabilities of C++ by symbolic
178 manipulations.  Here is how to generate and print a simple (and rather
179 pointless) bivariate polynomial with some large coefficients:
180
181 @example
182 #include <ginac/ginac.h>
183 using namespace GiNaC;
184
185 int main()
186 @{
187     symbol x("x"), y("y");
188     ex poly;
189
190     for (int i=0; i<3; ++i)
191         poly += factorial(i+16)*pow(x,i)*pow(y,2-i);
192
193     cout << poly << endl;
194     return 0;
195 @}
196 @end example
197
198 Assuming the file is called @file{hello.cc}, on our system we can compile
199 and run it like this:
200
201 @example
202 $ c++ hello.cc -o hello -lcln -lginac
203 $ ./hello
204 355687428096000*x*y+20922789888000*y^2+6402373705728000*x^2
205 @end example
206
207 (@xref{Package Tools}, for tools that help you when creating a software
208 package that uses GiNaC.)
209
210 @cindex Hermite polynomial
211 Next, there is a more meaningful C++ program that calls a function which
212 generates Hermite polynomials in a specified free variable.
213
214 @example
215 #include <ginac/ginac.h>
216 using namespace GiNaC;
217
218 ex HermitePoly(symbol x, int deg)
219 @{
220     ex HKer=exp(-pow(x,2));
221     // uses the identity H_n(x) == (-1)^n exp(x^2) (d/dx)^n exp(-x^2) 
222     return normal(pow(-1,deg) * diff(HKer, x, deg) / HKer);
223 @}
224
225 int main()
226 @{
227     symbol z("z");
228
229     for (int i=0; i<6; ++i)
230         cout << "H_" << i << "(z) == " << HermitePoly(z,i) << endl;
231
232     return 0;
233 @}
234 @end example
235
236 When run, this will type out
237
238 @example
239 H_0(z) == 1
240 H_1(z) == 2*z
241 H_2(z) == 4*z^2-2
242 H_3(z) == -12*z+8*z^3
243 H_4(z) == -48*z^2+16*z^4+12
244 H_5(z) == 120*z-160*z^3+32*z^5
245 @end example
246
247 This method of generating the coefficients is of course far from optimal
248 for production purposes.
249
250 In order to show some more examples of what GiNaC can do we will now use
251 the @command{ginsh}, a simple GiNaC interactive shell that provides a
252 convenient window into GiNaC's capabilities.
253
254
255 @node What it can do for you, Installation, How to use it from within C++, A Tour of GiNaC
256 @c    node-name, next, previous, up
257 @section What it can do for you
258
259 @cindex @code{ginsh}
260 After invoking @command{ginsh} one can test and experiment with GiNaC's
261 features much like in other Computer Algebra Systems except that it does
262 not provide programming constructs like loops or conditionals.  For a
263 concise description of the @command{ginsh} syntax we refer to its
264 accompanied man page. Suffice to say that assignments and comparisons in
265 @command{ginsh} are written as they are in C, i.e. @code{=} assigns and
266 @code{==} compares.
267
268 It can manipulate arbitrary precision integers in a very fast way.
269 Rational numbers are automatically converted to fractions of coprime
270 integers:
271
272 @example
273 > x=3^150;
274 369988485035126972924700782451696644186473100389722973815184405301748249
275 > y=3^149;
276 123329495011708990974900260817232214728824366796574324605061468433916083
277 > x/y;
278 3
279 > y/x;
280 1/3
281 @end example
282
283 All numbers occuring in GiNaC's expressions can be converted into floating
284 point numbers with the @code{evalf} method, to arbitrary accuracy:
285
286 @example
287 > evalf(1/7);
288 0.14285714285714285714
289 > Digits=150;
290 150
291 > evalf(1/7);
292 0.1428571428571428571428571428571428571428571428571428571428571428571428
293 5714285714285714285714285714285714285
294 @end example
295
296 Exact numbers other than rationals that can be manipulated in GiNaC
297 include predefined constants like Archimedes' @code{Pi}.  They can both
298 be used in symbolic manipulations (as an exact number) as well as in
299 numeric expressions (as an inexact number):
300
301 @example
302 > a=Pi^2+x;
303 x+Pi^2
304 > evalf(a);
305 x+9.869604401089358619L0
306 > x=2;
307 2
308 > evalf(a);
309 11.869604401089358619L0
310 @end example
311
312 Built-in functions evaluate immediately to exact numbers if
313 this is possible.  Conversions that can be safely performed are done
314 immediately; conversions that are not generally valid are not done:
315
316 @example
317 > cos(42*Pi);
318 1
319 > cos(acos(x));
320 x
321 > acos(cos(x));
322 acos(cos(x))
323 @end example
324
325 (Note that converting the last input to @code{x} would allow one to
326 conclude that @code{42*Pi} is equal to @code{0}.)
327
328 Linear equation systems can be solved along with basic linear
329 algebra manipulations over symbolic expressions.  In C++ GiNaC offers
330 a matrix class for this purpose but we can see what it can do using
331 @command{ginsh}'s notation of double brackets to type them in:
332
333 @example
334 > lsolve(a+x*y==z,x);
335 y^(-1)*(z-a);
336 lsolve([3*x+5*y == 7, -2*x+10*y == -5], [x, y]);
337 [x==19/8,y==-1/40]
338 > M = [[ [[1, 3]], [[-3, 2]] ]];
339 [[ [[1,3]], [[-3,2]] ]]
340 > determinant(M);
341 11
342 > charpoly(M,lambda);
343 lambda^2-3*lambda+11
344 @end example
345
346 Multivariate polynomials and rational functions may be expanded,
347 collected and normalized (i.e. converted to a ratio of two coprime 
348 polynomials):
349
350 @example
351 > a = x^4 + 2*x^2*y^2 + 4*x^3*y + 12*x*y^3 - 3*y^4;
352 -3*y^4+x^4+12*x*y^3+2*x^2*y^2+4*x^3*y
353 > b = x^2 + 4*x*y - y^2;
354 -y^2+x^2+4*x*y
355 > expand(a*b);
356 3*y^6+x^6-24*x*y^5+43*x^2*y^4+16*x^3*y^3+17*x^4*y^2+8*x^5*y
357 > collect(a*b,x);
358 3*y^6+48*x*y^4+2*x^2*y^2+x^4*(-y^2+x^2+4*x*y)+4*x^3*y*(-y^2+x^2+4*x*y)
359 > normal(a/b);
360 3*y^2+x^2
361 @end example
362
363 You can differentiate functions and expand them as Taylor or
364 Laurent series (the third argument of series is the evaluation point,
365 the fourth defines the order):
366
367 @example
368 > diff(tan(x),x);
369 tan(x)^2+1
370 > series(sin(x),x,0,4);
371 x-1/6*x^3+Order(x^4)
372 > series(1/tan(x),x,0,4);
373 x^(-1)-1/3*x+Order(x^2)
374 @end example
375
376 If you ever wanted to convert units in C or C++ and found this
377 is cumbersome, here is the solution.  Symbolic types can always be
378 used as tags for different types of objects.  Converting from wrong
379 units to the metric system is therefore easy:
380
381 @example
382 > in=.0254*m;
383 0.0254*m
384 > lb=.45359237*kg;
385 0.45359237*kg
386 > 200*lb/in^2;
387 140613.91592783185568*kg*m^(-2)
388 @end example
389
390
391 @node Installation, Prerequisites, What it can do for you, Top
392 @c    node-name, next, previous, up
393 @chapter Installation
394
395 @cindex CLN
396 GiNaC's installation follows the spirit of most GNU software. It is
397 easily installed on your system by three steps: configuration, build,
398 installation.
399
400 @menu
401 * Prerequisites::                Packages upon which GiNaC depends.
402 * Configuration::                How to configure GiNaC.
403 * Building GiNaC::               How to compile GiNaC.
404 * Installing GiNaC::             How to install GiNaC on your system.
405 @end menu
406
407
408 @node Prerequisites, Configuration, Installation, Installation
409 @c    node-name, next, previous, up
410 @section Prerequisites
411
412 In order to install GiNaC on your system, some prerequisites need
413 to be met.  First of all, you need to have a C++-compiler adhering to
414 the ANSI-standard @cite{ISO/IEC 14882:1998(E)}.  We used @acronym{GCC} for
415 development so if you have a different compiler you are on your own.
416 For the configuration to succeed you need a Posix compliant shell
417 installed in @file{/bin/sh}, GNU @command{bash} is fine.  Perl is needed
418 by the built process as well, since some of the source files are automatically
419 generated by Perl scripts.  Last but not least, Bruno Haible's library
420 @acronym{CLN} is extensively used and needs to be installed on your system.
421 Please get it from @uref{ftp://ftp.santafe.edu/pub/gnu/} or from
422 @uref{ftp://ftp.ilog.fr/pub/Users/haible/gnu/, Bruno Haible's FTP site}
423 (it is covered by GPL) and install it prior to trying to install GiNaC.
424 The configure script checks if it can find it and if it cannot
425 it will refuse to continue.
426
427
428 @node Configuration, Building GiNaC, Prerequisites, Installation
429 @c    node-name, next, previous, up
430 @section Configuration
431 @cindex configuration
432 @cindex Autoconf
433
434 To configure GiNaC means to prepare the source distribution for
435 building.  It is done via a shell script called @command{configure} that
436 is shipped with the sources and was originally generated by GNU
437 Autoconf.  Since a configure script generated by GNU Autoconf never
438 prompts, all customization must be done either via command line
439 parameters or environment variables.  It accepts a list of parameters,
440 the complete set of which can be listed by calling it with the
441 @option{--help} option.  The most important ones will be shortly
442 described in what follows:
443
444 @itemize @bullet
445
446 @item
447 @option{--disable-shared}: When given, this option switches off the
448 build of a shared library, i.e. a @file{.so} file.  This may be convenient
449 when developing because it considerably speeds up compilation.
450
451 @item
452 @option{--prefix=@var{PREFIX}}: The directory where the compiled library
453 and headers are installed. It defaults to @file{/usr/local} which means
454 that the library is installed in the directory @file{/usr/local/lib},
455 the header files in @file{/usr/local/include/GiNaC} and the documentation
456 (like this one) into @file{/usr/local/share/doc/GiNaC}.
457
458 @item
459 @option{--libdir=@var{LIBDIR}}: Use this option in case you want to have
460 the library installed in some other directory than
461 @file{@var{PREFIX}/lib/}.
462
463 @item
464 @option{--includedir=@var{INCLUDEDIR}}: Use this option in case you want
465 to have the header files installed in some other directory than
466 @file{@var{PREFIX}/include/ginac/}. For instance, if you specify
467 @option{--includedir=/usr/include} you will end up with the header files
468 sitting in the directory @file{/usr/include/ginac/}. Note that the
469 subdirectory @file{GiNaC} is enforced by this process in order to
470 keep the header files separated from others.  This avoids some
471 clashes and allows for an easier deinstallation of GiNaC. This ought
472 to be considered A Good Thing (tm).
473
474 @item
475 @option{--datadir=@var{DATADIR}}: This option may be given in case you
476 want to have the documentation installed in some other directory than
477 @file{@var{PREFIX}/share/doc/GiNaC/}.
478
479 @end itemize
480
481 In addition, you may specify some environment variables.
482 @env{CXX} holds the path and the name of the C++ compiler
483 in case you want to override the default in your path.  (The
484 @command{configure} script searches your path for @command{c++},
485 @command{g++}, @command{gcc}, @command{CC}, @command{cxx}
486 and @command{cc++} in that order.)  It may be very useful to
487 define some compiler flags with the @env{CXXFLAGS} environment
488 variable, like optimization, debugging information and warning
489 levels.  If omitted, it defaults to @option{-g -O2}.
490
491 The whole process is illustrated in the following two
492 examples. (Substitute @command{setenv @var{VARIABLE} @var{value}} for
493 @command{export @var{VARIABLE}=@var{value}} if the Berkeley C shell is
494 your login shell.)
495
496 Here is a simple configuration for a site-wide GiNaC library assuming
497 everything is in default paths:
498
499 @example
500 $ export CXXFLAGS="-Wall -O2"
501 $ ./configure
502 @end example
503
504 And here is a configuration for a private static GiNaC library with
505 several components sitting in custom places (site-wide @acronym{GCC} and
506 private @acronym{CLN}).  The compiler is pursuaded to be picky and full
507 assertions and debugging are switched on:
508
509 @example
510 $ export CXX=/usr/local/gnu/bin/c++
511 $ export CPPFLAGS="$(CPPFLAGS) -I$(HOME)/include"
512 $ export CXXFLAGS="$(CXXFLAGS) -DDO_GINAC_ASSERT -ggdb -Wall -ansi -pedantic"
513 $ export LDFLAGS="$(LDFLAGS) -L$(HOME)/lib"
514 $ ./configure --disable-shared --prefix=$(HOME)
515 @end example
516
517
518 @node Building GiNaC, Installing GiNaC, Configuration, Installation
519 @c    node-name, next, previous, up
520 @section Building GiNaC
521 @cindex building GiNaC
522
523 After proper configuration you should just build the whole
524 library by typing
525 @example
526 $ make
527 @end example
528 at the command prompt and go for a cup of coffee.  The exact time it
529 takes to compile GiNaC depends not only on the speed of your machines
530 but also on other parameters, for instance what value for @env{CXXFLAGS}
531 you entered.  Optimization may be very time-consuming.
532
533 Just to make sure GiNaC works properly you may run a simple test
534 suite by typing
535
536 @example
537 $ make check
538 @end example
539
540 This will compile some sample programs, run them and compare the output
541 to reference output. Each of the checks should return a message @samp{passed}
542 together with the CPU time used for that particular test.  If it does
543 not, something went wrong.  This is mostly intended to be a QA-check
544 if something was broken during the development, not a sanity check
545 of your system.  Another intent is to allow people to fiddle around
546 with optimization.  If @acronym{CLN} was installed all right
547 this step is unlikely to return any errors.
548
549 Generally, the top-level Makefile runs recursively to the
550 subdirectories.  It is therfore safe to go into any subdirectory
551 (@code{doc/}, @code{ginsh/}, ...) and simply type @code{make}
552 @var{target} there in case something went wrong.
553
554
555 @node Installing GiNaC, Basic Concepts, Building GiNaC, Installation
556 @c    node-name, next, previous, up
557 @section Installing GiNaC
558 @cindex installation
559
560 To install GiNaC on your system, simply type
561
562 @example
563 $ make install
564 @end example
565
566 As described in the section about configuration the files will be
567 installed in the following directories (the directories will be created
568 if they don't already exist):
569
570 @itemize @bullet
571
572 @item
573 @file{libginac.a} will go into @file{@var{PREFIX}/lib/} (or
574 @file{@var{LIBDIR}}) which defaults to @file{/usr/local/lib/}.
575 So will @file{libginac.so} unless the configure script was
576 given the option @option{--disable-shared}.  The proper symlinks
577 will be established as well.
578
579 @item
580 All the header files will be installed into @file{@var{PREFIX}/include/ginac/}
581 (or @file{@var{INCLUDEDIR}/ginac/}, if specified).
582
583 @item
584 All documentation (HTML and Postscript) will be stuffed into
585 @file{@var{PREFIX}/share/doc/GiNaC/} (or
586 @file{@var{DATADIR}/doc/GiNaC/}, if @var{DATADIR} was specified).
587
588 @end itemize
589
590 For the sake of completeness we will list some other useful make
591 targets: @command{make clean} deletes all files generated by
592 @command{make}, i.e. all the object files.  In addition @command{make
593 distclean} removes all files generated by the configuration and
594 @command{make maintainer-clean} goes one step further and deletes files
595 that may require special tools to rebuild (like the @command{libtool}
596 for instance).  Finally @command{make uninstall} removes the installed
597 library, header files and documentation@footnote{Uninstallation does not
598 work after you have called @command{make distclean} since the
599 @file{Makefile} is itself generated by the configuration from
600 @file{Makefile.in} and hence deleted by @command{make distclean}.  There
601 are two obvious ways out of this dilemma.  First, you can run the
602 configuration again with the same @var{PREFIX} thus creating a
603 @file{Makefile} with a working @samp{uninstall} target.  Second, you can
604 do it by hand since you now know where all the files went during
605 installation.}.
606
607
608 @node Basic Concepts, Expressions, Installing GiNaC, Top
609 @c    node-name, next, previous, up
610 @chapter Basic Concepts
611
612 This chapter will describe the different fundamental objects that can be
613 handled by GiNaC.  But before doing so, it is worthwhile introducing you
614 to the more commonly used class of expressions, representing a flexible
615 meta-class for storing all mathematical objects.
616
617 @menu
618 * Expressions::                  The fundamental GiNaC class.
619 * The Class Hierarchy::          Overview of GiNaC's classes.
620 * Symbols::                      Symbolic objects.
621 * Numbers::                      Numerical objects.
622 * Constants::                    Pre-defined constants.
623 * Fundamental operations::       The power, add and mul classes.
624 * Built-in functions::           Mathematical functions.
625 @end menu
626
627
628 @node Expressions, The Class Hierarchy, Basic Concepts, Basic Concepts
629 @c    node-name, next, previous, up
630 @section Expressions
631 @cindex expression (class @code{ex})
632 @cindex @code{has()}
633
634 The most common class of objects a user deals with is the expression
635 @code{ex}, representing a mathematical object like a variable, number,
636 function, sum, product, etc...  Expressions may be put together to form
637 new expressions, passed as arguments to functions, and so on.  Here is a
638 little collection of valid expressions:
639
640 @example
641 ex MyEx1 = 5;                       // simple number
642 ex MyEx2 = x + 2*y;                 // polynomial in x and y
643 ex MyEx3 = (x + 1)/(x - 1);         // rational expression
644 ex MyEx4 = sin(x + 2*y) + 3*z + 41; // containing a function
645 ex MyEx5 = MyEx4 + 1;               // similar to above
646 @end example
647
648 Expressions are handles to other more fundamental objects, that many
649 times contain other expressions thus creating a tree of expressions
650 (@xref{Internal Structures}, for particular examples).  Most methods on
651 @code{ex} therefore run top-down through such an expression tree.  For
652 example, the method @code{has()} scans recursively for occurrences of
653 something inside an expression.  Thus, if you have declared @code{MyEx4}
654 as in the example above @code{MyEx4.has(y)} will find @code{y} inside
655 the argument of @code{sin} and hence return @code{true}.
656
657 The next sections will outline the general picture of GiNaC's class
658 hierarchy and describe the classes of objects that are handled by
659 @code{ex}.
660
661
662 @node The Class Hierarchy, Symbols, Expressions, Basic Concepts
663 @c    node-name, next, previous, up
664 @section The Class Hierarchy
665
666 GiNaC's class hierarchy consists of several classes representing
667 mathematical objects, all of which (except for @code{ex} and some
668 helpers) are internally derived from one abstract base class called
669 @code{basic}.  You do not have to deal with objects of class
670 @code{basic}, instead you'll be dealing with symbols and functions of
671 symbols.  You'll soon learn in this chapter how many of the functions on
672 symbols are really classes.  This is because simple symbolic arithmetic
673 is not supported by languages like C++ so in a certain way GiNaC has to
674 implement its own arithmetic.
675
676 To give an idea about what kinds of symbolic composits may be built we
677 have a look at the most important classes in the class hierarchy.  The
678 dashed line symbolizes a "points to" or "handles" relationship while the
679 solid lines stand for "inherits from" relationship in the class
680 hierarchy:
681
682 @image{classhierarchy}
683
684 Some of the classes shown here (the ones sitting in white boxes) are
685 abstract base classes that are of no interest at all for the user.  They
686 are used internally in order to avoid code duplication if two or more
687 classes derived from them share certain features.  An example would be
688 @code{expairseq}, which is a container for a sequence of pairs each
689 consisting of one expression and a number (@code{numeric}).  What
690 @emph{is} visible to the user are the derived classes @code{add} and
691 @code{mul}, representing sums of terms and products, respectively.
692 We'll come back later to some more details about these two classes and
693 motivate the use of pairs in sums and products here.
694
695
696 @node Symbols, Numbers, The Class Hierarchy, Basic Concepts
697 @c    node-name, next, previous, up
698 @section Symbols
699 @cindex Symbols (class @code{symbol})
700
701 Symbols are for symbolic manipulation what atoms are for chemistry.  You
702 can declare objects of class @code{symbol} as any other object simply by
703 saying @code{symbol x,y;}.  There is, however, a catch in here having to
704 do with the fact that C++ is a compiled language.  The information about
705 the symbol's name is thrown away by the compiler but at a later stage
706 you may want to print expressions holding your symbols.  In order to
707 avoid confusion GiNaC's symbols are able to know their own name.  This
708 is accomplished by declaring its name for output at construction time in
709 the fashion @code{symbol x("x");}.  If you declare a symbol using the
710 default constructor (i.e. without string argument) the system will deal
711 out a unique name.  That name may not be suitable for printing but for
712 internal routines when no output is desired it is often enough.  We'll
713 come across examples of such symbols later in this tutorial.
714
715 This implies that the strings passed to symbols at construction time may
716 not be used for comparing two of them.  It is perfectly legitimate to
717 write @code{symbol x("x"),y("x");} but it is likely to lead into
718 trouble.  Here, @code{x} and @code{y} are different symbols and
719 statements like @code{x-y} will not be simplified to zero although the
720 output @code{x-x} looks funny.  Such output may also occur when there
721 are two different symbols in two scopes, for instance when you call a
722 function that declares a symbol with a name already existent in a symbol
723 in the calling function.  Again, comparing them (using @code{operator==}
724 for instance) will always reveal their difference.  Watch out, please.
725
726 Although symbols can be assigned expressions for internal reasons, you
727 should not do it (and we are not going to tell you how it is done).  If
728 you want to replace a symbol with something else in an expression, you
729 can use the expression's @code{.subs()} method.
730
731
732 @node Numbers, Constants, Symbols, Basic Concepts
733 @c    node-name, next, previous, up
734 @section Numbers
735 @cindex numbers (class @code{numeric})
736
737 @cindex CLN
738 For storing numerical things, GiNaC uses Bruno Haible's library
739 @acronym{CLN}.  The classes therein serve as foundation classes for
740 GiNaC.  @acronym{CLN} stands for Class Library for Numbers or
741 alternatively for Common Lisp Numbers.  In order to find out more about
742 @acronym{CLN}'s internals the reader is refered to the documentation of
743 that library.  @inforef{Introduction, , cln}, for more
744 information. Suffice to say that it is by itself build on top of another
745 library, the GNU Multiple Precision library @acronym{GMP}, which is an
746 extremely fast library for arbitrary long integers and rationals as well
747 as arbitrary precision floating point numbers.  It is very commonly used
748 by several popular cryptographic applications.  @acronym{CLN} extends
749 @acronym{GMP} by several useful things: First, it introduces the complex
750 number field over either reals (i.e. floating point numbers with
751 arbitrary precision) or rationals.  Second, it automatically converts
752 rationals to integers if the denominator is unity and complex numbers to
753 real numbers if the imaginary part vanishes and also correctly treats
754 algebraic functions.  Third it provides good implementations of
755 state-of-the-art algorithms for all trigonometric and hyperbolic
756 functions as well as for calculation of some useful constants.
757
758 The user can construct an object of class @code{numeric} in several
759 ways.  The following example shows the four most important constructors.
760 It uses construction from C-integer, construction of fractions from two
761 integers, construction from C-float and construction from a string:
762
763 @example
764 #include <ginac/ginac.h>
765 using namespace GiNaC;
766
767 int main()
768 @{
769     numeric two(2);                     // exact integer 2
770     numeric r(2,3);                     // exact fraction 2/3
771     numeric e(2.71828);                 // floating point number
772     numeric p("3.1415926535897932385"); // floating point number
773
774     cout << two*p << endl;  // floating point 6.283...
775     // ...
776 @}
777 @end example
778
779 Note that all those constructors are @emph{explicit} which means you are
780 not allowed to write @code{numeric two=2;}.  This is because the basic
781 objects to be handled by GiNaC are the expressions @code{ex} and we want
782 to keep things simple and wish objects like @code{pow(x,2)} to be
783 handled the same way as @code{pow(x,a)}, which means that we need to
784 allow a general @code{ex} as base and exponent.  Therefore there is an
785 implicit constructor from C-integers directly to expressions handling
786 numerics at work in most of our examples.  This design really becomes
787 convenient when one declares own functions having more than one
788 parameter but it forbids using implicit constructors because that would
789 lead to ambiguities.
790
791 It may be tempting to construct numbers writing @code{numeric r(3/2)}.
792 This would, however, call C's built-in operator @code{/} for integers
793 first and result in a numeric holding a plain integer 1.  @strong{Never
794 use @code{/} on integers!} Use the constructor from two integers
795 instead, as shown in the example above.  Writing @code{numeric(1)/2} may
796 look funny but works also.
797
798 @cindex @code{Digits}
799 @cindex accuracy
800 We have seen now the distinction between exact numbers and floating
801 point numbers.  Clearly, the user should never have to worry about
802 dynamically created exact numbers, since their "exactness" always
803 determines how they ought to be handled, i.e. how "long" they are.  The
804 situation is different for floating point numbers.  Their accuracy is
805 controlled by one @emph{global} variable, called @code{Digits}.  (For
806 those readers who know about Maple: it behaves very much like Maple's
807 @code{Digits}).  All objects of class numeric that are constructed from
808 then on will be stored with a precision matching that number of decimal
809 digits:
810
811 @example
812 #include <ginac/ginac.h>
813 using namespace GiNaC;
814
815 void foo()
816 @{
817     numeric three(3.0), one(1.0);
818     numeric x = one/three;
819
820     cout << "in " << Digits << " digits:" << endl;
821     cout << x << endl;
822     cout << Pi.evalf() << endl;
823 @}
824
825 int main()
826 @{
827     foo();
828     Digits = 60;
829     foo();
830     return 0;
831 @}
832 @end example
833
834 The above example prints the following output to screen:
835
836 @example
837 in 17 digits:
838 0.333333333333333333
839 3.14159265358979324
840 in 60 digits:
841 0.333333333333333333333333333333333333333333333333333333333333333333
842 3.14159265358979323846264338327950288419716939937510582097494459231
843 @end example
844
845 It should be clear that objects of class @code{numeric} should be used
846 for constructing numbers or for doing arithmetic with them.  The objects
847 one deals with most of the time are the polymorphic expressions @code{ex}.
848
849 @subsection Tests on numbers
850
851 Once you have declared some numbers, assigned them to expressions and
852 done some arithmetic with them it is frequently desired to retrieve some
853 kind of information from them like asking whether that number is
854 integer, rational, real or complex.  For those cases GiNaC provides
855 several useful methods.  (Internally, they fall back to invocations of
856 certain CLN functions.)
857
858 As an example, let's construct some rational number, multiply it with
859 some multiple of its denominator and test what comes out:
860
861 @example
862 #include <ginac/ginac.h>
863 using namespace GiNaC;
864
865 // some very important constants:
866 const numeric twentyone(21);
867 const numeric ten(10);
868 const numeric five(5);
869
870 int main()
871 @{
872     numeric answer = twentyone;
873
874     answer /= five;
875     cout << answer.is_integer() << endl;  // false, it's 21/5
876     answer *= ten;
877     cout << answer.is_integer() << endl;  // true, it's 42 now!
878     // ...
879 @}
880 @end example
881
882 Note that the variable @code{answer} is constructed here as an integer
883 by @code{numeric}'s copy constructor but in an intermediate step it
884 holds a rational number represented as integer numerator and integer
885 denominator.  When multiplied by 10, the denominator becomes unity and
886 the result is automatically converted to a pure integer again.
887 Internally, the underlying @acronym{CLN} is responsible for this
888 behaviour and we refer the reader to @acronym{CLN}'s documentation.
889 Suffice to say that the same behaviour applies to complex numbers as
890 well as return values of certain functions.  Complex numbers are
891 automatically converted to real numbers if the imaginary part becomes
892 zero.  The full set of tests that can be applied is listed in the
893 following table.
894
895 @cartouche
896 @multitable @columnfractions .33 .67
897 @item Method @tab Returns true if@dots{}
898 @item @code{.is_zero()}
899 @tab object is equal to zero
900 @item @code{.is_positive()}
901 @tab object is not complex and greater than 0
902 @item @code{.is_integer()}
903 @tab object is a (non-complex) integer
904 @item @code{.is_pos_integer()}
905 @tab object is an integer and greater than 0
906 @item @code{.is_nonneg_integer()}
907 @tab object is an integer and greater equal 0
908 @item @code{.is_even()}
909 @tab object is an even integer
910 @item @code{.is_odd()}
911 @tab object is an odd integer
912 @item @code{.is_prime()}
913 @tab object is a prime integer (probabilistic primality test)
914 @item @code{.is_rational()}
915 @tab object is an exact rational number (integers are rational, too, as are complex extensions like @math{2/3+7/2*I})
916 @item @code{.is_real()}
917 @tab object is a real integer, rational or float (i.e. is not complex)
918 @end multitable
919 @end cartouche
920
921
922 @node Constants, Fundamental operations, Numbers, Basic Concepts
923 @c    node-name, next, previous, up
924 @section Constants
925 @cindex constants (class @code{constant})
926 @cindex @code{evalf()}
927
928 Constants behave pretty much like symbols except that they return some
929 specific number when the method @code{.evalf()} is called.
930
931 The predefined known constants are:
932
933 @cartouche
934 @multitable @columnfractions .14 .29 .57
935 @item Name @tab Common Name @tab Numerical Value (35 digits)
936 @item @code{Pi}
937 @tab Archimedes' constant
938 @tab 3.14159265358979323846264338327950288
939 @item @code{Catalan}
940 @tab Catalan's constant
941 @tab 0.91596559417721901505460351493238411
942 @item @code{EulerGamma}
943 @tab Euler's (or Euler-Mascheroni) constant
944 @tab 0.57721566490153286060651209008240243
945 @end multitable
946 @end cartouche
947
948
949 @node Fundamental operations, Built-in functions, Constants, Basic Concepts
950 @c    node-name, next, previous, up
951 @section Fundamental operations: the @code{power}, @code{add} and @code{mul} classes
952 @cindex polynomials
953 @cindex @code{add}
954 @cindex @code{mul}
955 @cindex @code{power}
956
957 Simple polynomial expressions are written down in GiNaC pretty much like
958 in other CAS or like expressions involving numerical variables in C.
959 The necessary operators @code{+}, @code{-}, @code{*} and @code{/} have
960 been overloaded to achieve this goal.  When you run the following
961 program, the constructor for an object of type @code{mul} is
962 automatically called to hold the product of @code{a} and @code{b} and
963 then the constructor for an object of type @code{add} is called to hold
964 the sum of that @code{mul} object and the number one:
965
966 @example
967 #include <ginac/ginac.h>
968 using namespace GiNaC;
969
970 int main()
971 @{
972     symbol a("a"), b("b");
973     ex MyTerm = 1+a*b;
974     // ...
975 @}
976 @end example
977
978 For exponentiation, you have already seen the somewhat clumsy (though C-ish)
979 statement @code{pow(x,2);} to represent @code{x} squared.  This direct
980 construction is necessary since we cannot safely overload the constructor
981 @code{^} in C++ to construct a @code{power} object.  If we did, it would
982 have several counterintuitive effects:
983
984 @itemize @bullet
985 @item
986 Due to C's operator precedence, @code{2*x^2} would be parsed as @code{(2*x)^2}.
987 @item
988 Due to the binding of the operator @code{^}, @code{x^a^b} would result in
989 @code{(x^a)^b}. This would be confusing since most (though not all) other CAS
990 interpret this as @code{x^(a^b)}.
991 @item
992 Also, expressions involving integer exponents are very frequently used,
993 which makes it even more dangerous to overload @code{^} since it is then
994 hard to distinguish between the semantics as exponentiation and the one
995 for exclusive or.  (It would be embarassing to return @code{1} where one
996 has requested @code{2^3}.)
997 @end itemize
998
999 @cindex @code{ginsh}
1000 All effects are contrary to mathematical notation and differ from the
1001 way most other CAS handle exponentiation, therefore overloading @code{^}
1002 is ruled out for GiNaC's C++ part.  The situation is different in
1003 @command{ginsh}, there the exponentiation-@code{^} exists.  (Also note
1004 that the other frequently used exponentiation operator @code{**} does
1005 not exist at all in C++).
1006
1007 To be somewhat more precise, objects of the three classes described
1008 here, are all containers for other expressions.  An object of class
1009 @code{power} is best viewed as a container with two slots, one for the
1010 basis, one for the exponent.  All valid GiNaC expressions can be
1011 inserted.  However, basic transformations like simplifying
1012 @code{pow(pow(x,2),3)} to @code{x^6} automatically are only performed
1013 when this is mathematically possible.  If we replace the outer exponent
1014 three in the example by some symbols @code{a}, the simplification is not
1015 safe and will not be performed, since @code{a} might be @code{1/2} and
1016 @code{x} negative.
1017
1018 Objects of type @code{add} and @code{mul} are containers with an
1019 arbitrary number of slots for expressions to be inserted.  Again, simple
1020 and safe simplifications are carried out like transforming
1021 @code{3*x+4-x} to @code{2*x+4}.
1022
1023 The general rule is that when you construct such objects, GiNaC
1024 automatically creates them in canonical form, which might differ from
1025 the form you typed in your program.  This allows for rapid comparison of
1026 expressions, since after all @code{a-a} is simply zero.  Note, that the
1027 canonical form is not necessarily lexicographical ordering or in any way
1028 easily guessable.  It is only guaranteed that constructing the same
1029 expression twice, either implicitly or explicitly, results in the same
1030 canonical form.
1031
1032
1033 @node Built-in functions, Important Algorithms, Fundamental operations, Basic Concepts
1034 @c    node-name, next, previous, up
1035 @section Built-in functions
1036
1037 There are quite a number of useful functions built into GiNaC.  They are
1038 all objects of class @code{function}.  They accept one or more
1039 expressions as arguments and return one expression.  If the arguments
1040 are not numerical, the evaluation of the function may be halted, as it
1041 does in the next example:
1042
1043 @example
1044 #include <ginac/ginac.h>
1045 using namespace GiNaC;
1046
1047 int main()
1048 @{
1049     symbol x("x"), y("y");
1050     
1051     ex foo = x+y/2;
1052     cout << "gamma(" << foo << ") -> " << gamma(foo) << endl;
1053     ex bar = foo.subs(y==1);
1054     cout << "gamma(" << bar << ") -> " << gamma(bar) << endl;
1055     ex foobar = bar.subs(x==7);
1056     cout << "gamma(" << foobar << ") -> " << gamma(foobar) << endl;
1057     // ...
1058 @}
1059 @end example
1060
1061 This program shows how the function returns itself twice and finally an
1062 expression that may be really useful:
1063
1064 @example
1065 gamma(x+(1/2)*y) -> gamma(x+(1/2)*y)
1066 gamma(x+1/2) -> gamma(x+1/2)
1067 gamma(15/2) -> (135135/128)*Pi^(1/2)
1068 @end example
1069
1070 Most of these functions can be differentiated, series expanded and so
1071 on.  Read the next chapter in order to learn more about this.
1072
1073
1074 @node Important Algorithms, Polynomial Expansion, Built-in functions, Top
1075 @c    node-name, next, previous, up
1076 @chapter Important Algorithms
1077 @cindex polynomials
1078
1079 In this chapter the most important algorithms provided by GiNaC will be
1080 described.  Some of them are implemented as functions on expressions,
1081 others are implemented as methods provided by expression objects.  If
1082 they are methods, there exists a wrapper function around it, so you can
1083 alternatively call it in a functional way as shown in the simple
1084 example:
1085
1086 @example
1087 #include <ginac/ginac.h>
1088 using namespace GiNaC;
1089
1090 int main()
1091 @{
1092     ex x = numeric(1.0);
1093     
1094     cout << "As method:   " << sin(x).evalf() << endl;
1095     cout << "As function: " << evalf(sin(x)) << endl;
1096     // ...
1097 @}
1098 @end example
1099
1100 The general rule is that wherever methods accept one or more parameters
1101 (@var{arg1}, @var{arg2}, @dots{}) the order of arguments the function
1102 wrapper accepts is the same but preceded by the object to act on
1103 (@var{object}, @var{arg1}, @var{arg2}, @dots{}).  This approach is the
1104 most natural one in an OO model but it may lead to confusion for MapleV
1105 users because where they would type @code{A:=x+1; subs(x=2,A);} GiNaC
1106 would require @code{A=x+1; subs(A,x==2);} (after proper declaration of
1107 @code{A} and @code{x}).  On the other hand, since MapleV returns 3 on
1108 @code{A:=x^2+3; coeff(A,x,0);} (GiNaC: @code{A=pow(x,2)+3;
1109 coeff(A,x,0);}) it is clear that MapleV is not trying to be consistent
1110 here.  Also, users of MuPAD will in most cases feel more comfortable
1111 with GiNaC's convention.  All function wrappers are always implemented
1112 as simple inline functions which just call the corresponding method and
1113 are only provided for users uncomfortable with OO who are dead set to
1114 avoid method invocations.  Generally, a chain of function wrappers is
1115 much harder to read than a chain of methods and should therefore be
1116 avoided if possible.  On the other hand, not everything in GiNaC is a
1117 method on class @code{ex} and sometimes calling a function cannot be
1118 avoided.
1119
1120 @menu
1121 * Polynomial Expansion::
1122 * Collecting expressions::
1123 * Polynomial Arithmetic::
1124 * Symbolic Differentiation::
1125 * Series Expansion::
1126 @end menu
1127
1128
1129 @node Polynomial Expansion, Collecting expressions, Important Algorithms, Important Algorithms
1130 @c    node-name, next, previous, up
1131 @section Polynomial Expansion
1132 @cindex @code{expand()}
1133
1134 A polynomial in one or more variables has many equivalent
1135 representations.  Some useful ones serve a specific purpose.  Consider
1136 for example the trivariate polynomial @math{4*x*y + x*z + 20*y^2 +
1137 21*y*z + 4*z^2} (written down here in output-style).  It is equivalent
1138 to the factorized polynomial @math{(x + 5*y + 4*z)*(4*y + z)}.  Other
1139 representations are the recursive ones where one collects for exponents
1140 in one of the three variable.  Since the factors are themselves
1141 polynomials in the remaining two variables the procedure can be
1142 repeated.  In our expample, two possibilities would be @math{(4*y + z)*x
1143 + 20*y^2 + 21*y*z + 4*z^2} and @math{20*y^2 + (21*z + 4*x)*y + 4*z^2 +
1144 x*z}.
1145
1146 To bring an expression into expanded form, its method @code{.expand()}
1147 may be called.  In our example above, this corresponds to @math{4*x*y +
1148 x*z + 20*y^2 + 21*y*z + 4*z^2}.  Again, since the canonical form in
1149 GiNaC is not easily guessable you should be prepared to see different
1150 orderings of terms in such sums!
1151
1152
1153 @node Collecting expressions, Polynomial Arithmetic, Polynomial Expansion, Important Algorithms
1154 @c    node-name, next, previous, up
1155 @section Collecting expressions
1156 @cindex @code{collect()}
1157 @cindex @code{coeff()}
1158
1159 Another useful representation of multivariate polynomials is as a
1160 univariate polynomial in one of the variables with the coefficients
1161 being polynomials in the remaining variables.  The method
1162 @code{collect()} accomplishes this task.  Here is its declaration:
1163
1164 @example
1165 ex ex::collect(symbol const & s);
1166 @end example
1167
1168 Note that the original polynomial needs to be in expanded form in order
1169 to be able to find the coefficients properly.  The range of occuring
1170 coefficients can be checked using the two methods
1171
1172 @example
1173 int ex::degree(symbol const & s);
1174 int ex::ldegree(symbol const & s);
1175 @end example
1176
1177 where @code{degree()} returns the highest coefficient and
1178 @code{ldegree()} the lowest one.  (These two methods work also reliably
1179 on non-expanded input polynomials).  An application is illustrated in
1180 the next example, where a multivariate polynomial is analysed:
1181
1182 @example
1183 #include <ginac/ginac.h>
1184 using namespace GiNaC;
1185
1186 int main()
1187 @{
1188     symbol x("x"), y("y");
1189     ex PolyInp = 4*pow(x,3)*y + 5*x*pow(y,2) + 3*y
1190                  - pow(x+y,2) + 2*pow(y+2,2) - 8;
1191     ex Poly = PolyInp.expand();
1192     
1193     for (int i=Poly.ldegree(x); i<=Poly.degree(x); ++i) @{
1194         cout << "The x^" << i << "-coefficient is "
1195              << Poly.coeff(x,i) << endl;
1196     @}
1197     cout << "As polynomial in y: " 
1198          << Poly.collect(y) << endl;
1199     // ...
1200 @}
1201 @end example
1202
1203 When run, it returns an output in the following fashion:
1204
1205 @example
1206 The x^0-coefficient is y^2+11*y
1207 The x^1-coefficient is 5*y^2-2*y
1208 The x^2-coefficient is -1
1209 The x^3-coefficient is 4*y
1210 As polynomial in y: -x^2+(5*x+1)*y^2+(-2*x+4*x^3+11)*y
1211 @end example
1212
1213 As always, the exact output may vary between different versions of GiNaC
1214 or even from run to run since the internal canonical ordering is not
1215 within the user's sphere of influence.
1216
1217
1218 @node Polynomial Arithmetic, Symbolic Differentiation, Collecting expressions, Important Algorithms
1219 @c    node-name, next, previous, up
1220 @section Polynomial Arithmetic
1221
1222 @subsection GCD and LCM
1223 @cindex GCD
1224 @cindex LCM
1225
1226 The functions for polynomial greatest common divisor and least common
1227 multiple have the synopsis:
1228
1229 @example
1230 ex gcd(const ex & a, const ex & b);
1231 ex lcm(const ex & a, const ex & b);
1232 @end example
1233
1234 The functions @code{gcd()} and @code{lcm()} accept two expressions
1235 @code{a} and @code{b} as arguments and return a new expression, their
1236 greatest common divisor or least common multiple, respectively.  If the
1237 polynomials @code{a} and @code{b} are coprime @code{gcd(a,b)} returns 1
1238 and @code{lcm(a,b)} returns the product of @code{a} and @code{b}.
1239
1240 @example
1241 #include <ginac/ginac.h>
1242 using namespace GiNaC;
1243
1244 int main()
1245 @{
1246     symbol x("x"), y("y"), z("z");
1247     ex P_a = 4*x*y + x*z + 20*pow(y, 2) + 21*y*z + 4*pow(z, 2);
1248     ex P_b = x*y + 3*x*z + 5*pow(y, 2) + 19*y*z + 12*pow(z, 2);
1249
1250     ex P_gcd = gcd(P_a, P_b);
1251     // x + 5*y + 4*z
1252     ex P_lcm = lcm(P_a, P_b);
1253     // 4*x*y^2 + 13*y*x*z + 20*y^3 + 81*y^2*z + 67*y*z^2 + 3*x*z^2 + 12*z^3
1254     // ...
1255 @}
1256 @end example
1257
1258 @subsection The @code{normal} method
1259 @cindex @code{normal()}
1260 @cindex temporary replacement
1261
1262 While in common symbolic code @code{gcd()} and @code{lcm()} are not too
1263 heavily used, simplification is called for frequently.  Therefore
1264 @code{.normal()}, which provides some basic form of simplification, has
1265 become a method of class @code{ex}, just like @code{.expand()}.  It
1266 converts a rational function into an equivalent rational function where
1267 numerator and denominator are coprime.  This means, it finds the GCD of
1268 numerator and denominator and cancels it.  If it encounters some object
1269 which does not belong to the domain of rationals (a function for
1270 instance), that object is replaced by a temporary symbol.  This means
1271 that both expressions @code{t1} and @code{t2} are indeed simplified in
1272 this little program:
1273
1274 @example
1275 #include <ginac/ginac.h>
1276 using namespace GiNaC;
1277
1278 int main()
1279 @{
1280     symbol x("x");
1281     ex t1 = (pow(x,2) + 2*x + 1)/(x + 1);
1282     ex t2 = (pow(sin(x),2) + 2*sin(x) + 1)/(sin(x) + 1);
1283     cout << "t1 is " << t1.normal() << endl;
1284     cout << "t2 is " << t2.normal() << endl;
1285     // ...
1286 @}
1287 @end example
1288
1289 Of course this works for multivariate polynomials too, so the ratio of
1290 the sample-polynomials from the section about GCD and LCM above would be
1291 normalized to @code{P_a/P_b} = @code{(4*y+z)/(y+3*z)}.
1292
1293
1294 @node Symbolic Differentiation, Series Expansion, Polynomial Arithmetic, Important Algorithms
1295 @c    node-name, next, previous, up
1296 @section Symbolic Differentiation
1297 @cindex differentiation
1298 @cindex chain rule
1299 @cindex product rule
1300
1301 GiNaC's objects know how to differentiate themselves.  Thus, a
1302 polynomial (class @code{add}) knows that its derivative is the sum of
1303 the derivatives of all the monomials:
1304
1305 @example
1306 #include <ginac/ginac.h>
1307 using namespace GiNaC;
1308
1309 int main()
1310 @{
1311     symbol x("x"), y("y"), z("z");
1312     ex P = pow(x, 5) + pow(x, 2) + y;
1313
1314     cout << P.diff(x,2) << endl;  // 20*x^3 + 2
1315     cout << P.diff(y) << endl;    // 1
1316     cout << P.diff(z) << endl;    // 0
1317     // ...
1318 @}
1319 @end example
1320
1321 If a second integer parameter @var{n} is given, the @code{diff} method
1322 returns the @var{n}th derivative.
1323
1324 If @emph{every} object and every function is told what its derivative
1325 is, all derivatives of composed objects can be calculated using the
1326 chain rule and the product rule.  Consider, for instance the expression
1327 @code{1/cosh(x)}.  Since the derivative of @code{cosh(x)} is
1328 @code{sinh(x)} and the derivative of @code{pow(x,-1)} is
1329 @code{-pow(x,-2)}, GiNaC can readily compute the composition.  It turns
1330 out that the composition is the generating function for Euler Numbers,
1331 i.e. the so called @var{n}th Euler number is the coefficient of
1332 @code{x^n/n!} in the expansion of @code{1/cosh(x)}.  We may use this
1333 identity to code a function that generates Euler numbers in just three
1334 lines:
1335
1336 @cindex Euler numbers
1337 @example
1338 #include <ginac/ginac.h>
1339 using namespace GiNaC;
1340
1341 ex EulerNumber(unsigned n)
1342 @{
1343     symbol x;
1344     ex generator = pow(cosh(x),-1);
1345     return generator.diff(x,n).subs(x==0);
1346 @}
1347
1348 int main()
1349 @{
1350     for (unsigned i=0; i<11; i+=2)
1351         cout << EulerNumber(i) << endl;
1352     return 0;
1353 @}
1354 @end example
1355
1356 When you run it, it produces the sequence @code{1}, @code{-1}, @code{5},
1357 @code{-61}, @code{1385}, @code{-50521}.  We increment the loop variable
1358 @code{i} by two since all odd Euler numbers vanish anyways.
1359
1360
1361 @node Series Expansion, Extending GiNaC, Symbolic Differentiation, Important Algorithms
1362 @c    node-name, next, previous, up
1363 @section Series Expansion
1364 @cindex series expansion
1365 @cindex Taylor expansion
1366 @cindex Laurent expansion
1367
1368 Expressions know how to expand themselves as a Taylor series or (more
1369 generally) a Laurent series.  Similar to most conventional Computer
1370 Algebra Systems, no distinction is made between those two.  There is a
1371 class of its own for storing such series as well as a class for storing
1372 the order of the series.  A sample program could read:
1373
1374 @example
1375 #include <ginac/ginac.h>
1376 using namespace GiNaC;
1377
1378 int main()
1379 @{
1380     symbol x("x");
1381     numeric point(0);
1382     ex MyExpr1 = sin(x);
1383     ex MyExpr2 = 1/(x - pow(x, 2) - pow(x, 3));
1384     ex MyTailor, MySeries;
1385     
1386     MyTailor = MyExpr1.series(x, point, 5);
1387     cout << MyExpr1 << " == " << MyTailor
1388          << " for small " << x << endl;
1389     MySeries = MyExpr2.series(x, point, 7);
1390     cout << MyExpr2 << " == " << MySeries
1391          << " for small " << x << endl;
1392     // ...
1393 @}
1394 @end example
1395
1396 @cindex M@'echain's formula
1397 As an instructive application, let us calculate the numerical value of
1398 Archimedes' constant
1399 @tex
1400 $\pi$
1401 @end tex
1402 (for which there already exists the built-in constant @code{Pi}) 
1403 using M@'echain's amazing formula
1404 @tex
1405 $\pi=16$~atan~$\!\left(1 \over 5 \right)-4$~atan~$\!\left(1 \over 239 \right)$.
1406 @end tex
1407 @ifnottex
1408 @math{Pi==16*atan(1/5)-4*atan(1/239)}.
1409 @end ifnottex
1410 We may expand the arcus tangent around @code{0} and insert the fractions
1411 @code{1/5} and @code{1/239}.  But, as we have seen, a series in GiNaC
1412 carries an order term with it and the question arises what the system is
1413 supposed to do when the fractions are plugged into that order term.  The
1414 solution is to use the function @code{series_to_poly()} to simply strip
1415 the order term off:
1416
1417 @example
1418 #include <ginac/ginac.h>
1419 using namespace GiNaC;
1420
1421 ex mechain_pi(int degr)
1422 @{
1423     symbol x;
1424     ex pi_expansion = series_to_poly(atan(x).series(x,0,degr));
1425     ex pi_approx = 16*pi_expansion.subs(x==numeric(1,5))
1426                    -4*pi_expansion.subs(x==numeric(1,239));
1427     return pi_approx;
1428 @}
1429
1430 int main()
1431 @{
1432     ex pi_frac;
1433     for (int i=2; i<12; i+=2) @{
1434         pi_frac = mechain_pi(i);
1435         cout << i << ":\t" << pi_frac << endl
1436              << "\t" << pi_frac.evalf() << endl;
1437     @}
1438     return 0;
1439 @}
1440 @end example
1441
1442 When you run this program, it will type out:
1443
1444 @example
1445 2:      3804/1195
1446         3.1832635983263598326
1447 4:      5359397032/1706489875
1448         3.1405970293260603143
1449 6:      38279241713339684/12184551018734375
1450         3.141621029325034425
1451 8:      76528487109180192540976/24359780855939418203125
1452         3.141591772182177295
1453 10:     327853873402258685803048818236/104359128170408663038552734375
1454         3.1415926824043995174
1455 @end example
1456
1457
1458 @node Extending GiNaC, What does not belong into GiNaC, Series Expansion, Top
1459 @c    node-name, next, previous, up
1460 @chapter Extending GiNaC
1461
1462 By reading so far you should have gotten a fairly good understanding of
1463 GiNaC's design-patterns.  From here on you should start reading the
1464 sources.  All we can do now is issue some recommendations how to tackle
1465 GiNaC's many loose ends in order to fulfill everybody's dreams.  If you
1466 develop some useful extension please don't hesitate to contact the GiNaC
1467 authors---they will happily incorporate them into future versions.
1468
1469 @menu
1470 * What does not belong into GiNaC::  What to avoid.
1471 * Symbolic functions::               Implementing symbolic functions.
1472 @end menu
1473
1474
1475 @node What does not belong into GiNaC, Symbolic functions, Extending GiNaC, Extending GiNaC
1476 @c    node-name, next, previous, up
1477 @section What doesn't belong into GiNaC
1478
1479 @cindex @code{ginsh}
1480 First of all, GiNaC's name must be read literally.  It is designed to be
1481 a library for use within C++.  The tiny @command{ginsh} accompanying
1482 GiNaC makes this even more clear: it doesn't even attempt to provide a
1483 language.  There are no loops or conditional expressions in
1484 @command{ginsh}, it is merely a window into the library for the
1485 programmer to test stuff (or to show off).  Still, the design of a
1486 complete CAS with a language of its own, graphical capabilites and all
1487 this on top of GiNaC is possible and is without doubt a nice project for
1488 the future.
1489
1490 There are many built-in functions in GiNaC that do not know how to
1491 evaluate themselves numerically to a precision declared at runtime
1492 (using @code{Digits}).  Some may be evaluated at certain points, but not
1493 generally.  This ought to be fixed.  However, doing numerical
1494 computations with GiNaC's quite abstract classes is doomed to be
1495 inefficient.  For this purpose, the underlying bignum-package
1496 @acronym{CLN} is much better suited.
1497
1498
1499 @node Symbolic functions, A Comparison With Other CAS, What does not belong into GiNaC, Extending GiNaC
1500 @c    node-name, next, previous, up
1501 @section Symbolic functions
1502
1503 The easiest and most instructive way to start with is probably to
1504 implement your own function.  Objects of class @code{function} are
1505 inserted into the system via a kind of "registry".  They get a serial
1506 number that is used internally to identify them but you usually need not
1507 worry about this.  What you have to care for are functions that are
1508 called when the user invokes certain methods.  These are usual
1509 C++-functions accepting a number of @code{ex} as arguments and returning
1510 one @code{ex}.  As an example, if we have a look at a simplified
1511 implementation of the cosine trigonometric function, we first need a
1512 function that is called when one wishes to @code{eval} it.  It could
1513 look something like this:
1514
1515 @example
1516 static ex cos_eval_method(ex const & x)
1517 @{
1518     // if x%2*Pi return 1
1519     // if x%Pi return -1
1520     // if x%Pi/2 return 0
1521     // care for other cases...
1522     return cos(x).hold();
1523 @}
1524 @end example
1525
1526 The last line returns @code{cos(x)} if we don't know what else to do and
1527 stops a potential recursive evaluation by saying @code{.hold()}.  We
1528 should also implement a method for numerical evaluation and since we are
1529 lazy we sweep the problem under the rug by calling someone else's
1530 function that does so, in this case the one in class @code{numeric}:
1531
1532 @example
1533 static ex cos_evalf_method(ex const & x)
1534 @{
1535     return sin(ex_to_numeric(x));
1536 @}
1537 @end example
1538
1539 Differentiation will surely turn up and so we need to tell
1540 @code{sin} how to differentiate itself:
1541
1542 @example
1543 static ex cos_diff_method(ex const & x, unsigned diff_param)
1544 @{
1545     return cos(x);
1546 @}
1547 @end example
1548
1549 @cindex product rule
1550 The second parameter is obligatory but uninteresting at this point.  It
1551 specifies which parameter to differentiate in a partial derivative in
1552 case the function has more than one parameter and its main application
1553 is for correct handling of the chain rule.  For Taylor expansion, it is
1554 enough to know how to differentiate.  But if the function you want to
1555 implement does have a pole somewhere in the complex plane, you need to
1556 write another method for Laurent expansion around that point.
1557
1558 Now that all the ingrediences for @code{cos} have been set up, we need
1559 to tell the system about it.  This is done by a macro and we are not
1560 going to descibe how it expands, please consult your preprocessor if you
1561 are curious:
1562
1563 @example
1564 REGISTER_FUNCTION(cos, cos_eval_method, cos_evalf_method, cos_diff, NULL);
1565 @end example
1566
1567 The first argument is the function's name, the second, third and fourth
1568 bind the corresponding methods to this objects and the fifth is a slot
1569 for inserting a method for series expansion.  Also, the new function
1570 needs to be declared somewhere.  This may also be done by a convenient
1571 preprocessor macro:
1572
1573 @example
1574 DECLARE_FUNCTION_1P(cos)
1575 @end example
1576
1577 The suffix @code{_1P} stands for @emph{one parameter}.  Of course, this
1578 implementation of @code{cos} is very incomplete and lacks several safety
1579 mechanisms.  Please, have a look at the real implementation in GiNaC.
1580 (By the way: in case you are worrying about all the macros above we can
1581 assure you that functions are GiNaC's most macro-intense classes.  We
1582 have done our best to avoid them where we can.)
1583
1584 That's it. May the source be with you!
1585
1586
1587 @node A Comparison With Other CAS, Internal Structures, Symbolic functions, Top
1588 @c    node-name, next, previous, up
1589 @chapter A Comparison With Other CAS
1590 @cindex advocacy
1591
1592 This chapter will give you some information on how GiNaC compares to
1593 other, traditional Computer Algebra Systems, like @emph{Maple},
1594 @emph{Mathematica} or @emph{Reduce}, where it has advantages and
1595 disadvantages over these systems.
1596
1597
1598 @heading Advantages
1599
1600 GiNaC has several advantages over traditional Computer
1601 Algebra Systems, like 
1602
1603 @itemize @bullet
1604
1605 @item
1606 familiar language: all common CAS implement their own proprietary
1607 grammar which you have to learn first (and maybe learn again when your
1608 vendor chooses to "enhance" it).  With GiNaC you can write your program
1609 in common C++, which is standardized.
1610
1611 @item
1612 structured data types: you can build up structured data types using
1613 @code{struct}s or @code{class}es together with STL features instead of
1614 using unnamed lists of lists of lists.
1615
1616 @item
1617 strongly typed: in CAS, you usually have only one kind of variables
1618 which can hold contents of an arbitrary type.  This 4GL like feature is
1619 nice for novice programmers, but dangerous.
1620     
1621 @item
1622 development tools: powerful development tools exist for C++, like fancy
1623 editors (e.g. with automatic indentation and syntax highlighting),
1624 debuggers, visualization tools, documentation tools...
1625
1626 @item
1627 modularization: C++ programs can easily be split into modules by
1628 separating interface and implementation.
1629
1630 @item
1631 price: GiNaC is distributed under the GNU Public License which means
1632 that it is free and available with source code.  And there are excellent
1633 C++-compilers for free, too.
1634     
1635 @item
1636 extendable: you can add your own classes to GiNaC, thus extending it on
1637 a very low level.  Compare this to a traditional CAS that you can
1638 usually only extend on a high level by writing in the language defined
1639 by the parser.  In particular, it turns out to be almost impossible to
1640 fix bugs in a traditional system.
1641
1642 @item
1643 seemless integration: it is somewhere between difficult and impossible
1644 to call CAS functions from within a program written in C++ or any other
1645 programming language and vice versa.  With GiNaC, your symbolic routines
1646 are part of your program.  You can easily call third party libraries,
1647 e.g. for numerical evaluation or graphical interaction.  All other
1648 approaches are much more cumbersome: they range from simply ignoring the
1649 problem (i.e. @emph{Maple}) to providing a method for "embedding" the
1650 system (i.e. @emph{Yacas}).
1651
1652 @item
1653 efficiency: often large parts of a program do not need symbolic
1654 calculations at all.  Why use large integers for loop variables or
1655 arbitrary precision arithmetics where double accuracy is sufficient?
1656 For pure symbolic applications, GiNaC is comparable in speed with other
1657 CAS.
1658
1659 @end itemize
1660
1661
1662 @heading Disadvantages
1663
1664 Of course it also has some disadvantages:
1665
1666 @itemize @bullet
1667
1668 @item
1669 not interactive: GiNaC programs have to be written in an editor,
1670 compiled and executed. You cannot play with expressions interactively.
1671 However, such an extension is not inherently forbidden by design.  In
1672 fact, two interactive interfaces are possible: First, a simple shell
1673 that exposes GiNaC's types to a command line can readily be written (and
1674 has been written) and second, as a more consistent approach we plan an
1675 integration with the @acronym{CINT} C++ interpreter.
1676
1677 @item
1678 advanced features: GiNaC cannot compete with a program like
1679 @emph{Reduce} which exists for more than 30 years now or @emph{Maple}
1680 which grows since 1981 by the work of dozens of programmers, with
1681 respect to mathematical features. Integration, factorization,
1682 non-trivial simplifications, limits etc. are missing in GiNaC (and are
1683 not planned for the near future).
1684
1685 @item
1686 portability: While the GiNaC library itself is designed to avoid any
1687 platform dependent features (it should compile on any ANSI compliant C++
1688 compiler), the currently used version of the CLN library (fast large
1689 integer and arbitrary precision arithmetics) can be compiled only on
1690 systems with a recently new C++ compiler from the GNU Compiler
1691 Collection (@acronym{GCC}).  GiNaC uses recent language features like
1692 explicit constructors, mutable members, RTTI, @code{dynamic_cast}s and
1693 STL, so ANSI compliance is meant literally.  Recent @acronym{GCC}
1694 versions starting at 2.95, although itself not yet ANSI compliant,
1695 support all needed features.
1696     
1697 @end itemize
1698
1699
1700 @heading Why C++?
1701
1702 Why did we choose to implement GiNaC in C++ instead of Java or any other
1703 language? C++ is not perfect: type checking is not strict (casting is
1704 possible), separation between interface and implementation is not
1705 complete, object oriented design is not enforced.  The main reason is
1706 the often scolded feature of operator overloading in C++. While it may
1707 be true that operating on classes with a @code{+} operator is rarely
1708 meaningful, it is perfectly suited for algebraic expressions. Writing
1709 @math{3x+5y} as @code{3*x+5*y} instead of
1710 @code{x.times(3).plus(y.times(5))} looks much more natural. Furthermore,
1711 the main developers are more familiar with C++ than with any other
1712 programming language.
1713
1714
1715 @node Internal Structures, Expressions are reference counted, A Comparison With Other CAS, Top
1716 @c    node-name, next, previous, up
1717 @appendix Internal Structures
1718
1719 @menu
1720 * Expressions are reference counted::
1721 * Internal representation of products and sums::
1722 @end menu
1723
1724 @node Expressions are reference counted, Internal representation of products and sums, Internal Structures, Internal Structures
1725 @c    node-name, next, previous, up
1726 @appendixsection Expressions are reference counted
1727
1728 @cindex reference counting
1729 @cindex copy-on-write
1730 @cindex garbage collection
1731 An expression is extremely light-weight since internally it works like a
1732 handle to the actual representation and really holds nothing more than a
1733 pointer to some other object. What this means in practice is that
1734 whenever you create two @code{ex} and set the second equal to the first
1735 no copying process is involved. Instead, the copying takes place as soon
1736 as you try to change the second.  Consider the simple sequence of code:
1737
1738 @example
1739 #include <ginac/ginac.h>
1740 using namespace GiNaC;
1741
1742 int main()
1743 @{
1744     symbol x("x"), y("y"), z("z");
1745     ex e1, e2;
1746
1747     e1 = sin(x + 2*y) + 3*z + 41;
1748     e2 = e1;                // e2 points to same object as e1
1749     cout << e2 << endl;     // prints sin(x+2*y)+3*z+41
1750     e2 += 1;                // e2 is copied into a new object
1751     cout << e2 << endl;     // prints sin(x+2*y)+3*z+42
1752     // ...
1753 @}
1754 @end example
1755
1756 The line @code{e2 = e1;} creates a second expression pointing to the
1757 object held already by @code{e1}.  The time involved for this operation
1758 is therefore constant, no matter how large @code{e1} was.  Actual
1759 copying, however, must take place in the line @code{e2 += 1;} because
1760 @code{e1} and @code{e2} are not handles for the same object any more.
1761 This concept is called @dfn{copy-on-write semantics}.  It increases
1762 performance considerably whenever one object occurs multiple times and
1763 represents a simple garbage collection scheme because when an @code{ex}
1764 runs out of scope its destructor checks whether other expressions handle
1765 the object it points to too and deletes the object from memory if that
1766 turns out not to be the case.  A slightly less trivial example of
1767 differentiation using the chain-rule should make clear how powerful this
1768 can be:
1769
1770 @example
1771 #include <ginac/ginac.h>
1772 using namespace GiNaC;
1773
1774 int main()
1775 @{
1776     symbol x("x"), y("y");
1777
1778     ex e1 = x + 3*y;
1779     ex e2 = pow(e1, 3);
1780     ex e3 = diff(sin(e2), x);   // first derivative of sin(e2) by x
1781     cout << e1 << endl          // prints x+3*y
1782          << e2 << endl          // prints (x+3*y)^3
1783          << e3 << endl;         // prints 3*(x+3*y)^2*cos((x+3*y)^3)
1784     // ...
1785 @}
1786 @end example
1787
1788 Here, @code{e1} will actually be referenced three times while @code{e2}
1789 will be referenced two times.  When the power of an expression is built,
1790 that expression needs not be copied.  Likewise, since the derivative of
1791 a power of an expression can be easily expressed in terms of that
1792 expression, no copying of @code{e1} is involved when @code{e3} is
1793 constructed.  So, when @code{e3} is constructed it will print as
1794 @code{3*(x+3*y)^2*cos((x+3*y)^3)} but the argument of @code{cos()} only
1795 holds a reference to @code{e2} and the factor in front is just
1796 @code{3*e1^2}.
1797
1798 As a user of GiNaC, you cannot see this mechanism of copy-on-write
1799 semantics.  When you insert an expression into a second expression, the
1800 result behaves exactly as if the contents of the first expression were
1801 inserted.  But it may be useful to remember that this is not what
1802 happens.  Knowing this will enable you to write much more efficient
1803 code.  If you still have an uncertain feeling with copy-on-write
1804 semantics, we recommend you have a look at the
1805 @uref{http://www.cerfnet.com/~mpcline/c++-faq-lite/, C++-FAQ lite} by
1806 Marshall Cline.  Chapter 16 covers this issue and presents an
1807 implementation which is pretty close to the one in GiNaC.
1808
1809
1810 @node Internal representation of products and sums, Package Tools, Expressions are reference counted, Internal Structures
1811 @c    node-name, next, previous, up
1812 @appendixsection Internal representation of products and sums
1813
1814 @cindex representation
1815 @cindex @code{add}
1816 @cindex @code{mul}
1817 @cindex @code{power}
1818 Although it should be completely transparent for the user of
1819 GiNaC a short discussion of this topic helps to understand the sources
1820 and also explain performance to a large degree.  Consider the 
1821 unexpanded symbolic expression 
1822 @tex
1823 $2d^3 \left( 4a + 5b - 3 \right)$
1824 @end tex
1825 @ifnottex
1826 @math{2*d^3*(4*a+5*b-3)}
1827 @end ifnottex
1828 which could naively be represented by a tree of linear containers for
1829 addition and multiplication, one container for exponentiation with base
1830 and exponent and some atomic leaves of symbols and numbers in this
1831 fashion:
1832
1833 @image{repnaive}
1834
1835 @cindex pair-wise representation
1836 However, doing so results in a rather deeply nested tree which will
1837 quickly become inefficient to manipulate.  We can improve on this by
1838 representing the sum instead as a sequence of terms, each one being a
1839 pair of a purely numeric multiplicative coefficient and its rest.  In
1840 the same spirit we can store the multiplication as a sequence of terms,
1841 each having a numeric exponent and a possibly complicated base, the tree
1842 becomes much more flat:
1843
1844 @image{reppair}
1845
1846 The number @code{3} above the symbol @code{d} shows that @code{mul}
1847 objects are treated similarly where the coefficients are interpreted as
1848 @emph{exponents} now.  Addition of sums of terms or multiplication of
1849 products with numerical exponents can be coded to be very efficient with
1850 such a pair-wise representation.  Internally, this handling is performed
1851 by most CAS in this way.  It typically speeds up manipulations by an
1852 order of magnitude.  The overall multiplicative factor @code{2} and the
1853 additive term @code{-3} look somewhat out of place in this
1854 representation, however, since they are still carrying a trivial
1855 exponent and multiplicative factor @code{1} respectively.  Within GiNaC,
1856 this is avoided by adding a field that carries an overall numeric
1857 coefficient.  This results in the realistic picture of internal
1858 representation for
1859 @tex
1860 $2d^3 \left( 4a + 5b - 3 \right)$
1861 @end tex
1862 @ifnottex
1863 @math{2*d^3*(4*a+5*b-3)}
1864 @end ifnottex
1865 :
1866
1867 @image{repreal}
1868
1869 This also allows for a better handling of numeric radicals, since
1870 @code{sqrt(2)} can now be carried along calculations.  Now it should be
1871 clear, why both classes @code{add} and @code{mul} are derived from the
1872 same abstract class: the data representation is the same, only the
1873 semantics differs.  In the class hierarchy, methods for polynomial
1874 expansion and the like are reimplemented for @code{add} and @code{mul},
1875 but the data structure is inherited from @code{expairseq}.
1876
1877
1878 @node Package Tools, ginac-config, Internal representation of products and sums, Top
1879 @c    node-name, next, previous, up
1880 @appendix Package Tools
1881
1882 If you are creating a software package that uses the GiNaC library,
1883 setting the correct command line options for the compiler and linker
1884 can be difficult. GiNaC includes two tools to make this process easier.
1885
1886 @menu
1887 * ginac-config::   A shell script to detect compiler and linker flags.
1888 * AM_PATH_GINAC::  Macro for GNU automake.
1889 @end menu
1890
1891
1892 @node ginac-config, AM_PATH_GINAC, Package Tools, Package Tools
1893 @c    node-name, next, previous, up
1894 @section @command{ginac-config}
1895 @cindex ginac-config
1896
1897 @command{ginac-config} is a shell script that you can use to determine
1898 the compiler and linker command line options required to compile and
1899 link a program with the GiNaC library.
1900
1901 @command{ginac-config} takes the following flags:
1902
1903 @table @samp
1904 @item --version
1905 Prints out the version of GiNaC installed.
1906 @item --cppflags
1907 Prints '-I' flags pointing to the installed header files.
1908 @item --libs
1909 Prints out the linker flags necessary to link a program against GiNaC.
1910 @item --prefix[=@var{PREFIX}]
1911 If @var{PREFIX} is specified, overrides the configured value of @env{$prefix}.
1912 (And of exec-prefix, unless --exec-prefix is also specified)
1913 Otherwise, prints out the configured value of @env{$prefix}.
1914 @item --exec-prefix[=@var{PREFIX}]
1915 If @var{PREFIX} is specified, overrides the configured value of @env{$exec_prefix}.
1916 Otherwise, prints out the configured value of @env{$exec_prefix}.
1917 @end table
1918
1919 Typically, @command{ginac-config} will be used within a configure script,
1920 as described below. It, however, can also be used directly
1921 from the command line to compile a simple program. For example:
1922
1923 @example
1924 c++ -o simple `ginac-config --cppflags` simple.cpp `ginac-config --libs`
1925 @end example
1926
1927 This command line might expand to (for example):
1928
1929 @example
1930 cc -o simple -I/usr/local/include simple.cpp -L/usr/local/lib \
1931   -lginac -lcln -lstdc++
1932 @end example
1933
1934 Not only is the form using @command{ginac-config} easier to type, it will
1935 work on any system, no matter how GiNaC was configured.
1936
1937
1938 @node AM_PATH_GINAC, Configure script options, ginac-config, Package Tools
1939 @c    node-name, next, previous, up
1940 @section @samp{AM_PATH_GINAC}
1941 @cindex AM_PATH_GINAC
1942
1943 For packages configured using GNU automake, GiNaC also provides
1944 a macro to automate the process of checking for GiNaC.
1945
1946 @example
1947 AM_PATH_GINAC([@var{MINIMUM-VERSION}, [@var{ACTION-IF-FOUND} [, @var{ACTION-IF-NOT-FOUND}]]])
1948 @end example
1949
1950 This macro:
1951
1952 @itemize @bullet
1953
1954 @item
1955 Determines the location of GiNaC using @command{ginac-config}, which is
1956 either found in the user's path, or from the environment variable
1957 @env{GINACLIB_CONFIG}.
1958
1959 @item
1960 Tests the installed libraries to make sure that there version
1961 is later than @var{MINIMUM-VERSION}. (A default version will be used
1962 if not specified)
1963
1964 @item
1965 If the required version was found, sets the @env{GINACLIB_CPPFLAGS} variable
1966 to the output of @command{ginac-config --cppflags} and the @env{GINACLIB_LIBS}
1967 variable to the output of @command{ginac-config --libs}, and calls
1968 @samp{AC_SUBST()} for these variables so they can be used in generated
1969 makefiles, and then executes @var{ACTION-IF-FOUND}.
1970
1971 @item
1972 If the required version was not found, sets @env{GINACLIB_CPPFLAGS} and
1973 @env{GINACLIB_LIBS} to empty strings, and executes @var{ACTION-IF-NOT-FOUND}.
1974
1975 @end itemize
1976
1977 This macro is in file @file{ginac.m4} which is installed in
1978 @file{$datadir/aclocal}. Note that if automake was installed with a
1979 different @samp{--prefix} than GiNaC, you will either have to manually
1980 move @file{ginac.m4} to automake's @file{$datadir/aclocal}, or give
1981 aclocal the @samp{-I} option when running it.
1982
1983 @menu
1984 * Configure script options::  Configuring a package that uses AM_PATH_GINAC.
1985 * Example package::           Example of a package using AM_PATH_GINAC.
1986 @end menu
1987
1988
1989 @node Configure script options, Example package, AM_PATH_GINAC, AM_PATH_GINAC
1990 @c    node-name, next, previous, up
1991 @subsection Configuring a package that uses @samp{AM_PATH_GINAC}
1992
1993 Simply make sure that @command{ginac-config} is in your path, and run
1994 the configure script.
1995
1996 Notes:
1997
1998 @itemize @bullet
1999
2000 @item
2001 The directory where the GiNaC libraries are installed needs
2002 to be found by your system's dynamic linker.
2003   
2004 This is generally done by
2005
2006 @display
2007 editing @file{/etc/ld.so.conf} and running @command{ldconfig}
2008 @end display
2009
2010 or by
2011    
2012 @display
2013 setting the environment variable @env{LD_LIBRARY_PATH},
2014 @end display
2015
2016 or, as a last resort, 
2017  
2018 @display
2019 giving a @samp{-R} or @samp{-rpath} flag (depending on your linker) when
2020 running configure, for instance:
2021
2022 @example
2023 LDFLAGS=-R/home/cbauer/lib ./configure
2024 @end example
2025 @end display
2026
2027 @item
2028 You can also specify a @command{ginac-config} not in your path by
2029 setting the @env{GINACLIB_CONFIG} environment variable to the
2030 name of the executable
2031
2032 @item
2033 If you move the GiNaC package from its installed location,
2034 you will need either need to modify @command{ginac-config} script
2035 manually to point to the new location or rebuild GiNaC.
2036
2037 @end itemize
2038
2039 Advanced note:
2040
2041 @itemize @bullet
2042 @item
2043 configure flags
2044   
2045 @example
2046 --with-ginac-prefix=@var{PREFIX}
2047 --with-ginac-exec-prefix=@var{PREFIX}
2048 @end example
2049
2050 are provided to override the prefix and exec-prefix that were stored
2051 in the @command{ginac-config} shell script by GiNaC's configure. You are
2052 generally better off configuring GiNaC with the right path to begin with.
2053 @end itemize
2054
2055
2056 @node Example package, Bibliography, Configure script options, AM_PATH_GINAC
2057 @c    node-name, next, previous, up
2058 @subsection Example of a package using @samp{AM_PATH_GINAC}
2059
2060 The following shows how to build a simple package using automake
2061 and the @samp{AM_PATH_GINAC} macro. The program used here is @file{simple.cpp}:
2062
2063 @example
2064 #include <ginac/ginac.h>
2065 using namespace GiNaC;
2066
2067 int main(void)
2068 @{
2069     symbol x("x");
2070     ex a = sin(x); 
2071     cout << "Derivative of " << a << " is " << a.diff(x) << endl;
2072     return 0;
2073 @}
2074 @end example
2075
2076 You should first read the introductory portions of the automake
2077 Manual, if you are not already familiar with it.
2078
2079 Two files are needed, @file{configure.in}, which is used to build the
2080 configure script:
2081
2082 @example
2083 dnl Process this file with autoconf to produce a configure script.
2084 AC_INIT(simple.cpp)
2085 AM_INIT_AUTOMAKE(simple.cpp, 1.0.0)
2086
2087 AC_PROG_CXX
2088 AC_PROG_INSTALL
2089 AC_LANG_CPLUSPLUS
2090
2091 AM_PATH_GINAC(0.4.0, [
2092   LIBS="$LIBS $GINACLIB_LIBS"
2093   CPPFLAGS="$CFLAGS $GINACLIB_CPPFLAGS"  
2094 ], AC_MSG_ERROR([need to have GiNaC installed]))
2095
2096 AC_OUTPUT(Makefile)
2097 @end example
2098
2099 The only command in this which is not standard for automake
2100 is the @samp{AM_PATH_GINAC} macro.
2101
2102 That command does the following:
2103
2104 @display
2105 If a GiNaC version greater than 0.4.0 is found, adds @env{$GINACLIB_LIBS} to 
2106 @env{$LIBS} and @env{$GINACLIB_CPPFLAGS} to @env{$CPPFLAGS}. Otherwise, dies
2107 with the error message "need to have GiNaC installed"
2108 @end display
2109
2110 And the @file{Makefile.am}, which will be used to build the Makefile.
2111
2112 @example
2113 ## Process this file with automake to produce Makefile.in
2114 bin_PROGRAMS = simple
2115 simple_SOURCES = simple.cpp
2116 @end example
2117
2118 This @file{Makefile.am}, says that we are building a single executable,
2119 from a single sourcefile @file{simple.cpp}. Since every program
2120 we are building uses GiNaC we simply added the GiNaC options
2121 to @env{$LIBS} and @env{$CPPFLAGS}, but in other circumstances, we might
2122 want to specify them on a per-program basis: for instance by
2123 adding the lines:
2124
2125 @example
2126 simple_LDADD = $(GINACLIB_LIBS)
2127 INCLUDES = $(GINACLIB_CPPFLAGS)
2128 @end example
2129
2130 to the @file{Makefile.am}.
2131
2132 To try this example out, create a new directory and add the three
2133 files above to it.
2134
2135 Now execute the following commands:
2136
2137 @example
2138 $ automake --add-missing
2139 $ aclocal
2140 $ autoconf
2141 @end example
2142
2143 You now have a package that can be built in the normal fashion
2144
2145 @example
2146 $ ./configure
2147 $ make
2148 $ make install
2149 @end example
2150
2151
2152 @node Bibliography, Concept Index, Example package, Top
2153 @c    node-name, next, previous, up
2154 @appendix Bibliography
2155
2156 @itemize @minus{}
2157
2158 @item
2159 @cite{ISO/IEC 14882:1998: Programming Languages: C++}
2160
2161 @item
2162 @cite{CLN: A Class Library for Numbers}, @email{haible@@ilog.fr, Bruno Haible}
2163
2164 @item
2165 @cite{The C++ Programming Language}, Bjarne Stroustrup, 3rd Edition, ISBN 0-201-88954-4, Addison Wesley
2166
2167 @item
2168 @cite{C++ FAQs}, Marshall Cline, ISBN 0-201-58958-3, 1995, Addison Wesley
2169
2170 @item
2171 @cite{Algorithms for Computer Algebra}, Keith O. Geddes, Stephen R. Czapor,
2172 and George Labahn, ISBN 0-7923-9259-0, 1992, Kluwer Academic Publishers, Norwell, Massachusetts
2173
2174 @item
2175 @cite{Computer Algebra: Systems and Algorithms for Algebraic Computation},
2176 J.H. Davenport, Y. Siret, and E. Tournier, ISBN 0-12-204230-1, 1988, 
2177 Academic Press, London
2178
2179 @end itemize
2180
2181
2182 @node Concept Index, , Bibliography, Top
2183 @c    node-name, next, previous, up
2184 @unnumbered Concept Index
2185
2186 @printindex cp
2187
2188 @bye
2189