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