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