]> www.ginac.de Git - ginac.git/blob - ginac/numeric.cpp
- Made configure warn a lot when readline-stuff couldn't be found.
[ginac.git] / ginac / numeric.cpp
1 /** @file numeric.cpp
2  *
3  *  This file contains the interface to the underlying bignum package.
4  *  Its most important design principle is to completely hide the inner
5  *  working of that other package from the user of GiNaC.  It must either 
6  *  provide implementation of arithmetic operators and numerical evaluation
7  *  of special functions or implement the interface to the bignum package. */
8
9 /*
10  *  GiNaC Copyright (C) 1999-2000 Johannes Gutenberg University Mainz, Germany
11  *
12  *  This program is free software; you can redistribute it and/or modify
13  *  it under the terms of the GNU General Public License as published by
14  *  the Free Software Foundation; either version 2 of the License, or
15  *  (at your option) any later version.
16  *
17  *  This program is distributed in the hope that it will be useful,
18  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
19  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  *  GNU General Public License for more details.
21  *
22  *  You should have received a copy of the GNU General Public License
23  *  along with this program; if not, write to the Free Software
24  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25  */
26
27 #include "config.h"
28
29 #include <vector>
30 #include <stdexcept>
31 #include <string>
32
33 #if defined(HAVE_SSTREAM)
34 #include <sstream>
35 #elif defined(HAVE_STRSTREAM)
36 #include <strstream>
37 #else
38 #error Need either sstream or strstream
39 #endif
40
41 #include "numeric.h"
42 #include "ex.h"
43 #include "archive.h"
44 #include "debugmsg.h"
45 #include "utils.h"
46
47 // CLN should not pollute the global namespace, hence we include it here
48 // instead of in some header file where it would propagate to other parts.
49 // Also, we only need a subset of CLN, so we don't include the complete cln.h:
50 #ifdef HAVE_CLN_CLN_H
51 #include <cln/cl_integer_io.h>
52 #include <cln/cl_integer_ring.h>
53 #include <cln/cl_rational_io.h>
54 #include <cln/cl_rational_ring.h>
55 #include <cln/cl_lfloat_class.h>
56 #include <cln/cl_lfloat_io.h>
57 #include <cln/cl_real_io.h>
58 #include <cln/cl_real_ring.h>
59 #include <cln/cl_complex_io.h>
60 #include <cln/cl_complex_ring.h>
61 #include <cln/cl_numtheory.h>
62 #else  // def HAVE_CLN_CLN_H
63 #include <cl_integer_io.h>
64 #include <cl_integer_ring.h>
65 #include <cl_rational_io.h>
66 #include <cl_rational_ring.h>
67 #include <cl_lfloat_class.h>
68 #include <cl_lfloat_io.h>
69 #include <cl_real_io.h>
70 #include <cl_real_ring.h>
71 #include <cl_complex_io.h>
72 #include <cl_complex_ring.h>
73 #include <cl_numtheory.h>
74 #endif  // def HAVE_CLN_CLN_H
75
76 #ifndef NO_NAMESPACE_GINAC
77 namespace GiNaC {
78 #endif  // ndef NO_NAMESPACE_GINAC
79
80 // linker has no problems finding text symbols for numerator or denominator
81 //#define SANE_LINKER
82
83 GINAC_IMPLEMENT_REGISTERED_CLASS(numeric, basic)
84
85 //////////
86 // default constructor, destructor, copy constructor assignment
87 // operator and helpers
88 //////////
89
90 // public
91
92 /** default ctor. Numerically it initializes to an integer zero. */
93 numeric::numeric() : basic(TINFO_numeric)
94 {
95     debugmsg("numeric default constructor", LOGLEVEL_CONSTRUCT);
96     value = new cl_N;
97     *value=cl_I(0);
98     calchash();
99     setflag(status_flags::evaluated|
100             status_flags::hash_calculated);
101 }
102
103 numeric::~numeric()
104 {
105     debugmsg("numeric destructor" ,LOGLEVEL_DESTRUCT);
106     destroy(0);
107 }
108
109 numeric::numeric(const numeric & other)
110 {
111     debugmsg("numeric copy constructor", LOGLEVEL_CONSTRUCT);
112     copy(other);
113 }
114
115 const numeric & numeric::operator=(const numeric & other)
116 {
117     debugmsg("numeric operator=", LOGLEVEL_ASSIGNMENT);
118     if (this != &other) {
119         destroy(1);
120         copy(other);
121     }
122     return *this;
123 }
124
125 // protected
126
127 void numeric::copy(const numeric & other)
128 {
129     basic::copy(other);
130     value = new cl_N(*other.value);
131 }
132
133 void numeric::destroy(bool call_parent)
134 {
135     delete value;
136     if (call_parent) basic::destroy(call_parent);
137 }
138
139 //////////
140 // other constructors
141 //////////
142
143 // public
144
145 numeric::numeric(int i) : basic(TINFO_numeric)
146 {
147     debugmsg("numeric constructor from int",LOGLEVEL_CONSTRUCT);
148     // Not the whole int-range is available if we don't cast to long
149     // first. This is due to the behaviour of the cl_I-ctor, which
150     // emphasizes efficiency:
151     value = new cl_I((long) i);
152     calchash();
153     setflag(status_flags::evaluated|
154             status_flags::hash_calculated);
155 }
156
157
158 numeric::numeric(unsigned int i) : basic(TINFO_numeric)
159 {
160     debugmsg("numeric constructor from uint",LOGLEVEL_CONSTRUCT);
161     // Not the whole uint-range is available if we don't cast to ulong
162     // first. This is due to the behaviour of the cl_I-ctor, which
163     // emphasizes efficiency:
164     value = new cl_I((unsigned long)i);
165     calchash();
166     setflag(status_flags::evaluated|
167             status_flags::hash_calculated);
168 }
169
170
171 numeric::numeric(long i) : basic(TINFO_numeric)
172 {
173     debugmsg("numeric constructor from long",LOGLEVEL_CONSTRUCT);
174     value = new cl_I(i);
175     calchash();
176     setflag(status_flags::evaluated|
177             status_flags::hash_calculated);
178 }
179
180
181 numeric::numeric(unsigned long i) : basic(TINFO_numeric)
182 {
183     debugmsg("numeric constructor from ulong",LOGLEVEL_CONSTRUCT);
184     value = new cl_I(i);
185     calchash();
186     setflag(status_flags::evaluated|
187             status_flags::hash_calculated);
188 }
189
190 /** Ctor for rational numerics a/b.
191  *
192  *  @exception overflow_error (division by zero) */
193 numeric::numeric(long numer, long denom) : basic(TINFO_numeric)
194 {
195     debugmsg("numeric constructor from long/long",LOGLEVEL_CONSTRUCT);
196     if (!denom)
197         throw (std::overflow_error("division by zero"));
198     value = new cl_I(numer);
199     *value = *value / cl_I(denom);
200     calchash();
201     setflag(status_flags::evaluated|
202             status_flags::hash_calculated);
203 }
204
205
206 numeric::numeric(double d) : basic(TINFO_numeric)
207 {
208     debugmsg("numeric constructor from double",LOGLEVEL_CONSTRUCT);
209     // We really want to explicitly use the type cl_LF instead of the
210     // more general cl_F, since that would give us a cl_DF only which
211     // will not be promoted to cl_LF if overflow occurs:
212     value = new cl_N;
213     *value = cl_float(d, cl_default_float_format);
214     calchash();
215     setflag(status_flags::evaluated|
216             status_flags::hash_calculated);
217 }
218
219
220 numeric::numeric(const char *s) : basic(TINFO_numeric)
221 {   // MISSING: treatment of complex and ints and rationals.
222     debugmsg("numeric constructor from string",LOGLEVEL_CONSTRUCT);
223     if (strchr(s, '.'))
224         value = new cl_LF(s);
225     else
226         value = new cl_I(s);
227     calchash();
228     setflag(status_flags::evaluated|
229             status_flags::hash_calculated);
230 }
231
232 /** Ctor from CLN types.  This is for the initiated user or internal use
233  *  only. */
234 numeric::numeric(const cl_N & z) : basic(TINFO_numeric)
235 {
236     debugmsg("numeric constructor from cl_N", LOGLEVEL_CONSTRUCT);
237     value = new cl_N(z);
238     calchash();
239     setflag(status_flags::evaluated|
240             status_flags::hash_calculated);
241 }
242
243 //////////
244 // archiving
245 //////////
246
247 /** Construct object from archive_node. */
248 numeric::numeric(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
249 {
250     debugmsg("numeric constructor from archive_node", LOGLEVEL_CONSTRUCT);
251     value = new cl_N;
252 #ifdef HAVE_SSTREAM
253     // Read number as string
254     string str;
255     if (n.find_string("number", str)) {
256         istringstream s(str);
257         cl_idecoded_float re, im;
258         char c;
259         s.get(c);
260         switch (c) {
261             case 'N':    // Ordinary number
262             case 'R':    // Integer-decoded real number
263                 s >> re.sign >> re.mantissa >> re.exponent;
264                 *value = re.sign * re.mantissa * ::expt(cl_float(2.0, cl_default_float_format), re.exponent);
265                 break;
266             case 'C':    // Integer-decoded complex number
267                 s >> re.sign >> re.mantissa >> re.exponent;
268                 s >> im.sign >> im.mantissa >> im.exponent;
269                 *value = ::complex(re.sign * re.mantissa * ::expt(cl_float(2.0, cl_default_float_format), re.exponent),
270                                  im.sign * im.mantissa * ::expt(cl_float(2.0, cl_default_float_format), im.exponent));
271                 break;
272             default:    // Ordinary number
273                                 s.putback(c);
274                 s >> *value;
275                 break;
276         }
277     }
278 #else
279     // Read number as string
280     string str;
281     if (n.find_string("number", str)) {
282         istrstream f(str.c_str(), str.size() + 1);
283         cl_idecoded_float re, im;
284         char c;
285         f.get(c);
286         switch (c) {
287             case 'R':    // Integer-decoded real number
288                 f >> re.sign >> re.mantissa >> re.exponent;
289                 *value = re.sign * re.mantissa * ::expt(cl_float(2.0, cl_default_float_format), re.exponent);
290                 break;
291             case 'C':    // Integer-decoded complex number
292                 f >> re.sign >> re.mantissa >> re.exponent;
293                 f >> im.sign >> im.mantissa >> im.exponent;
294                 *value = ::complex(re.sign * re.mantissa * ::expt(cl_float(2.0, cl_default_float_format), re.exponent),
295                                  im.sign * im.mantissa * ::expt(cl_float(2.0, cl_default_float_format), im.exponent));
296                 break;
297             default:    // Ordinary number
298                                 f.putback(c);
299                 f >> *value;
300                                 break;
301         }
302     }
303 #endif
304     calchash();
305     setflag(status_flags::evaluated|
306             status_flags::hash_calculated);
307 }
308
309 /** Unarchive the object. */
310 ex numeric::unarchive(const archive_node &n, const lst &sym_lst)
311 {
312     return (new numeric(n, sym_lst))->setflag(status_flags::dynallocated);
313 }
314
315 /** Archive the object. */
316 void numeric::archive(archive_node &n) const
317 {
318     inherited::archive(n);
319 #ifdef HAVE_SSTREAM
320     // Write number as string
321     ostringstream s;
322     if (this->is_crational())
323         s << *value;
324     else {
325         // Non-rational numbers are written in an integer-decoded format
326         // to preserve the precision
327         if (this->is_real()) {
328             cl_idecoded_float re = integer_decode_float(The(cl_F)(*value));
329             s << "R";
330             s << re.sign << " " << re.mantissa << " " << re.exponent;
331         } else {
332             cl_idecoded_float re = integer_decode_float(The(cl_F)(::realpart(*value)));
333             cl_idecoded_float im = integer_decode_float(The(cl_F)(::imagpart(*value)));
334             s << "C";
335             s << re.sign << " " << re.mantissa << " " << re.exponent << " ";
336             s << im.sign << " " << im.mantissa << " " << im.exponent;
337         }
338     }
339     n.add_string("number", s.str());
340 #else
341     // Write number as string
342     char buf[1024];
343     ostrstream f(buf, 1024);
344     if (this->is_crational())
345         f << *value << ends;
346     else {
347         // Non-rational numbers are written in an integer-decoded format
348         // to preserve the precision
349         if (this->is_real()) {
350             cl_idecoded_float re = integer_decode_float(The(cl_F)(*value));
351             f << "R";
352             f << re.sign << " " << re.mantissa << " " << re.exponent << ends;
353         } else {
354             cl_idecoded_float re = integer_decode_float(The(cl_F)(::realpart(*value)));
355             cl_idecoded_float im = integer_decode_float(The(cl_F)(::imagpart(*value)));
356             f << "C";
357             f << re.sign << " " << re.mantissa << " " << re.exponent << " ";
358             f << im.sign << " " << im.mantissa << " " << im.exponent << ends;
359         }
360     }
361     string str(buf);
362     n.add_string("number", str);
363 #endif
364 }
365
366 //////////
367 // functions overriding virtual functions from bases classes
368 //////////
369
370 // public
371
372 basic * numeric::duplicate() const
373 {
374     debugmsg("numeric duplicate", LOGLEVEL_DUPLICATE);
375     return new numeric(*this);
376 }
377
378 void numeric::print(ostream & os, unsigned upper_precedence) const
379 {
380     // The method print adds to the output so it blends more consistently
381     // together with the other routines and produces something compatible to
382     // ginsh input.
383     debugmsg("numeric print", LOGLEVEL_PRINT);
384     if (this->is_real()) {
385         // case 1, real:  x  or  -x
386         if ((precedence<=upper_precedence) && (!this->is_pos_integer())) {
387             os << "(" << *value << ")";
388         } else {
389             os << *value;
390         }
391     } else {
392         // case 2, imaginary:  y*I  or  -y*I
393         if (::realpart(*value) == 0) {
394             if ((precedence<=upper_precedence) && (::imagpart(*value) < 0)) {
395                 if (::imagpart(*value) == -1) {
396                     os << "(-I)";
397                 } else {
398                     os << "(" << ::imagpart(*value) << "*I)";
399                 }
400             } else {
401                 if (::imagpart(*value) == 1) {
402                     os << "I";
403                 } else {
404                     if (::imagpart (*value) == -1) {
405                         os << "-I";
406                     } else {
407                         os << ::imagpart(*value) << "*I";
408                     }
409                 }
410             }
411         } else {
412             // case 3, complex:  x+y*I  or  x-y*I  or  -x+y*I  or  -x-y*I
413             if (precedence <= upper_precedence) os << "(";
414             os << ::realpart(*value);
415             if (::imagpart(*value) < 0) {
416                 if (::imagpart(*value) == -1) {
417                     os << "-I";
418                 } else {
419                     os << ::imagpart(*value) << "*I";
420                 }
421             } else {
422                 if (::imagpart(*value) == 1) {
423                     os << "+I";
424                 } else {
425                     os << "+" << ::imagpart(*value) << "*I";
426                 }
427             }
428             if (precedence <= upper_precedence) os << ")";
429         }
430     }
431 }
432
433
434 void numeric::printraw(ostream & os) const
435 {
436     // The method printraw doesn't do much, it simply uses CLN's operator<<()
437     // for output, which is ugly but reliable. e.g: 2+2i
438     debugmsg("numeric printraw", LOGLEVEL_PRINT);
439     os << "numeric(" << *value << ")";
440 }
441
442
443 void numeric::printtree(ostream & os, unsigned indent) const
444 {
445     debugmsg("numeric printtree", LOGLEVEL_PRINT);
446     os << string(indent,' ') << *value
447        << " (numeric): "
448        << "hash=" << hashvalue << " (0x" << hex << hashvalue << dec << ")"
449        << ", flags=" << flags << endl;
450 }
451
452
453 void numeric::printcsrc(ostream & os, unsigned type, unsigned upper_precedence) const
454 {
455     debugmsg("numeric print csrc", LOGLEVEL_PRINT);
456     ios::fmtflags oldflags = os.flags();
457     os.setf(ios::scientific);
458     if (this->is_rational() && !this->is_integer()) {
459         if (compare(_num0()) > 0) {
460             os << "(";
461             if (type == csrc_types::ctype_cl_N)
462                 os << "cl_F(\"" << numer().evalf() << "\")";
463             else
464                 os << numer().to_double();
465         } else {
466             os << "-(";
467             if (type == csrc_types::ctype_cl_N)
468                 os << "cl_F(\"" << -numer().evalf() << "\")";
469             else
470                 os << -numer().to_double();
471         }
472         os << "/";
473         if (type == csrc_types::ctype_cl_N)
474             os << "cl_F(\"" << denom().evalf() << "\")";
475         else
476             os << denom().to_double();
477         os << ")";
478     } else {
479         if (type == csrc_types::ctype_cl_N)
480             os << "cl_F(\"" << evalf() << "\")";
481         else
482             os << to_double();
483     }
484     os.flags(oldflags);
485 }
486
487
488 bool numeric::info(unsigned inf) const
489 {
490     switch (inf) {
491     case info_flags::numeric:
492     case info_flags::polynomial:
493     case info_flags::rational_function:
494         return true;
495     case info_flags::real:
496         return is_real();
497     case info_flags::rational:
498     case info_flags::rational_polynomial:
499         return is_rational();
500     case info_flags::crational:
501     case info_flags::crational_polynomial:
502         return is_crational();
503     case info_flags::integer:
504     case info_flags::integer_polynomial:
505         return is_integer();
506     case info_flags::cinteger:
507     case info_flags::cinteger_polynomial:
508         return is_cinteger();
509     case info_flags::positive:
510         return is_positive();
511     case info_flags::negative:
512         return is_negative();
513     case info_flags::nonnegative:
514         return compare(_num0())>=0;
515     case info_flags::posint:
516         return is_pos_integer();
517     case info_flags::negint:
518         return is_integer() && (compare(_num0())<0);
519     case info_flags::nonnegint:
520         return is_nonneg_integer();
521     case info_flags::even:
522         return is_even();
523     case info_flags::odd:
524         return is_odd();
525     case info_flags::prime:
526         return is_prime();
527     }
528     return false;
529 }
530
531 /** Disassemble real part and imaginary part to scan for the occurrence of a
532  *  single number.  Also handles the imaginary unit.  It ignores the sign on
533  *  both this and the argument, which may lead to what might appear as funny
534  *  results:  (2+I).has(-2) -> true.  But this is consistent, since we also
535  *  would like to have (-2+I).has(2) -> true and we want to think about the
536  *  sign as a multiplicative factor. */
537 bool numeric::has(const ex & other) const
538 {
539     if (!is_exactly_of_type(*other.bp, numeric))
540         return false;
541     const numeric & o = static_cast<numeric &>(const_cast<basic &>(*other.bp));
542     if (this->is_equal(o) || this->is_equal(-o))
543         return true;
544     if (o.imag().is_zero())  // e.g. scan for 3 in -3*I
545         return (this->real().is_equal(o) || this->imag().is_equal(o) ||
546                 this->real().is_equal(-o) || this->imag().is_equal(-o));
547     else {
548         if (o.is_equal(I))  // e.g scan for I in 42*I
549             return !this->is_real();
550         if (o.real().is_zero())  // e.g. scan for 2*I in 2*I+1
551             return (this->real().has(o*I) || this->imag().has(o*I) ||
552                     this->real().has(-o*I) || this->imag().has(-o*I));
553     }
554     return false;
555 }
556
557
558 /** Evaluation of numbers doesn't do anything at all. */
559 ex numeric::eval(int level) const
560 {
561     // Warning: if this is ever gonna do something, the ex ctors from all kinds
562     // of numbers should be checking for status_flags::evaluated.
563     return this->hold();
564 }
565
566
567 /** Cast numeric into a floating-point object.  For example exact numeric(1) is
568  *  returned as a 1.0000000000000000000000 and so on according to how Digits is
569  *  currently set.
570  *
571  *  @param level  ignored, but needed for overriding basic::evalf.
572  *  @return  an ex-handle to a numeric. */
573 ex numeric::evalf(int level) const
574 {
575     // level can safely be discarded for numeric objects.
576     return numeric(::cl_float(1.0, ::cl_default_float_format) * (*value));  // -> CLN
577 }
578
579 // protected
580
581 /** Implementation of ex::diff() for a numeric. It always returns 0.
582  *
583  *  @see ex::diff */
584 ex numeric::derivative(const symbol & s) const
585 {
586     return _ex0();
587 }
588
589
590 int numeric::compare_same_type(const basic & other) const
591 {
592     GINAC_ASSERT(is_exactly_of_type(other, numeric));
593     const numeric & o = static_cast<numeric &>(const_cast<basic &>(other));
594
595     if (*value == *o.value) {
596         return 0;
597     }
598
599     return compare(o);    
600 }
601
602
603 bool numeric::is_equal_same_type(const basic & other) const
604 {
605     GINAC_ASSERT(is_exactly_of_type(other,numeric));
606     const numeric *o = static_cast<const numeric *>(&other);
607     
608     return this->is_equal(*o);
609 }
610
611 /*
612 unsigned numeric::calchash(void) const
613 {
614     double d=to_double();
615     int s=d>0 ? 1 : -1;
616     d=fabs(d);
617     if (d>0x07FF0000) {
618         d=0x07FF0000;
619     }
620     return 0x88000000U+s*unsigned(d/0x07FF0000);
621 }
622 */
623
624
625 //////////
626 // new virtual functions which can be overridden by derived classes
627 //////////
628
629 // none
630
631 //////////
632 // non-virtual functions in this class
633 //////////
634
635 // public
636
637 /** Numerical addition method.  Adds argument to *this and returns result as
638  *  a new numeric object. */
639 numeric numeric::add(const numeric & other) const
640 {
641     return numeric((*value)+(*other.value));
642 }
643
644 /** Numerical subtraction method.  Subtracts argument from *this and returns
645  *  result as a new numeric object. */
646 numeric numeric::sub(const numeric & other) const
647 {
648     return numeric((*value)-(*other.value));
649 }
650
651 /** Numerical multiplication method.  Multiplies *this and argument and returns
652  *  result as a new numeric object. */
653 numeric numeric::mul(const numeric & other) const
654 {
655     static const numeric * _num1p=&_num1();
656     if (this==_num1p) {
657         return other;
658     } else if (&other==_num1p) {
659         return *this;
660     }
661     return numeric((*value)*(*other.value));
662 }
663
664 /** Numerical division method.  Divides *this by argument and returns result as
665  *  a new numeric object.
666  *
667  *  @exception overflow_error (division by zero) */
668 numeric numeric::div(const numeric & other) const
669 {
670     if (::zerop(*other.value))
671         throw (std::overflow_error("division by zero"));
672     return numeric((*value)/(*other.value));
673 }
674
675 numeric numeric::power(const numeric & other) const
676 {
677     static const numeric * _num1p=&_num1();
678     if (&other==_num1p)
679         return *this;
680     if (::zerop(*value)) {
681         if (::zerop(*other.value))
682             throw (std::domain_error("numeric::eval(): pow(0,0) is undefined"));
683         else if (other.is_real() && !::plusp(::realpart(*other.value)))
684             throw (std::overflow_error("numeric::eval(): division by zero"));
685         else
686             return _num0();
687     }
688     return numeric(::expt(*value,*other.value));
689 }
690
691 /** Inverse of a number. */
692 numeric numeric::inverse(void) const
693 {
694     return numeric(::recip(*value));  // -> CLN
695 }
696
697 const numeric & numeric::add_dyn(const numeric & other) const
698 {
699     return static_cast<const numeric &>((new numeric((*value)+(*other.value)))->
700                                         setflag(status_flags::dynallocated));
701 }
702
703 const numeric & numeric::sub_dyn(const numeric & other) const
704 {
705     return static_cast<const numeric &>((new numeric((*value)-(*other.value)))->
706                                         setflag(status_flags::dynallocated));
707 }
708
709 const numeric & numeric::mul_dyn(const numeric & other) const
710 {
711     static const numeric * _num1p=&_num1();
712     if (this==_num1p) {
713         return other;
714     } else if (&other==_num1p) {
715         return *this;
716     }
717     return static_cast<const numeric &>((new numeric((*value)*(*other.value)))->
718                                         setflag(status_flags::dynallocated));
719 }
720
721 const numeric & numeric::div_dyn(const numeric & other) const
722 {
723     if (::zerop(*other.value))
724         throw (std::overflow_error("division by zero"));
725     return static_cast<const numeric &>((new numeric((*value)/(*other.value)))->
726                                         setflag(status_flags::dynallocated));
727 }
728
729 const numeric & numeric::power_dyn(const numeric & other) const
730 {
731     static const numeric * _num1p=&_num1();
732     if (&other==_num1p)
733         return *this;
734     if (::zerop(*value)) {
735         if (::zerop(*other.value))
736             throw (std::domain_error("numeric::eval(): pow(0,0) is undefined"));
737         else if (other.is_real() && !::plusp(::realpart(*other.value)))
738             throw (std::overflow_error("numeric::eval(): division by zero"));
739         else
740             return _num0();
741     }
742     return static_cast<const numeric &>((new numeric(::expt(*value,*other.value)))->
743                                         setflag(status_flags::dynallocated));
744 }
745
746 const numeric & numeric::operator=(int i)
747 {
748     return operator=(numeric(i));
749 }
750
751 const numeric & numeric::operator=(unsigned int i)
752 {
753     return operator=(numeric(i));
754 }
755
756 const numeric & numeric::operator=(long i)
757 {
758     return operator=(numeric(i));
759 }
760
761 const numeric & numeric::operator=(unsigned long i)
762 {
763     return operator=(numeric(i));
764 }
765
766 const numeric & numeric::operator=(double d)
767 {
768     return operator=(numeric(d));
769 }
770
771 const numeric & numeric::operator=(const char * s)
772 {
773     return operator=(numeric(s));
774 }
775
776 /** Return the complex half-plane (left or right) in which the number lies.
777  *  csgn(x)==0 for x==0, csgn(x)==1 for Re(x)>0 or Re(x)=0 and Im(x)>0,
778  *  csgn(x)==-1 for Re(x)<0 or Re(x)=0 and Im(x)<0.
779  *
780  *  @see numeric::compare(const numeric & other) */
781 int numeric::csgn(void) const
782 {
783     if (this->is_zero())
784         return 0;
785     if (!::zerop(::realpart(*value))) {
786         if (::plusp(::realpart(*value)))
787             return 1;
788         else
789             return -1;
790     } else {
791         if (::plusp(::imagpart(*value)))
792             return 1;
793         else
794             return -1;
795     }
796 }
797
798 /** This method establishes a canonical order on all numbers.  For complex
799  *  numbers this is not possible in a mathematically consistent way but we need
800  *  to establish some order and it ought to be fast.  So we simply define it
801  *  to be compatible with our method csgn.
802  *
803  *  @return csgn(*this-other)
804  *  @see numeric::csgn(void) */
805 int numeric::compare(const numeric & other) const
806 {
807     // Comparing two real numbers?
808     if (this->is_real() && other.is_real())
809         // Yes, just compare them
810         return ::cl_compare(The(cl_R)(*value), The(cl_R)(*other.value));    
811     else {
812         // No, first compare real parts
813         cl_signean real_cmp = ::cl_compare(::realpart(*value), ::realpart(*other.value));
814         if (real_cmp)
815             return real_cmp;
816
817         return ::cl_compare(::imagpart(*value), ::imagpart(*other.value));
818     }
819 }
820
821 bool numeric::is_equal(const numeric & other) const
822 {
823     return (*value == *other.value);
824 }
825
826 /** True if object is zero. */
827 bool numeric::is_zero(void) const
828 {
829     return ::zerop(*value);  // -> CLN
830 }
831
832 /** True if object is not complex and greater than zero. */
833 bool numeric::is_positive(void) const
834 {
835     if (this->is_real())
836         return ::plusp(The(cl_R)(*value));  // -> CLN
837     return false;
838 }
839
840 /** True if object is not complex and less than zero. */
841 bool numeric::is_negative(void) const
842 {
843     if (this->is_real())
844         return ::minusp(The(cl_R)(*value));  // -> CLN
845     return false;
846 }
847
848 /** True if object is a non-complex integer. */
849 bool numeric::is_integer(void) const
850 {
851     return ::instanceof(*value, cl_I_ring);  // -> CLN
852 }
853
854 /** True if object is an exact integer greater than zero. */
855 bool numeric::is_pos_integer(void) const
856 {
857     return (this->is_integer() && ::plusp(The(cl_I)(*value)));  // -> CLN
858 }
859
860 /** True if object is an exact integer greater or equal zero. */
861 bool numeric::is_nonneg_integer(void) const
862 {
863     return (this->is_integer() && !::minusp(The(cl_I)(*value)));  // -> CLN
864 }
865
866 /** True if object is an exact even integer. */
867 bool numeric::is_even(void) const
868 {
869     return (this->is_integer() && ::evenp(The(cl_I)(*value)));  // -> CLN
870 }
871
872 /** True if object is an exact odd integer. */
873 bool numeric::is_odd(void) const
874 {
875     return (this->is_integer() && ::oddp(The(cl_I)(*value)));  // -> CLN
876 }
877
878 /** Probabilistic primality test.
879  *
880  *  @return  true if object is exact integer and prime. */
881 bool numeric::is_prime(void) const
882 {
883     return (this->is_integer() && ::isprobprime(The(cl_I)(*value)));  // -> CLN
884 }
885
886 /** True if object is an exact rational number, may even be complex
887  *  (denominator may be unity). */
888 bool numeric::is_rational(void) const
889 {
890     return ::instanceof(*value, cl_RA_ring);  // -> CLN
891 }
892
893 /** True if object is a real integer, rational or float (but not complex). */
894 bool numeric::is_real(void) const
895 {
896     return ::instanceof(*value, cl_R_ring);  // -> CLN
897 }
898
899 bool numeric::operator==(const numeric & other) const
900 {
901     return (*value == *other.value);  // -> CLN
902 }
903
904 bool numeric::operator!=(const numeric & other) const
905 {
906     return (*value != *other.value);  // -> CLN
907 }
908
909 /** True if object is element of the domain of integers extended by I, i.e. is
910  *  of the form a+b*I, where a and b are integers. */
911 bool numeric::is_cinteger(void) const
912 {
913     if (::instanceof(*value, cl_I_ring))
914         return true;
915     else if (!this->is_real()) {  // complex case, handle n+m*I
916         if (::instanceof(::realpart(*value), cl_I_ring) &&
917             ::instanceof(::imagpart(*value), cl_I_ring))
918             return true;
919     }
920     return false;
921 }
922
923 /** True if object is an exact rational number, may even be complex
924  *  (denominator may be unity). */
925 bool numeric::is_crational(void) const
926 {
927     if (::instanceof(*value, cl_RA_ring))
928         return true;
929     else if (!this->is_real()) {  // complex case, handle Q(i):
930         if (::instanceof(::realpart(*value), cl_RA_ring) &&
931             ::instanceof(::imagpart(*value), cl_RA_ring))
932             return true;
933     }
934     return false;
935 }
936
937 /** Numerical comparison: less.
938  *
939  *  @exception invalid_argument (complex inequality) */ 
940 bool numeric::operator<(const numeric & other) const
941 {
942     if (this->is_real() && other.is_real())
943         return (The(cl_R)(*value) < The(cl_R)(*other.value));  // -> CLN
944     throw (std::invalid_argument("numeric::operator<(): complex inequality"));
945     return false;  // make compiler shut up
946 }
947
948 /** Numerical comparison: less or equal.
949  *
950  *  @exception invalid_argument (complex inequality) */ 
951 bool numeric::operator<=(const numeric & other) const
952 {
953     if (this->is_real() && other.is_real())
954         return (The(cl_R)(*value) <= The(cl_R)(*other.value));  // -> CLN
955     throw (std::invalid_argument("numeric::operator<=(): complex inequality"));
956     return false;  // make compiler shut up
957 }
958
959 /** Numerical comparison: greater.
960  *
961  *  @exception invalid_argument (complex inequality) */ 
962 bool numeric::operator>(const numeric & other) const
963 {
964     if (this->is_real() && other.is_real())
965         return (The(cl_R)(*value) > The(cl_R)(*other.value));  // -> CLN
966     throw (std::invalid_argument("numeric::operator>(): complex inequality"));
967     return false;  // make compiler shut up
968 }
969
970 /** Numerical comparison: greater or equal.
971  *
972  *  @exception invalid_argument (complex inequality) */  
973 bool numeric::operator>=(const numeric & other) const
974 {
975     if (this->is_real() && other.is_real())
976         return (The(cl_R)(*value) >= The(cl_R)(*other.value));  // -> CLN
977     throw (std::invalid_argument("numeric::operator>=(): complex inequality"));
978     return false;  // make compiler shut up
979 }
980
981 /** Converts numeric types to machine's int.  You should check with
982  *  is_integer() if the number is really an integer before calling this method.
983  *  You may also consider checking the range first. */
984 int numeric::to_int(void) const
985 {
986     GINAC_ASSERT(this->is_integer());
987     return ::cl_I_to_int(The(cl_I)(*value));  // -> CLN
988 }
989
990 /** Converts numeric types to machine's long.  You should check with
991  *  is_integer() if the number is really an integer before calling this method.
992  *  You may also consider checking the range first. */
993 long numeric::to_long(void) const
994 {
995     GINAC_ASSERT(this->is_integer());
996     return ::cl_I_to_long(The(cl_I)(*value));  // -> CLN
997 }
998
999 /** Converts numeric types to machine's double. You should check with is_real()
1000  *  if the number is really not complex before calling this method. */
1001 double numeric::to_double(void) const
1002 {
1003     GINAC_ASSERT(this->is_real());
1004     return ::cl_double_approx(::realpart(*value));  // -> CLN
1005 }
1006
1007 /** Real part of a number. */
1008 numeric numeric::real(void) const
1009 {
1010     return numeric(::realpart(*value));  // -> CLN
1011 }
1012
1013 /** Imaginary part of a number. */
1014 numeric numeric::imag(void) const
1015 {
1016     return numeric(::imagpart(*value));  // -> CLN
1017 }
1018
1019 #ifndef SANE_LINKER
1020 // Unfortunately, CLN did not provide an official way to access the numerator
1021 // or denominator of a rational number (cl_RA). Doing some excavations in CLN
1022 // one finds how it works internally in src/rational/cl_RA.h:
1023 struct cl_heap_ratio : cl_heap {
1024     cl_I numerator;
1025     cl_I denominator;
1026 };
1027
1028 inline cl_heap_ratio* TheRatio (const cl_N& obj)
1029 { return (cl_heap_ratio*)(obj.pointer); }
1030 #endif // ndef SANE_LINKER
1031
1032 /** Numerator.  Computes the numerator of rational numbers, rationalized
1033  *  numerator of complex if real and imaginary part are both rational numbers
1034  *  (i.e numer(4/3+5/6*I) == 8+5*I), the number carrying the sign in all other
1035  *  cases. */
1036 numeric numeric::numer(void) const
1037 {
1038     if (this->is_integer()) {
1039         return numeric(*this);
1040     }
1041 #ifdef SANE_LINKER
1042     else if (::instanceof(*value, cl_RA_ring)) {
1043         return numeric(::numerator(The(cl_RA)(*value)));
1044     }
1045     else if (!this->is_real()) {  // complex case, handle Q(i):
1046         cl_R r = ::realpart(*value);
1047         cl_R i = ::imagpart(*value);
1048         if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_I_ring))
1049             return numeric(*this);
1050         if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_RA_ring))
1051             return numeric(::complex(r*::denominator(The(cl_RA)(i)), ::numerator(The(cl_RA)(i))));
1052         if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_I_ring))
1053             return numeric(::complex(::numerator(The(cl_RA)(r)), i*::denominator(The(cl_RA)(r))));
1054         if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_RA_ring)) {
1055             cl_I s = ::lcm(::denominator(The(cl_RA)(r)), ::denominator(The(cl_RA)(i)));
1056             return numeric(::complex(::numerator(The(cl_RA)(r))*(exquo(s,::denominator(The(cl_RA)(r)))),
1057                                    ::numerator(The(cl_RA)(i))*(exquo(s,::denominator(The(cl_RA)(i))))));
1058         }
1059     }
1060 #else
1061     else if (instanceof(*value, cl_RA_ring)) {
1062         return numeric(TheRatio(*value)->numerator);
1063     }
1064     else if (!this->is_real()) {  // complex case, handle Q(i):
1065         cl_R r = ::realpart(*value);
1066         cl_R i = ::imagpart(*value);
1067         if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
1068             return numeric(*this);
1069         if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
1070             return numeric(::complex(r*TheRatio(i)->denominator, TheRatio(i)->numerator));
1071         if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
1072             return numeric(::complex(TheRatio(r)->numerator, i*TheRatio(r)->denominator));
1073         if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) {
1074             cl_I s = ::lcm(TheRatio(r)->denominator, TheRatio(i)->denominator);
1075             return numeric(::complex(TheRatio(r)->numerator*(exquo(s,TheRatio(r)->denominator)),
1076                                    TheRatio(i)->numerator*(exquo(s,TheRatio(i)->denominator))));
1077         }
1078     }
1079 #endif // def SANE_LINKER
1080     // at least one float encountered
1081     return numeric(*this);
1082 }
1083
1084 /** Denominator.  Computes the denominator of rational numbers, common integer
1085  *  denominator of complex if real and imaginary part are both rational numbers
1086  *  (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
1087 numeric numeric::denom(void) const
1088 {
1089     if (this->is_integer()) {
1090         return _num1();
1091     }
1092 #ifdef SANE_LINKER
1093     if (instanceof(*value, cl_RA_ring)) {
1094         return numeric(::denominator(The(cl_RA)(*value)));
1095     }
1096     if (!this->is_real()) {  // complex case, handle Q(i):
1097         cl_R r = ::realpart(*value);
1098         cl_R i = ::imagpart(*value);
1099         if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_I_ring))
1100             return _num1();
1101         if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_RA_ring))
1102             return numeric(::denominator(The(cl_RA)(i)));
1103         if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_I_ring))
1104             return numeric(::denominator(The(cl_RA)(r)));
1105         if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_RA_ring))
1106             return numeric(::lcm(::denominator(The(cl_RA)(r)), ::denominator(The(cl_RA)(i))));
1107     }
1108 #else
1109     if (instanceof(*value, cl_RA_ring)) {
1110         return numeric(TheRatio(*value)->denominator);
1111     }
1112     if (!this->is_real()) {  // complex case, handle Q(i):
1113         cl_R r = ::realpart(*value);
1114         cl_R i = ::imagpart(*value);
1115         if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
1116             return _num1();
1117         if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
1118             return numeric(TheRatio(i)->denominator);
1119         if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
1120             return numeric(TheRatio(r)->denominator);
1121         if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring))
1122             return numeric(::lcm(TheRatio(r)->denominator, TheRatio(i)->denominator));
1123     }
1124 #endif // def SANE_LINKER
1125     // at least one float encountered
1126     return _num1();
1127 }
1128
1129 /** Size in binary notation.  For integers, this is the smallest n >= 0 such
1130  *  that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
1131  *  2^(n-1) <= x < 2^n.
1132  *
1133  *  @return  number of bits (excluding sign) needed to represent that number
1134  *  in two's complement if it is an integer, 0 otherwise. */    
1135 int numeric::int_length(void) const
1136 {
1137     if (this->is_integer())
1138         return ::integer_length(The(cl_I)(*value));  // -> CLN
1139     else
1140         return 0;
1141 }
1142
1143
1144 //////////
1145 // static member variables
1146 //////////
1147
1148 // protected
1149
1150 unsigned numeric::precedence = 30;
1151
1152 //////////
1153 // global constants
1154 //////////
1155
1156 const numeric some_numeric;
1157 const type_info & typeid_numeric=typeid(some_numeric);
1158 /** Imaginary unit.  This is not a constant but a numeric since we are
1159  *  natively handing complex numbers anyways. */
1160 const numeric I = numeric(::complex(cl_I(0),cl_I(1)));
1161
1162
1163 /** Exponential function.
1164  *
1165  *  @return  arbitrary precision numerical exp(x). */
1166 const numeric exp(const numeric & x)
1167 {
1168     return ::exp(*x.value);  // -> CLN
1169 }
1170
1171
1172 /** Natural logarithm.
1173  *
1174  *  @param z complex number
1175  *  @return  arbitrary precision numerical log(x).
1176  *  @exception overflow_error (logarithmic singularity) */
1177 const numeric log(const numeric & z)
1178 {
1179     if (z.is_zero())
1180         throw (std::overflow_error("log(): logarithmic singularity"));
1181     return ::log(*z.value);  // -> CLN
1182 }
1183
1184
1185 /** Numeric sine (trigonometric function).
1186  *
1187  *  @return  arbitrary precision numerical sin(x). */
1188 const numeric sin(const numeric & x)
1189 {
1190     return ::sin(*x.value);  // -> CLN
1191 }
1192
1193
1194 /** Numeric cosine (trigonometric function).
1195  *
1196  *  @return  arbitrary precision numerical cos(x). */
1197 const numeric cos(const numeric & x)
1198 {
1199     return ::cos(*x.value);  // -> CLN
1200 }
1201
1202
1203 /** Numeric tangent (trigonometric function).
1204  *
1205  *  @return  arbitrary precision numerical tan(x). */
1206 const numeric tan(const numeric & x)
1207 {
1208     return ::tan(*x.value);  // -> CLN
1209 }
1210     
1211
1212 /** Numeric inverse sine (trigonometric function).
1213  *
1214  *  @return  arbitrary precision numerical asin(x). */
1215 const numeric asin(const numeric & x)
1216 {
1217     return ::asin(*x.value);  // -> CLN
1218 }
1219
1220
1221 /** Numeric inverse cosine (trigonometric function).
1222  *
1223  *  @return  arbitrary precision numerical acos(x). */
1224 const numeric acos(const numeric & x)
1225 {
1226     return ::acos(*x.value);  // -> CLN
1227 }
1228     
1229
1230 /** Arcustangent.
1231  *
1232  *  @param z complex number
1233  *  @return atan(z)
1234  *  @exception overflow_error (logarithmic singularity) */
1235 const numeric atan(const numeric & x)
1236 {
1237     if (!x.is_real() &&
1238         x.real().is_zero() &&
1239         !abs(x.imag()).is_equal(_num1()))
1240         throw (std::overflow_error("atan(): logarithmic singularity"));
1241     return ::atan(*x.value);  // -> CLN
1242 }
1243
1244
1245 /** Arcustangent.
1246  *
1247  *  @param x real number
1248  *  @param y real number
1249  *  @return atan(y/x) */
1250 const numeric atan(const numeric & y, const numeric & x)
1251 {
1252     if (x.is_real() && y.is_real())
1253         return ::atan(::realpart(*x.value), ::realpart(*y.value));  // -> CLN
1254     else
1255         throw (std::invalid_argument("numeric::atan(): complex argument"));        
1256 }
1257
1258
1259 /** Numeric hyperbolic sine (trigonometric function).
1260  *
1261  *  @return  arbitrary precision numerical sinh(x). */
1262 const numeric sinh(const numeric & x)
1263 {
1264     return ::sinh(*x.value);  // -> CLN
1265 }
1266
1267
1268 /** Numeric hyperbolic cosine (trigonometric function).
1269  *
1270  *  @return  arbitrary precision numerical cosh(x). */
1271 const numeric cosh(const numeric & x)
1272 {
1273     return ::cosh(*x.value);  // -> CLN
1274 }
1275
1276
1277 /** Numeric hyperbolic tangent (trigonometric function).
1278  *
1279  *  @return  arbitrary precision numerical tanh(x). */
1280 const numeric tanh(const numeric & x)
1281 {
1282     return ::tanh(*x.value);  // -> CLN
1283 }
1284     
1285
1286 /** Numeric inverse hyperbolic sine (trigonometric function).
1287  *
1288  *  @return  arbitrary precision numerical asinh(x). */
1289 const numeric asinh(const numeric & x)
1290 {
1291     return ::asinh(*x.value);  // -> CLN
1292 }
1293
1294
1295 /** Numeric inverse hyperbolic cosine (trigonometric function).
1296  *
1297  *  @return  arbitrary precision numerical acosh(x). */
1298 const numeric acosh(const numeric & x)
1299 {
1300     return ::acosh(*x.value);  // -> CLN
1301 }
1302
1303
1304 /** Numeric inverse hyperbolic tangent (trigonometric function).
1305  *
1306  *  @return  arbitrary precision numerical atanh(x). */
1307 const numeric atanh(const numeric & x)
1308 {
1309     return ::atanh(*x.value);  // -> CLN
1310 }
1311
1312
1313 /** Numeric evaluation of Riemann's Zeta function.  Currently works only for
1314  *  integer arguments. */
1315 const numeric zeta(const numeric & x)
1316 {
1317     // A dirty hack to allow for things like zeta(3.0), since CLN currently
1318     // only knows about integer arguments and zeta(3).evalf() automatically
1319     // cascades down to zeta(3.0).evalf().  The trick is to rely on 3.0-3
1320     // being an exact zero for CLN, which can be tested and then we can just
1321     // pass the number casted to an int:
1322     if (x.is_real()) {
1323         int aux = (int)(::cl_double_approx(::realpart(*x.value)));
1324         if (zerop(*x.value-aux))
1325             return ::cl_zeta(aux);  // -> CLN
1326     }
1327     clog << "zeta(" << x
1328          << "): Does anybody know good way to calculate this numerically?"
1329          << endl;
1330     return numeric(0);
1331 }
1332
1333
1334 /** The gamma function.
1335  *  This is only a stub! */
1336 const numeric gamma(const numeric & x)
1337 {
1338     clog << "gamma(" << x
1339          << "): Does anybody know good way to calculate this numerically?"
1340          << endl;
1341     return numeric(0);
1342 }
1343
1344
1345 /** The psi function (aka polygamma function).
1346  *  This is only a stub! */
1347 const numeric psi(const numeric & x)
1348 {
1349     clog << "psi(" << x
1350          << "): Does anybody know good way to calculate this numerically?"
1351          << endl;
1352     return numeric(0);
1353 }
1354
1355
1356 /** The psi functions (aka polygamma functions).
1357  *  This is only a stub! */
1358 const numeric psi(const numeric & n, const numeric & x)
1359 {
1360     clog << "psi(" << n << "," << x
1361          << "): Does anybody know good way to calculate this numerically?"
1362          << endl;
1363     return numeric(0);
1364 }
1365
1366
1367 /** Factorial combinatorial function.
1368  *
1369  *  @param n  integer argument >= 0
1370  *  @exception range_error (argument must be integer >= 0) */
1371 const numeric factorial(const numeric & n)
1372 {
1373     if (!n.is_nonneg_integer())
1374         throw (std::range_error("numeric::factorial(): argument must be integer >= 0"));
1375     return numeric(::factorial(n.to_int()));  // -> CLN
1376 }
1377
1378
1379 /** The double factorial combinatorial function.  (Scarcely used, but still
1380  *  useful in cases, like for exact results of Gamma(n+1/2) for instance.)
1381  *
1382  *  @param n  integer argument >= -1
1383  *  @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == (-1)!! == 1
1384  *  @exception range_error (argument must be integer >= -1) */
1385 const numeric doublefactorial(const numeric & n)
1386 {
1387     if (n == numeric(-1)) {
1388         return _num1();
1389     }
1390     if (!n.is_nonneg_integer()) {
1391         throw (std::range_error("numeric::doublefactorial(): argument must be integer >= -1"));
1392     }
1393     return numeric(::doublefactorial(n.to_int()));  // -> CLN
1394 }
1395
1396
1397 /** The Binomial coefficients.  It computes the binomial coefficients.  For
1398  *  integer n and k and positive n this is the number of ways of choosing k
1399  *  objects from n distinct objects.  If n is negative, the formula
1400  *  binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */
1401 const numeric binomial(const numeric & n, const numeric & k)
1402 {
1403     if (n.is_integer() && k.is_integer()) {
1404         if (n.is_nonneg_integer()) {
1405             if (k.compare(n)!=1 && k.compare(_num0())!=-1)
1406                 return numeric(::binomial(n.to_int(),k.to_int()));  // -> CLN
1407             else
1408                 return _num0();
1409         } else {
1410             return _num_1().power(k)*binomial(k-n-_num1(),k);
1411         }
1412     }
1413     
1414     // should really be gamma(n+1)/(gamma(r+1)/gamma(n-r+1) or a suitable limit
1415     throw (std::range_error("numeric::binomial(): don´t know how to evaluate that."));
1416 }
1417
1418
1419 /** Bernoulli number.  The nth Bernoulli number is the coefficient of x^n/n!
1420  *  in the expansion of the function x/(e^x-1).
1421  *
1422  *  @return the nth Bernoulli number (a rational number).
1423  *  @exception range_error (argument must be integer >= 0) */
1424 const numeric bernoulli(const numeric & nn)
1425 {
1426     if (!nn.is_integer() || nn.is_negative())
1427         throw (std::range_error("numeric::bernoulli(): argument must be integer >= 0"));
1428     if (nn.is_zero())
1429         return _num1();
1430     if (!nn.compare(_num1()))
1431         return numeric(-1,2);
1432     if (nn.is_odd())
1433         return _num0();
1434     // Until somebody has the Blues and comes up with a much better idea and
1435     // codes it (preferably in CLN) we make this a remembering function which
1436     // computes its results using the formula
1437     // B(nn) == - 1/(nn+1) * sum_{k=0}^{nn-1}(binomial(nn+1,k)*B(k))
1438     // whith B(0) == 1.
1439     static vector<numeric> results;
1440     static int highest_result = -1;
1441     int n = nn.sub(_num2()).div(_num2()).to_int();
1442     if (n <= highest_result)
1443         return results[n];
1444     if (results.capacity() < (unsigned)(n+1))
1445         results.reserve(n+1);
1446     
1447     numeric tmp;  // used to store the sum
1448     for (int i=highest_result+1; i<=n; ++i) {
1449         // the first two elements:
1450         tmp = numeric(-2*i-1,2);
1451         // accumulate the remaining elements:
1452         for (int j=0; j<i; ++j)
1453             tmp += binomial(numeric(2*i+3),numeric(j*2+2))*results[j];
1454         // divide by -(nn+1) and store result:
1455         results.push_back(-tmp/numeric(2*i+3));
1456     }
1457     highest_result=n;
1458     return results[n];
1459 }
1460
1461
1462 /** Fibonacci number.  The nth Fibonacci number F(n) is defined by the
1463  *  recurrence formula F(n)==F(n-1)+F(n-2) with F(0)==0 and F(1)==1.
1464  *
1465  *  @param n an integer
1466  *  @return the nth Fibonacci number F(n) (an integer number)
1467  *  @exception range_error (argument must be an integer) */
1468 const numeric fibonacci(const numeric & n)
1469 {
1470     if (!n.is_integer()) {
1471         throw (std::range_error("numeric::fibonacci(): argument must be integer"));
1472     }
1473     // For positive arguments compute the nearest integer to
1474     // ((1+sqrt(5))/2)^n/sqrt(5).  For negative arguments, apply an additional
1475     // sign.  Note that we are falling back to longs, but this should suffice
1476     // for all times.
1477     int sig = 1;
1478     const long nn = ::abs(n.to_double());
1479     if (n.is_negative() && n.is_even())
1480         sig =-1;
1481     
1482     // Need a precision of ((1+sqrt(5))/2)^-n.
1483     cl_float_format_t prec = ::cl_float_format((int)(0.208987641*nn+5));
1484     cl_R sqrt5 = ::sqrt(::cl_float(5,prec));
1485     cl_R phi = (1+sqrt5)/2;
1486     return numeric(::round1(::expt(phi,nn)/sqrt5)*sig);
1487 }
1488
1489
1490 /** Absolute value. */
1491 numeric abs(const numeric & x)
1492 {
1493     return ::abs(*x.value);  // -> CLN
1494 }
1495
1496
1497 /** Modulus (in positive representation).
1498  *  In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1499  *  sign of a or is zero. This is different from Maple's modp, where the sign
1500  *  of b is ignored. It is in agreement with Mathematica's Mod.
1501  *
1502  *  @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1503  *  integer, 0 otherwise. */
1504 numeric mod(const numeric & a, const numeric & b)
1505 {
1506     if (a.is_integer() && b.is_integer())
1507         return ::mod(The(cl_I)(*a.value), The(cl_I)(*b.value));  // -> CLN
1508     else
1509         return _num0();  // Throw?
1510 }
1511
1512
1513 /** Modulus (in symmetric representation).
1514  *  Equivalent to Maple's mods.
1515  *
1516  *  @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1517 numeric smod(const numeric & a, const numeric & b)
1518 {
1519     if (a.is_integer() && b.is_integer()) {
1520         cl_I b2 = The(cl_I)(ceiling1(The(cl_I)(*b.value) / 2)) - 1;
1521         return ::mod(The(cl_I)(*a.value) + b2, The(cl_I)(*b.value)) - b2;
1522     } else
1523         return _num0();  // Throw?
1524 }
1525
1526
1527 /** Numeric integer remainder.
1528  *  Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1529  *  In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1530  *  sign of a or is zero.
1531  *
1532  *  @return remainder of a/b if both are integer, 0 otherwise. */
1533 numeric irem(const numeric & a, const numeric & b)
1534 {
1535     if (a.is_integer() && b.is_integer())
1536         return ::rem(The(cl_I)(*a.value), The(cl_I)(*b.value));  // -> CLN
1537     else
1538         return _num0();  // Throw?
1539 }
1540
1541
1542 /** Numeric integer remainder.
1543  *  Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1544  *  irem(a,b,q) == a - q*b.  In general, mod(a,b) has the sign of b or is zero,
1545  *  and irem(a,b) has the sign of a or is zero.  
1546  *
1547  *  @return remainder of a/b and quotient stored in q if both are integer,
1548  *  0 otherwise. */
1549 numeric irem(const numeric & a, const numeric & b, numeric & q)
1550 {
1551     if (a.is_integer() && b.is_integer()) {  // -> CLN
1552         cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1553         q = rem_quo.quotient;
1554         return rem_quo.remainder;
1555     }
1556     else {
1557         q = _num0();
1558         return _num0();  // Throw?
1559     }
1560 }
1561
1562
1563 /** Numeric integer quotient.
1564  *  Equivalent to Maple's iquo as far as sign conventions are concerned.
1565  *  
1566  *  @return truncated quotient of a/b if both are integer, 0 otherwise. */
1567 numeric iquo(const numeric & a, const numeric & b)
1568 {
1569     if (a.is_integer() && b.is_integer())
1570         return truncate1(The(cl_I)(*a.value), The(cl_I)(*b.value));  // -> CLN
1571     else
1572         return _num0();  // Throw?
1573 }
1574
1575
1576 /** Numeric integer quotient.
1577  *  Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1578  *  r == a - iquo(a,b,r)*b.
1579  *
1580  *  @return truncated quotient of a/b and remainder stored in r if both are
1581  *  integer, 0 otherwise. */
1582 numeric iquo(const numeric & a, const numeric & b, numeric & r)
1583 {
1584     if (a.is_integer() && b.is_integer()) {  // -> CLN
1585         cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1586         r = rem_quo.remainder;
1587         return rem_quo.quotient;
1588     } else {
1589         r = _num0();
1590         return _num0();  // Throw?
1591     }
1592 }
1593
1594
1595 /** Numeric square root.
1596  *  If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4)
1597  *  should return integer 2.
1598  *
1599  *  @param z numeric argument
1600  *  @return square root of z. Branch cut along negative real axis, the negative
1601  *  real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part
1602  *  where imag(z)>0. */
1603 numeric sqrt(const numeric & z)
1604 {
1605     return ::sqrt(*z.value);  // -> CLN
1606 }
1607
1608
1609 /** Integer numeric square root. */
1610 numeric isqrt(const numeric & x)
1611 {
1612     if (x.is_integer()) {
1613         cl_I root;
1614         ::isqrt(The(cl_I)(*x.value), &root);  // -> CLN
1615         return root;
1616     } else
1617         return _num0();  // Throw?
1618 }
1619
1620
1621 /** Greatest Common Divisor.
1622  *   
1623  *  @return  The GCD of two numbers if both are integer, a numerical 1
1624  *  if they are not. */
1625 numeric gcd(const numeric & a, const numeric & b)
1626 {
1627     if (a.is_integer() && b.is_integer())
1628         return ::gcd(The(cl_I)(*a.value), The(cl_I)(*b.value));  // -> CLN
1629     else
1630         return _num1();
1631 }
1632
1633
1634 /** Least Common Multiple.
1635  *   
1636  *  @return  The LCM of two numbers if both are integer, the product of those
1637  *  two numbers if they are not. */
1638 numeric lcm(const numeric & a, const numeric & b)
1639 {
1640     if (a.is_integer() && b.is_integer())
1641         return ::lcm(The(cl_I)(*a.value), The(cl_I)(*b.value));  // -> CLN
1642     else
1643         return *a.value * *b.value;
1644 }
1645
1646
1647 /** Floating point evaluation of Archimedes' constant Pi. */
1648 ex PiEvalf(void)
1649
1650     return numeric(::cl_pi(cl_default_float_format));  // -> CLN
1651 }
1652
1653
1654 /** Floating point evaluation of Euler's constant Gamma. */
1655 ex EulerGammaEvalf(void)
1656
1657     return numeric(::cl_eulerconst(cl_default_float_format));  // -> CLN
1658 }
1659
1660
1661 /** Floating point evaluation of Catalan's constant. */
1662 ex CatalanEvalf(void)
1663 {
1664     return numeric(::cl_catalanconst(cl_default_float_format));  // -> CLN
1665 }
1666
1667
1668 // It initializes to 17 digits, because in CLN cl_float_format(17) turns out to
1669 // be 61 (<64) while cl_float_format(18)=65.  We want to have a cl_LF instead 
1670 // of cl_SF, cl_FF or cl_DF but everything else is basically arbitrary.
1671 _numeric_digits::_numeric_digits()
1672     : digits(17)
1673 {
1674     assert(!too_late);
1675     too_late = true;
1676     cl_default_float_format = ::cl_float_format(17);
1677 }
1678
1679
1680 _numeric_digits& _numeric_digits::operator=(long prec)
1681 {
1682     digits=prec;
1683     cl_default_float_format = ::cl_float_format(prec); 
1684     return *this;
1685 }
1686
1687
1688 _numeric_digits::operator long()
1689 {
1690     return (long)digits;
1691 }
1692
1693
1694 void _numeric_digits::print(ostream & os) const
1695 {
1696     debugmsg("_numeric_digits print", LOGLEVEL_PRINT);
1697     os << digits;
1698 }
1699
1700
1701 ostream& operator<<(ostream& os, const _numeric_digits & e)
1702 {
1703     e.print(os);
1704     return os;
1705 }
1706
1707 //////////
1708 // static member variables
1709 //////////
1710
1711 // private
1712
1713 bool _numeric_digits::too_late = false;
1714
1715
1716 /** Accuracy in decimal digits.  Only object of this type!  Can be set using
1717  *  assignment from C++ unsigned ints and evaluated like any built-in type. */
1718 _numeric_digits Digits;
1719
1720 #ifndef NO_NAMESPACE_GINAC
1721 } // namespace GiNaC
1722 #endif // ndef NO_NAMESPACE_GINAC