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