Giac API


Noeud « Next »: , Noeud « Up »: (dir)

Giac is a C++ library that has types for symbolic algebraic manipulations. Xcas is a GUI linked with Giac that provides the functionnalities of a general purpose computer algebra system. Giac's name derive from http://www.ginac.de, another C++ library for symbolic algebraic computations.


Noeud « Next »: , Noeud « Previous »: Top, Noeud « Up »: Top

1 Installing giac


Noeud « Next »: , Noeud « Previous »: Installation, Noeud « Up »: Installation

1.1 Installing binaries

If you want to use xcas/giac like another CAS and your OS is Intel x86 GNU/Linux or Intel StrongARM GNU/Linux or Windows 9x, then you don't need to worry about compilation. Instead you can install precompiled binaries:


Noeud « Next »: , Noeud « Previous »: Binaries, Noeud « Up »: Installation

1.2 Requirements

Get Giac source at ftp://fourier.ujf-grenoble.fr/pub/hp48/giac.tgz or http://perso.wanadoo.fr/bernard.parisse/giac-0.2.2.tar.gz. Check that your C++ compiler understand the C++ ANSI 3 norm. For example gcc version 2.95 or later will work. If the GMP GNU Math Precision Library is not installed on your system, install it: http://www.gnu.org/directory/gnump.html. If you are using GNU/Linux, the GMP library is most probably installed but the headers files might not, check for a package named something like gmp-devel.


Noeud « Next »: , Noeud « Previous »: Requirements, Noeud « Up »: Installation

1.3 Options

  1. If you want numerical functions you should install the Gnu Scientific Library available at http://sources.redhat.com/gsl
  2. If you want to use NTL for some polynomial operations (currently factorization), get version >= 5.2 at http://www.shoup.net. Then check that you configured with namespace enabled (this is not the default) and with GMP enabled (not the default, but this is not mandatory) If you are not sure of your install go in the NTL directory and type
               make clean
               ./configure NTL_GMP_LIP=on NTL_STD_CXX=on
               make
               make install
         
  3. If you want advanced arithmetic functions, get PARI at http://www.parigp-home.de. If you plan to use PARI WITHOUT NTL then you MUST MAKE THE FOLLOWING PATCHES in the PARI source directory: Check in the giac src directory, file pari.cc that the memory allocated to the PARI stack suit your needs (default is 10M of RAM) or modify: long pari_mem_size=10000000;
  4. If you want GUI support, check that you have FLTK 1.0 (or FLNX) installed (available at http://www.fltk.org). Additionnaly you can get modifications to FLTK 1.0.11 from http://www-fourier.ujf-grenoble.fr/~parisse/fltkpar.tgz this add auto-selection of matching parentheses. WARNING: Currently xcas does not work with FLTK 1.1. For the matrix editor/spreadsheet, you will additionnaly need FLVW http://flvw.sourceforge.net/
  5. TeXmacs provides an interface for giac. You can get it at http://www.texmacs.org. After installing giac, run texmacs and use Insert->Session->giac.


Noeud « Next »: , Noeud « Previous »: Options, Noeud « Up »: Installation

1.4 Configure options

The ./configure shell-script recognizes the following options:

  1. –enable-debug Allow vecteurs printing and add some debugging code
  2. –enable-fltk GUI support
  3. –enable-gsl Use the Gnu Scientific Library for floating point (e.g. special functions..)
  4. –enable-sscl Allow inclusion of code for semi-classical algorithms (Moyal product, ...) Not available yet
  5. –enable-ntl Allow inclusion of NTL code
  6. –enable-pari Allow inclusion of PARI code

These options can be turned off using --disable-option-name instead of --enable-option-name. By default configure will use these options if the libraries are available on your system.

For full speed binaries, before calling configure do (with bash as shell)

$ export CXXFLAGS="-O3 -fexpensive-optimizations -malign-loops=2 -malign-jumps=2 -malign-functions=2"

or (with tcsh as shell)

$ setenv CXXFLAGS "-O3 -fexpensive-optimizations -malign-loops=2 -malign-jumps=2 -malign-functions=2"


Noeud « Next »: , Noeud « Previous »: Configure, Noeud « Up »: Installation

1.5 Compiling

Like with any autoconfiguring GNU software, you can type :

./configure

[add options as needed: try ./configure -help for option info]

make

make check

[become root if necessary]

make install

Tips:


Noeud « Previous »: Compiling, Noeud « Up »: Installation

1.6 Troubles


Noeud « Next »: , Noeud « Previous »: Installation, Noeud « Up »: Top

2 Using xcas, an user-interface to giac

xcas is an user-interface to giac that is similar to a calculator. A readline interface named cas is also available.


Noeud « Next »: , Noeud « Up »: Xcas

2.1 The interface

You can use but you don't need a keyboard to use xcas since this interface is designed to be used on a PDA as well. Use the green shift button to get the button-keyboard.

The window is composed from left and up to right and down of:

  1. The main menu-bar
  2. The history or graphic window
  3. The history toolbar and Edit/plot menu
  4. The commandline
  5. The soft menu bar (like in the HP4x graphing calculators)
  6. On-line help
  7. Calculator-like buttons on the right

The interface ressembles advanced graphing calculators (TI89, TI92, HP49G in algebraic mode): you write a command in the commandline with the help of the keyboard and/or the buttons, on-line help and menus. Then hitting Enter will evaluate your expression and return the answer in the history area. If your command returns a graphical object the history window will be replaced by the graphic window. You can switch from history window to graphic window by hand using the Geo button in the soft menu bar.

The on-line help gives a short description of all the CAS commands with examples that can be pasted to the commandline. It is available by default in xcas or by the aide command from a shell.

Printing requires a working LaTeX installation with pstricks.


Noeud « Next »: , Noeud « Previous »: Interface, Noeud « Up »: Xcas

2.2 Computer algebra system commands

A list of commands of the CAS system.


Noeud « Next »: , Noeud « Up »: CAS

2.2.1 Basic mathematic commands


Noeud « Next »: , Noeud « Previous »: Math menu, Noeud « Up »: CAS

2.2.2 Arithmetic of integers and polynomials

The gcd and lcm commands apply to both argument types : they return the greatest common divisor or the least common multiplicator. Other arithmetic commands must begin with an i if you want to use them with integers, otherwise the arguments will be considered as constant polynomials.


Noeud « Next »: , Noeud « Up »: Arithmetic
2.2.2.1 Integer arithmetic functions


Noeud « Next »: , Noeud « Up »: Integer arithmetic
2.2.2.2 Euclidean integer division

Given two integers a and b, the euclidean integer division is defined by the equality :

     a=b*q+r

where usually r is taken between 0 and b-1, or in the symmetric representation, between -b/2 and b/2. The functions iquo(a,b) and irem(a,b) return respectively q and r, or iquorem(a,b) return both in a vector. The smod(a,b) function will return r using the symmetric remainder convention.


Noeud « Next »: , Noeud « Previous »: Division, Noeud « Up »: Integer arithmetic
2.2.2.3 Integer gcd

The gcd(a,b) function returns the greatest common divisor d of two integers a and b. If you need two integers u and v such that:

     a*u+b*v=d

you should call egcd(a,b) instead, it will return [u,v,d].

The ichinrem([a,n],[b,m]) call where n and m are prime together will return a vector [c,n*m] such that c=a (mod n) and c=b (mod m).


Noeud « Next »: , Noeud « Previous »: Gcd, Noeud « Up »: Integer arithmetic
2.2.2.4 Primality and factorization

The is_prime(a) function will return 0 if a is not prime. If will return 2 if a is known to be prime, and 1 if a is a (strong) pseudo-prime. If you have compiled xcas with PARI support, you will get a prime certificate instead (see PARI documentation for more information).

The nextprime(a) and prevprime(a) will return the next or previous (pseudo-)prime, given an integer a.

The ifactor(a) function returns a factorization of a. It is a good idea to compile with PARI support if you plan to factor relatively large integers (with prime factors having more than 20 digits).


Noeud « Previous »: Primality, Noeud « Up »: Integer arithmetic
2.2.2.5 Other integer functions (Legendre, Jacobi, ...)

Additional integer functions provided by xcas are


Noeud « Previous »: Integer arithmetic, Noeud « Up »: Arithmetic
2.2.2.6 Polynomial arithmetic functions

Polynomials have two representations: symbolic representation or by a vector of coefficients. In the symbolic representation you might add the variable name as an additionnal parameter to the functions you call, otherwise the default variable is used. For the vector representation, it is recommended to use the right delimiter poly1[ instead of [ so that usual operations (addition, ...) behave correctly (i.e. not like vectors or matrices).

  1. quo(a,b) rem(a,b) and quorem(a,b) return respectively q, r and [q,r] polynomials so that a=b*q+r and degree(r)<degree(b)
  2. gcd(a,b) return the greatest common divisor of two polynomials
  3. egcd(a,b) is the extended euclidean GCD algorithm, like for integers it returns a list of 3 polynomials u,v,d such that au+bv=d.
  4. chinrem return the chinese remainder for polynomials written as lists. The 2 arguments are two lists made of a polynomial modulo another polynomial (where the modulo polynomials must be prime together). The answer is the polynomial modulo the product of the modulo polynomials that reduce to the original polynomials modulo the original modulo polynomials
  5. cyclotomic takes an integer n as argument and returns the n-th cyclotomic polynomial.


Noeud « Next »: , Noeud « Previous »: Arithmetic, Noeud « Up »: CAS

2.2.3 Algebra, calculus, ...


Noeud « Next »: , Noeud « Up »: Cas menu
2.2.3.1 Rewriting expressions

The normal command rewrites a rational fraction as a ratio of two coprime polynomials. If an expression is not rational, it is first rationalized by substitution of transcendental expressions (e.g. sin(x) by a temporary identifier. Algebraic expressions (e.g. sqrt(x)) are normalized too.

The factor command factorize polynomials. Like above a non polynomial expression is first rationalized. You can choose the main variable with respect to which the polynomial will be factorized by adding it as second argument of factor.

The texpand function is called to expand transcendental expressions like exp(x+y)=exp(x)*exp(y) or similar rules for trigonometric functions. The tlin function does the reverse operation for trigonometric functions, as the lin function does it for exponentials.

The halftan function rewrites trigonometric expressions in terms of the tangent of the half angle. The hyp2exp function rewrites hyperbolic functions in terms of exponentials.


Noeud « Next »: , Noeud « Previous »: Rewriting, Noeud « Up »: Cas menu
2.2.3.2 Derivation, integration

The differentiation instruction is diff(expression,variable). The undefined antiderivative is obtained using integrate(expression,variable). If you need defined integration between bounds a and b, choose integrate(expression,variable,a,b) for exact integration or romberg(expression,variable,a,b) for numeric integration.

Example of defined integration are Fourier coefficients of periodic functions. They are provided using fourier_an and fourier_bn for trigonometric coefficients or using fourier_cn for complex exponentials coefficients.

Some discrete antiderivatives may be obtained using the sum(variable,expression) call.


Noeud « Next »: , Noeud « Previous »: Diff and integrate, Noeud « Up »: Cas menu
2.2.3.3 Limits, series expansion.

For a limit the syntax is limit(expression,variable,limitpoint[,direction]). For a series expansion series(expression,variable,limitpoint,order[,direction]). giac implementation of limit and series is based on the mrv algorithm.


Noeud « Next »: , Noeud « Previous »: Limits and series, Noeud « Up »: Cas menu

2.2.4 Solving equations

The solve(expression,variable) call is used to find exact solutions of (polynomial-)like equations. Use newton instead for numeric solutions (of a wider range of equations).


Noeud « Previous »: Solving equations, Noeud « Up »: Cas menu


Noeud « Previous »: Cas menu, Noeud « Up »: CAS

2.2.5 Linear algebra

Arithmetic operations on matrices and vectors are done using the usual operators. The scalar product of two vectors is obtained using the * operator.

Gaussian elimination (Gauss-Bareiss) over a matrix is performed using rref(m). The kernel of a linear application with matrix m is obtained with ker(m). A system of linear equations (written symbolically in a vector) can be solved via linsolve([equations],[variables]).

The determinant of a matrix may be obtained using two algorithms, either Gauss-Bareiss invoking det(m), or by computing minors det_minor(m). Actually, a last method is provided using the computation of the constant coefficient of the characteristic polynomial using Fadeev-Leverrier algorithm.

The characteristic polynomial of a matrix may be computed by Fadeev-Leverrier algorithm calling pcar(m). For matrices withe coefficients in a finite field, pcar_hessenberg(m) is a better choice (O(n^3) complexity where n is the size of the matrix).

Eigenvalues and eigenvectors are computed using respectively egvl(m) and egv(m). The Jordan normal form is obtained invoking jordan(m).

Quadratic forms (written symbolically) can be reduced to sum and differences of squares using gauss(expression,[variables]).

There is some support for isometries: mkisom may be used to make an isometry from its proper elements as isom(m) return the proper elements of an isometry.


Noeud « Next »: , Noeud « Previous »: CAS, Noeud « Up »: Xcas

2.3 Geometry

As other objects, you can create geometrical objects anatically using the commandline. Additionnally, if the graphic window is active (click on the Geo button if necessary), you can create points and segments with the mouse (or the stylus) or move a geometrical object. To create a point just click. To create a line, push any button of the mouse, move the mouse and release it at the second point. To move an object, first select it by clicking near it. The commandline should display the name of the object. You can drag it by pushing the mouse near the object and moving. Release the mouse at the final position. You can cancel a move by release the mouse out of the graphical window. As with any dynamical geometry package, all objects depending on an object will move when you move this object.

To print the current graph, you can use the graph2tex() instruction either with no argument (then the LaTeX code will be inserted at its place in the history) or with a string containing the name of a file where you save a standalone version of the graph, for example graph2tex("figure.tex") will create a file named figure.tex that you can compile with latex figure.tex.


Noeud « Next »: , Noeud « Previous »: Geometry, Noeud « Up »: Xcas

2.4 The xcas scripting language

The xcas and cas program provide an interpreted language that is similar to the popular other CAS programming language. This scripting language is available in 3 flavours: C-like syntax (default) or compatibility mode for simple Maple or Mupad programs. We describe only the C-like syntax. Instructions must end with a semi-column ;. Groups of instructions may be combined like in C with brackets.


Noeud « Next »: , Noeud « Up »: Scripting

2.5 Selecting the language mode

The command maple_mode(0) or maple_mode(1) or maple_mode(2) may be used to switch the language flavour respectively from C-like to Maple-like or Mupad-like mode. Note that this command takes effect only when the current parser session is finished which means when the next command is processed in interative mode or at the end of the current file in batch mode, hence you should not begin a script file with this command. In batch mode you can achieve the mode switch by setting the environment variable GIAC_MAPLE_MODE, for example with tcsh: setenv GIAC_MAPLE_MODE 1 or with bash export GIAC_MAPLE_MODE=1 will switch to the Maple-like language. Additionnally you can enter the maple_mode(1) command in the .xcasrc of your home directory to change the default behavior. Or inside xcas you can run the Import command of the File menu and select the flavour. The Export command can be used to translate the current level of the history inside xcas to a file, or the View as command of the Edit menu to translate to the Help output window.


Noeud « Next »: , Noeud « Previous »: Language mode, Noeud « Up »: Scripting

2.6 Data

The language accept local and global variables, variables are not typed. Global variables do not need to be declared, local variables must be declared at the beginning of a function by the keyword local followed by the names of the local variables separated by commas , with a final semi-columns ;

The affectation sign is := like popular CAS and unlike C. Other operations (e.g. {+ - * /}) and function calls are done like in C or like in an interactive session. As in C, the equality test is ==. The single equal sign = is used to return an equation (this equation will be checked as a test only in some situations where an equation can not be expected). The other tests are != for non equal, < <= > >= for real value comparisons. You can combine tests with && or and, and || or or. The boolean negation is ! or not.


Noeud « Next »: , Noeud « Previous »: Data, Noeud « Up »: Scripting

The loop keywoard is like in C

for (initialization;while_condition;increment){ loop_block }

You can break a loop inside the loop block with break;. You can skip immediately to the next iteration with continue;.

The conditionnal keywoard is like in C

if (condition) { bloc_if_true } [ else { bloc_if_false } ]

Additionnaly, multiple-cases is translated like in C

swith (variable){ case (value_1): ... break; default: ... ; }


Noeud « Previous »: Loops and conditionnals, Noeud « Up »: Scripting

Functions are declared and implemeted together like this

function_name(parameters):={ definition }

Parameters are like local variables with an additional initialization from the values of the parameters inside the calling instruction.

The return(return_value) should be used to return the value of the function.

It is not possible to pass arguments by reference, only by value.

Once a function is defined, a file named function_name.cas is generated in the current directory. It is a good idea to group function definitions corresponding to the same topic in a file named with a .cc extension (so that C-like indentation occurs automatically when you edit this file with your favorite editor) and "compile" these file with cas ccfilename.cc or inside xcas with the Run file command from the Files menu.

Once a function is defined, if you modify the corresponding .cas file, it will not affect the corresponding function definition during the current session.


Noeud « Previous »: Scripting, Noeud « Up »: Xcas

2.7 Environment variables

If one of these variables GIAC_MAPLE, GIAC_MUPAD, GIAC_C or GIAC_TI is defined, the corresponding syntax mode will be in effect. If XCAS_RPN is defined, then xcas will start in RPN mode.

The variable XCAS_ROOT may be used for a custom xcas installation, it should point to the directory where xcas is installed. XCAS_LOCALE should point to the directory where the locales are. XCAS_TMP may be defined for temporary exchange files between xcas processes, if not defined it will use the home directory.

The variable PARI_SIZE may be used to define the memory available for pari.

The variable BROWSER may be used for the HTML documentation browser.

The variable LANG may be used for internationalization.

The variable GIAC_TIME and GIAC_TEX may be used in giac readline interface to ask for timing and tex output. GIAC_DEBUG will give some info on the internals used.


Noeud « Next »: , Noeud « Previous »: Xcas, Noeud « Up »: Top

In this chapter we will first describe the generic data type of giac, the gen class. Then we describe the most important data types than gen dispatches to (polynomials, vectors, symbolic objects and gen unary functions). At this point, the reader should be able to code using giac, hence we describe how to integrate code to giac by inclusion in the library or as a separate runtime loadable library (called module). The last item describes how you can add new mathematical objects, e.g. quaternions, inside the gen type.


Noeud « Next »: , Noeud « Up »: Giac

Giac uses the C++ language because it is easier to write algebraic operations using usual operators, for example a+b*x is easier to understand and modify than add(a,mul(b,x)), but it does not require that you learn object oriented programming. In fact it is more a C library using C++ features that makes programming easier (like the I/O streams and the Standard Template Library). However you will need a recent C++ compiler, e.g. gcc version 2.95 or later.


Noeud « Next »: , Noeud « Previous »: C++, Noeud « Up »: Giac

3 The gen class

gen is the class used to represent mathematical objects (#include <giac/gen.h>). It's a C union, made either of “direct” objects like int or double or of pointers to heap allocated objects that are reference counted. Memory allocation is handled by the class itself (except for user-defined object types). You can check the actual type of a variable of type gen, e.g. gen e;, using it's type field (e.g. if (e.type==...)). This type field of a gen is an int.

The gen might be~:

  1. an immediate int (e.type==_INT_)
  2. a double (e.type==_REAL)
  3. an arbitrary precision integer (e.type==_ZINT)
  4. a complex number (e.type==_CINT), a pointer to two objects of type gen the real and imaginary parts
  5. a global name (e.type==_IDNT), with a pointer to an identificateur type
  6. a symbolic object (e.type==_SYMB), with a pointer to a symbolic type
  7. a vector object (in fact it is a list) (e.type==_VECT), with a pointer to a vecteur type
  8. a function object (e.type==_FUNC), with a pointer to a unary_function_ptr type

Some other types are available (e.g. a pointer to gen_user an object you can derive to make your own class, or arbitrary precision floating point numbers that will be implemented later), for a complete description look at giac/gen.h (if you have installed giac the path to the include files is /usr/local/include/giac unless you override the default, if you did not install it, the path is the path to the src directory of the source code distribution).

If you want to access the underlying type, after checking that the type is correct, you can do the following:

  1. for immediate int: int i=e.val;
  2. for double: double d=e._DOUBLE_val;
  3. for arbitray precision integers: mpz_t * m=e._ZINTptr;
  4. for complex numbers: gen realpart=*e._CINTptr;
  5. for identificateur: identificateur i=*e._IDNTptr;
  6. for symbolics: symbolic s=*e._SYMBptr;
  7. for composites: vecteur v=*e._VECTptr;
  8. for function objects: unary_function_ptr u=*e._FUNCptr

In addition to the main type, each gen has a subtype. This subtype is used sometimes to select different behaviour, e.g. adding a constant to a vector might add the constant to all terms for some geometric objects represented using vectors, only to the term of the diagonal of a square matrix, or to the last term for dense polynomials. See giac/dispatch.h for the description of the subtypes.


Noeud « Next »: , Noeud « Previous »: Gen, Noeud « Up »: Giac

3.1 Polynomials

Polynomials are available as:

A gen can be a polynomials if it's type field is respectively _POLY (sparse) or _VECT (dense). Conversion functions to and from the symbolic representation with respect to global names are declared in giac/sym2poly.cc.


Noeud « Next »: , Noeud « Previous »: Polynomials, Noeud « Up »: Giac

3.2 Vectors and matrices

The type used for vectors and matrices is the same, it's a std::vector<gen> (unless you have configured with --enable-debug). The header file is giac/vecteur.h. A gen can be a vector if it's type field is _VECT.


Noeud « Next »: , Noeud « Previous »: Vectors and matrices, Noeud « Up »: Giac

3.3 Symbolics

Symbolic objects are trees. The sommet is a unary_function_ptr (a class pointing to the function). The feuille is either an atomic gen (for a function with one argument) or a composite (feuille.type==_VECT) for a function with more than one argument (these functions appears therefore as a function with one argument which is the list of all it's arguments).


Noeud « Next »: , Noeud « Previous »: Symbolics, Noeud « Up »: Giac

3.4 Unary functions

In the giac library, every function is viewed as a function taking one argument and returning one argument. If a function should have more than one argument, we pack these arguments in a vector.

The files usual.cc/.h give examples of declaration e.g. for exponential and trigonometric functions. Unary functions have the following members~:

Once your unary_function_unary is defined, you must construct a unary_function_ptr to be able to use it inside symbolics.

You may give an optional argument to specify a behavior for the evaluation of arguments (quoting). In this case, you may give a second optionnal argument to register your function dynamically in the list of function names recognized by the lexer. Be sure to link the object file so that initialization occurs after the initialization of input_lexer.ll, it means you must put your object file before input_lexer.o when linking (see for example the position of moyal.o in the Makefile.am file, moyal is one example where dynamic registering is done).

You have of course the option to declare the function name statically in the file input_lexer.ll.

You must always declare a function statically if it does not follow the standard syntax for a function.


Noeud « Next »: , Noeud « Previous »: Unary functions, Noeud « Up »: Giac

Here is one example of a dynamically linkable function named example which takes 2 arguments and returns the sum divided by the product if the argument are integers and return itself otherwise. The C++ header example.h code looks like

     #ifndef __EXAMPLE_H
     #define __EXAMPLE_H
     #include <giac/gen.h>
     #include <giac/unary.h>
     
     #ifndef NO_NAMESPACE_GIAC
     namespace giac {
     #endif // ndef NO_NAMESPACE_GIAC
     
       gen example(const gen & a,const gen & b);
       gen _example(const gen & args);
       extern unary_function_ptr at_example ;
     
     #ifndef NO_NAMESPACE_GIAC
     } // namespace giac
     #endif // ndef NO_NAMESPACE_GIAC
     #endif // __EXAMPLE_H

The C++ source code looks like:

     using namespace std;
     #include <giac/giac.h>
     #include "example.h"
     
     #ifndef NO_NAMESPACE_GIAC
     namespace giac {
     #endif // ndef NO_NAMESPACE_GIAC
     
       gen example(const gen & a,const gen & b){
         if (is_integer(a) && is_integer(b))
           return (a+b)/(a*b);
         return symbolic(at_example,makevecteur(a,b));
       }
     
       gen _example(const gen & args){
         if ( (args.type!=_VECT) || (args._VECTptr->size()!=2) )
           setsizeerr(); // type checking : args must be a vector of size 2
         vecteur & v=*args._VECTptr;
         return example(v[0],v[1]);
       }
       const string _example_s("example");
       unary_function_unary __example(&_example,_example_s);
       unary_function_ptr at_example (&__example,0,true);
     
     #ifndef NO_NAMESPACE_GIAC
     }
     #endif // ndef NO_NAMESPACE_GIAC

Compile it with

     c++ -g -c example.cc

To test your code, you should write the following test.cc program

     #include "example.h"
     
     using namespace std;
     using namespace giac;
     
     int main(){
       gen args;
       cout << "Enter argument of example function";
       cin >> args;
       cout << "Result: " << _example(args) << endl;
     }

Compile it with the command

     c++ -g example.o test.cc -lgiac -lgmp

You might need to link to other libraries e.g. -lreadline -lhistory -lcurses depedning on your installation. Then run a.out. Here you would test e.g. with [1,2].

You can debug your program as usual, e.g. with gdb a.out, it is recommended to create a .gdbinit file in the current directory so that you can use the v command to print giac data, the .gdbinit file should contain :

     echo Defining v as print command for giac types\n
     define v
     print ($arg0).dbgprint()
     end

When your function is tested, you can add it to the library. Edit the file Makefile.am of the src subdirectory of giac : just add example.cc before input_lexer.cc in the libgiac_la_SOURCES line and add example.h in the giacinclude_HEADERS line.

To rebuild the library go in the giac directory and type automake; make

If you want to share your function(s) with other people, you must license it under the GPL (because it will be linked to GPL-ed code). Add the GPL header to the files, and send them to the giac contribution e-mail, currently mailto:parisse@fourier.ujf-grenoble.fr

     /*
      *  Copyright (C) 2002 Your name
      *
      *  This program is free software; you can redistribute it and/or modify
      *  it under the terms of the GNU General Public License as published by
      *  the Free Software Foundation; either version 2 of the License, or
      *  (at your option) any later version.
      *
      *  This program is distributed in the hope that it will be useful,
      *  but WITHOUT ANY WARRANTY; without even the implied warranty of
      *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      *  GNU General Public License for more details.
      *
      *  You should have received a copy of the GNU General Public License
      *  along with this program; if not, write to the Free Software
      *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
      */


Noeud « Next »: , Noeud « Previous »: Making a library function, Noeud « Up »: Giac

Another way to share your code could be to build a dynamic library that can be loaded at runtime using facilities of <dlfcns.h>. Warning: modules do not work with static binaries. Be sure to have dynamic binaries (this is the default when you compile giac, but the packaged xcas distributed as a binary is build static to avoid incompatible libraries).

Let us define a function named mydll in the file mydll.cc like this :

     #include <giac/giac.h>
     
     #ifndef NO_NAMESPACE_GIAC
     namespace giac {
     #endif // ndef NO_NAMESPACE_GIAC
     
       const string _mydll_s("mydll");
       gen _mydll(const gen & args){
         return sin(ln(args));
       }
       unary_function_unary __mydll(&giac::_mydll,_mydll_s);
       unary_function_ptr at_mydll (&__mydll,0,true); // auto-register
     
     #ifndef NO_NAMESPACE_GIAC
     } // namespace giac
     #endif // ndef NO_NAMESPACE_GIAC

Compile it like this

     c++ -fPIC -DPIC -g -c mydll.cc -o mydll.lo
     cc -shared  mydll.lo  -lc  -Wl,-soname -Wl,libmydll.so.0 -o libmydll.so.0.0.0
     rm -f libmydll.so.0 && ln -s libmydll.so.0.0.0 libmydll.so.0
     rm -f libmydll.so && ln -s libmydll.so.0.0.0 libmydll.so

The library is loadable at runtime in a session using the command insmod("libmydll.so") assuming it is stored in a directory available from LD_LIBRARY_PATH or in /etc/ld.so.conf otherwise you must put a path to the library file (beginning with ./ if it is in the current directory).

A nice way to test your code is to add the following line in your ~/.xcasrc file :

     insmod("path_to_libmydll/libmydll.so");

where you replace path_to_libmydll.so with the actual path to libmydll.so for example /home/joe if your login name is joe and mydll is in your home directory. Then if you are using emacs as editor, put as first line of the file mydll.cc

     // -*- mode:C++ ; compile-command: "g++ -I.. -fPIC -DPIC -g -c mydll.cc -o mydll.lo && ln -sf mydll.lo mydll.o && gcc -shared mydll.lo -lc  -Wl,-soname -Wl,libmydll.so.0 -o libmydll.so.0.0.0 && ln -sf libmydll.so.0.0.0 libmydll.so.0 && ln -sf libmydll.so.0.0.0 libmydll.so" -*-

Now you can compile it with Compile of the menu Tools and the resulting code is automatically loaded when you launch a new session with xcas or cas which makes testing a breath.


Noeud « Previous »: Making modules, Noeud « Up »: Giac

3.5 User defined data

The class gen_user can be derived so that you can include your own data inside gen. Look at the declaration of gen_user in the file gen.h and at the example of the quaternions in the files quater.h and quater.cc.


Noeud « Next »: , Noeud « Previous »: Giac, Noeud « Up »: Top

4 Some examples of C++ program using giac


Noeud « Up »: Examples

5 A first simple example

Type the following text with your favorite editor

     #include <giac/giac.h>
     using namespace std;
     using namespace giac;
     
     int main(){
       gen e(string("x^2-1"));
       cout << factor(e) << endl;
     }

save it e.g. as tryit.cc and compile it with

c++ -g tryit.cc -lgiac -lgmp

If you get unresolved symbol, then readline is probably enabled and you should compile like that

c++ -g tryit.cc -lgiac -lgmp -lreadline -lcurses

You can now run a.out which will print the factorisation of x^2-1.

You can also run the program step by step using gdb. We recommended that you copy the file .gdbinit from the src directory of the giac distribution, because it enables using v varname to print the variable varname of type gen.

Some explanations of the code:


Noeud « Previous »: Examples, Noeud « Up »: Top

Concept Index

Table des matières