]> www.ginac.de Git - ginac.git/blob - ginac/numeric.cpp
- added using namespace GiNaC; after each #include<ginac/ginac.h>;
[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 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 <vector>
28 #include <stdexcept>
29
30 #include "numeric.h"
31 #include "ex.h"
32 #include "config.h"
33 #include "debugmsg.h"
34
35 // CLN should not pollute the global namespace, hence we include it here
36 // instead of in some header file where it would propagate to other parts:
37 #ifdef HAVE_CLN_CLN_H
38 #include <CLN/cln.h>
39 #else
40 #include <cln.h>
41 #endif
42
43 namespace GiNaC {
44
45 // linker has no problems finding text symbols for numerator or denominator
46 //#define SANE_LINKER
47
48 //////////
49 // default constructor, destructor, copy constructor assignment
50 // operator and helpers
51 //////////
52
53 // public
54
55 /** default ctor. Numerically it initializes to an integer zero. */
56 numeric::numeric() : basic(TINFO_numeric)
57 {
58     debugmsg("numeric default constructor", LOGLEVEL_CONSTRUCT);
59     value = new cl_N;
60     *value=cl_I(0);
61     calchash();
62     setflag(status_flags::evaluated|
63             status_flags::hash_calculated);
64 }
65
66 numeric::~numeric()
67 {
68     debugmsg("numeric destructor" ,LOGLEVEL_DESTRUCT);
69     destroy(0);
70 }
71
72 numeric::numeric(numeric const & other)
73 {
74     debugmsg("numeric copy constructor", LOGLEVEL_CONSTRUCT);
75     copy(other);
76 }
77
78 numeric const & numeric::operator=(numeric const & other)
79 {
80     debugmsg("numeric operator=", LOGLEVEL_ASSIGNMENT);
81     if (this != &other) {
82         destroy(1);
83         copy(other);
84     }
85     return *this;
86 }
87
88 // protected
89
90 void numeric::copy(numeric const & other)
91 {
92     basic::copy(other);
93     value = new cl_N(*other.value);
94 }
95
96 void numeric::destroy(bool call_parent)
97 {
98     delete value;
99     if (call_parent) basic::destroy(call_parent);
100 }
101
102 //////////
103 // other constructors
104 //////////
105
106 // public
107
108 numeric::numeric(int i) : basic(TINFO_numeric)
109 {
110     debugmsg("numeric constructor from int",LOGLEVEL_CONSTRUCT);
111     // Not the whole int-range is available if we don't cast to long
112     // first. This is due to the behaviour of the cl_I-ctor, which
113     // emphasizes efficiency:
114     value = new cl_I((long) i);
115     calchash();
116     setflag(status_flags::evaluated|
117             status_flags::hash_calculated);
118 }
119
120 numeric::numeric(unsigned int i) : basic(TINFO_numeric)
121 {
122     debugmsg("numeric constructor from uint",LOGLEVEL_CONSTRUCT);
123     // Not the whole uint-range is available if we don't cast to ulong
124     // first. This is due to the behaviour of the cl_I-ctor, which
125     // emphasizes efficiency:
126     value = new cl_I((unsigned long)i);
127     calchash();
128     setflag(status_flags::evaluated|
129             status_flags::hash_calculated);
130 }
131
132 numeric::numeric(long i) : basic(TINFO_numeric)
133 {
134     debugmsg("numeric constructor from long",LOGLEVEL_CONSTRUCT);
135     value = new cl_I(i);
136     calchash();
137     setflag(status_flags::evaluated|
138             status_flags::hash_calculated);
139 }
140
141 numeric::numeric(unsigned long i) : basic(TINFO_numeric)
142 {
143     debugmsg("numeric constructor from ulong",LOGLEVEL_CONSTRUCT);
144     value = new cl_I(i);
145     calchash();
146     setflag(status_flags::evaluated|
147             status_flags::hash_calculated);
148 }
149
150 /** Ctor for rational numerics a/b.
151  *
152  *  @exception overflow_error (division by zero) */
153 numeric::numeric(long numer, long denom) : basic(TINFO_numeric)
154 {
155     debugmsg("numeric constructor from long/long",LOGLEVEL_CONSTRUCT);
156     if (!denom)
157         throw (std::overflow_error("division by zero"));
158     value = new cl_I(numer);
159     *value = *value / cl_I(denom);
160     calchash();
161     setflag(status_flags::evaluated|
162             status_flags::hash_calculated);
163 }
164
165 numeric::numeric(double d) : basic(TINFO_numeric)
166 {
167     debugmsg("numeric constructor from double",LOGLEVEL_CONSTRUCT);
168     // We really want to explicitly use the type cl_LF instead of the
169     // more general cl_F, since that would give us a cl_DF only which
170     // will not be promoted to cl_LF if overflow occurs:
171     value = new cl_N;
172     *value = cl_float(d, cl_default_float_format);
173     calchash();
174     setflag(status_flags::evaluated|
175             status_flags::hash_calculated);
176 }
177
178 numeric::numeric(char const *s) : basic(TINFO_numeric)
179 {   // MISSING: treatment of complex and ints and rationals.
180     debugmsg("numeric constructor from string",LOGLEVEL_CONSTRUCT);
181     if (strchr(s, '.'))
182         value = new cl_LF(s);
183     else
184         value = new cl_I(s);
185     calchash();
186     setflag(status_flags::evaluated|
187             status_flags::hash_calculated);
188 }
189
190 /** Ctor from CLN types.  This is for the initiated user or internal use
191  *  only. */
192 numeric::numeric(cl_N const & z) : basic(TINFO_numeric)
193 {
194     debugmsg("numeric constructor from cl_N", LOGLEVEL_CONSTRUCT);
195     value = new cl_N(z);
196     calchash();
197     setflag(status_flags::evaluated|
198             status_flags::hash_calculated);
199 }
200
201 //////////
202 // functions overriding virtual functions from bases classes
203 //////////
204
205 // public
206
207 basic * numeric::duplicate() const
208 {
209     debugmsg("numeric duplicate", LOGLEVEL_DUPLICATE);
210     return new numeric(*this);
211 }
212
213 // The method printraw doesn't do much, it simply uses CLN's operator<<() for
214 // output, which is ugly but reliable. Examples:
215 // 2+2i 
216 void numeric::printraw(ostream & os) const
217 {
218     debugmsg("numeric printraw", LOGLEVEL_PRINT);
219     os << "numeric(" << *value << ")";
220 }
221
222 // The method print adds to the output so it blends more consistently together
223 // with the other routines and produces something compatible to Maple input.
224 void numeric::print(ostream & os, unsigned upper_precedence) const
225 {
226     debugmsg("numeric print", LOGLEVEL_PRINT);
227     if (is_real()) {  
228         // case 1, real:  x  or  -x
229         if ((precedence<=upper_precedence) && (!is_pos_integer())) {
230             os << "(" << *value << ")";
231         } else {
232             os << *value;
233         }
234     } else {
235         // case 2, imaginary:  y*I  or  -y*I
236         if (realpart(*value) == 0) {
237             if ((precedence<=upper_precedence) && (imagpart(*value) < 0)) {
238                 if (imagpart(*value) == -1) {
239                     os << "(-I)";
240                 } else {
241                     os << "(" << imagpart(*value) << "*I)";
242                 }
243             } else {
244                 if (imagpart(*value) == 1) {
245                     os << "I";
246                 } else {
247                     if (imagpart (*value) == -1) {
248                         os << "-I";
249                     } else {
250                         os << imagpart(*value) << "*I";
251                     }
252                 }
253             }
254         } else {
255             // case 3, complex:  x+y*I  or  x-y*I  or  -x+y*I  or  -x-y*I
256             if (precedence <= upper_precedence) os << "(";
257             os << realpart(*value);
258             if (imagpart(*value) < 0) {
259                 if (imagpart(*value) == -1) {
260                     os << "-I";
261                 } else {
262                     os << imagpart(*value) << "*I";
263                 }
264             } else {
265                 if (imagpart(*value) == 1) {
266                     os << "+I";
267                 } else {
268                     os << "+" << imagpart(*value) << "*I";
269                 }
270             }
271             if (precedence <= upper_precedence) os << ")";
272         }
273     }
274 }
275
276 bool numeric::info(unsigned inf) const
277 {
278     switch (inf) {
279     case info_flags::numeric:
280     case info_flags::polynomial:
281     case info_flags::rational_function:
282         return true;
283     case info_flags::real:
284         return is_real();
285     case info_flags::rational:
286     case info_flags::rational_polynomial:
287         return is_rational();
288     case info_flags::integer:
289     case info_flags::integer_polynomial:
290         return is_integer();
291     case info_flags::positive:
292         return is_positive();
293     case info_flags::negative:
294         return is_negative();
295     case info_flags::nonnegative:
296         return compare(numZERO())>=0;
297     case info_flags::posint:
298         return is_pos_integer();
299     case info_flags::negint:
300         return is_integer() && (compare(numZERO())<0);
301     case info_flags::nonnegint:
302         return is_nonneg_integer();
303     case info_flags::even:
304         return is_even();
305     case info_flags::odd:
306         return is_odd();
307     case info_flags::prime:
308         return is_prime();
309     }
310     return false;
311 }
312
313 /** Cast numeric into a floating-point object.  For example exact numeric(1) is
314  *  returned as a 1.0000000000000000000000 and so on according to how Digits is
315  *  currently set.
316  *
317  *  @param level  ignored, but needed for overriding basic::evalf.
318  *  @return an ex-handle to a numeric. */
319 ex numeric::evalf(int level) const
320 {
321     // level can safely be discarded for numeric objects.
322     return numeric(cl_float(1.0, cl_default_float_format) * (*value));  // -> CLN
323 }
324
325 // protected
326
327 int numeric::compare_same_type(basic const & other) const
328 {
329     ASSERT(is_exactly_of_type(other, numeric));
330     numeric const & o = static_cast<numeric &>(const_cast<basic &>(other));
331
332     if (*value == *o.value) {
333         return 0;
334     }
335
336     return compare(o);    
337 }
338
339 bool numeric::is_equal_same_type(basic const & other) const
340 {
341     ASSERT(is_exactly_of_type(other,numeric));
342     numeric const *o = static_cast<numeric const *>(&other);
343     
344     return is_equal(*o);
345 }
346
347 /*
348 unsigned numeric::calchash(void) const
349 {
350     double d=to_double();
351     int s=d>0 ? 1 : -1;
352     d=fabs(d);
353     if (d>0x07FF0000) {
354         d=0x07FF0000;
355     }
356     return 0x88000000U+s*unsigned(d/0x07FF0000);
357 }
358 */
359
360
361 //////////
362 // new virtual functions which can be overridden by derived classes
363 //////////
364
365 // none
366
367 //////////
368 // non-virtual functions in this class
369 //////////
370
371 // public
372
373 /** Numerical addition method.  Adds argument to *this and returns result as
374  *  a new numeric object. */
375 numeric numeric::add(numeric const & other) const
376 {
377     return numeric((*value)+(*other.value));
378 }
379
380 /** Numerical subtraction method.  Subtracts argument from *this and returns
381  *  result as a new numeric object. */
382 numeric numeric::sub(numeric const & other) const
383 {
384     return numeric((*value)-(*other.value));
385 }
386
387 /** Numerical multiplication method.  Multiplies *this and argument and returns
388  *  result as a new numeric object. */
389 numeric numeric::mul(numeric const & other) const
390 {
391     static const numeric * numONEp=&numONE();
392     if (this==numONEp) {
393         return other;
394     } else if (&other==numONEp) {
395         return *this;
396     }
397     return numeric((*value)*(*other.value));
398 }
399
400 /** Numerical division method.  Divides *this by argument and returns result as
401  *  a new numeric object.
402  *
403  *  @exception overflow_error (division by zero) */
404 numeric numeric::div(numeric const & other) const
405 {
406     if (zerop(*other.value))
407         throw (std::overflow_error("division by zero"));
408     return numeric((*value)/(*other.value));
409 }
410
411 numeric numeric::power(numeric const & other) const
412 {
413     static const numeric * numONEp=&numONE();
414     if (&other==numONEp) {
415         return *this;
416     }
417     if (zerop(*value) && other.is_real() && minusp(realpart(*other.value)))
418         throw (std::overflow_error("division by zero"));
419     return numeric(expt(*value,*other.value));
420 }
421
422 /** Inverse of a number. */
423 numeric numeric::inverse(void) const
424 {
425     return numeric(recip(*value));  // -> CLN
426 }
427
428 numeric const & numeric::add_dyn(numeric const & other) const
429 {
430     return static_cast<numeric const &>((new numeric((*value)+(*other.value)))->
431                                         setflag(status_flags::dynallocated));
432 }
433
434 numeric const & numeric::sub_dyn(numeric const & other) const
435 {
436     return static_cast<numeric const &>((new numeric((*value)-(*other.value)))->
437                                         setflag(status_flags::dynallocated));
438 }
439
440 numeric const & numeric::mul_dyn(numeric const & other) const
441 {
442     static const numeric * numONEp=&numONE();
443     if (this==numONEp) {
444         return other;
445     } else if (&other==numONEp) {
446         return *this;
447     }
448     return static_cast<numeric const &>((new numeric((*value)*(*other.value)))->
449                                         setflag(status_flags::dynallocated));
450 }
451
452 numeric const & numeric::div_dyn(numeric const & other) const
453 {
454     if (zerop(*other.value))
455         throw (std::overflow_error("division by zero"));
456     return static_cast<numeric const &>((new numeric((*value)/(*other.value)))->
457                                         setflag(status_flags::dynallocated));
458 }
459
460 numeric const & numeric::power_dyn(numeric const & other) const
461 {
462     static const numeric * numONEp=&numONE();
463     if (&other==numONEp) {
464         return *this;
465     }
466     // The ifs are only a workaround for a bug in CLN. It gets stuck otherwise:
467     if ( !other.is_integer() &&
468          other.is_rational() &&
469          (*this).is_nonneg_integer() ) {
470         if ( !zerop(*value) ) {
471             return static_cast<numeric const &>((new numeric(exp(*other.value * log(*value))))->
472                                                 setflag(status_flags::dynallocated));
473         } else {
474             if ( !zerop(*other.value) ) {  // 0^(n/m)
475                 return static_cast<numeric const &>((new numeric(0))->
476                                                     setflag(status_flags::dynallocated));
477             } else {                       // raise FPE (0^0 requested)
478                 return static_cast<numeric const &>((new numeric(1/(*other.value)))->
479                                                     setflag(status_flags::dynallocated));
480             }
481         }
482     } else {                               // default -> CLN
483         return static_cast<numeric const &>((new numeric(expt(*value,*other.value)))->
484                                             setflag(status_flags::dynallocated));
485     }
486 }
487
488 numeric const & numeric::operator=(int i)
489 {
490     return operator=(numeric(i));
491 }
492
493 numeric const & numeric::operator=(unsigned int i)
494 {
495     return operator=(numeric(i));
496 }
497
498 numeric const & numeric::operator=(long i)
499 {
500     return operator=(numeric(i));
501 }
502
503 numeric const & numeric::operator=(unsigned long i)
504 {
505     return operator=(numeric(i));
506 }
507
508 numeric const & numeric::operator=(double d)
509 {
510     return operator=(numeric(d));
511 }
512
513 numeric const & numeric::operator=(char const * s)
514 {
515     return operator=(numeric(s));
516 }
517
518 /** This method establishes a canonical order on all numbers.  For complex
519  *  numbers this is not possible in a mathematically consistent way but we need
520  *  to establish some order and it ought to be fast.  So we simply define it
521  *  similar to Maple's csgn. */
522 int numeric::compare(numeric const & other) const
523 {
524     // Comparing two real numbers?
525     if (is_real() && other.is_real())
526         // Yes, just compare them
527         return cl_compare(The(cl_R)(*value), The(cl_R)(*other.value));    
528     else {
529         // No, first compare real parts
530         cl_signean real_cmp = cl_compare(realpart(*value), realpart(*other.value));
531         if (real_cmp)
532             return real_cmp;
533
534         return cl_compare(imagpart(*value), imagpart(*other.value));
535     }
536 }
537
538 bool numeric::is_equal(numeric const & other) const
539 {
540     return (*value == *other.value);
541 }
542
543 /** True if object is zero. */
544 bool numeric::is_zero(void) const
545 {
546     return zerop(*value);  // -> CLN
547 }
548
549 /** True if object is not complex and greater than zero. */
550 bool numeric::is_positive(void) const
551 {
552     if (is_real()) {
553         return plusp(The(cl_R)(*value));  // -> CLN
554     }
555     return false;
556 }
557
558 /** True if object is not complex and less than zero. */
559 bool numeric::is_negative(void) const
560 {
561     if (is_real()) {
562         return minusp(The(cl_R)(*value));  // -> CLN
563     }
564     return false;
565 }
566
567 /** True if object is a non-complex integer. */
568 bool numeric::is_integer(void) const
569 {
570     return (bool)instanceof(*value, cl_I_ring);  // -> CLN
571 }
572
573 /** True if object is an exact integer greater than zero. */
574 bool numeric::is_pos_integer(void) const
575 {
576     return (is_integer() &&
577             plusp(The(cl_I)(*value)));  // -> CLN
578 }
579
580 /** True if object is an exact integer greater or equal zero. */
581 bool numeric::is_nonneg_integer(void) const
582 {
583     return (is_integer() &&
584             !minusp(The(cl_I)(*value)));  // -> CLN
585 }
586
587 /** True if object is an exact even integer. */
588 bool numeric::is_even(void) const
589 {
590     return (is_integer() &&
591             evenp(The(cl_I)(*value)));  // -> CLN
592 }
593
594 /** True if object is an exact odd integer. */
595 bool numeric::is_odd(void) const
596 {
597     return (is_integer() &&
598             oddp(The(cl_I)(*value)));  // -> CLN
599 }
600
601 /** Probabilistic primality test.
602  *
603  *  @return  true if object is exact integer and prime. */
604 bool numeric::is_prime(void) const
605 {
606     return (is_integer() &&
607             isprobprime(The(cl_I)(*value)));  // -> CLN
608 }
609
610 /** True if object is an exact rational number, may even be complex
611  *  (denominator may be unity). */
612 bool numeric::is_rational(void) const
613 {
614     if (instanceof(*value, cl_RA_ring)) {
615         return true;
616     } else if (!is_real()) {  // complex case, handle Q(i):
617         if ( instanceof(realpart(*value), cl_RA_ring) &&
618              instanceof(imagpart(*value), cl_RA_ring) )
619             return true;
620     }
621     return false;
622 }
623
624 /** True if object is a real integer, rational or float (but not complex). */
625 bool numeric::is_real(void) const
626 {
627     return (bool)instanceof(*value, cl_R_ring);  // -> CLN
628 }
629
630 bool numeric::operator==(numeric const & other) const
631 {
632     return (*value == *other.value);  // -> CLN
633 }
634
635 bool numeric::operator!=(numeric const & other) const
636 {
637     return (*value != *other.value);  // -> CLN
638 }
639
640 /** Numerical comparison: less.
641  *
642  *  @exception invalid_argument (complex inequality) */ 
643 bool numeric::operator<(numeric const & other) const
644 {
645     if ( is_real() && other.is_real() ) {
646         return (bool)(The(cl_R)(*value) < The(cl_R)(*other.value));  // -> CLN
647     }
648     throw (std::invalid_argument("numeric::operator<(): complex inequality"));
649     return false;  // make compiler shut up
650 }
651
652 /** Numerical comparison: less or equal.
653  *
654  *  @exception invalid_argument (complex inequality) */ 
655 bool numeric::operator<=(numeric const & other) const
656 {
657     if ( is_real() && other.is_real() ) {
658         return (bool)(The(cl_R)(*value) <= The(cl_R)(*other.value));  // -> CLN
659     }
660     throw (std::invalid_argument("numeric::operator<=(): complex inequality"));
661     return false;  // make compiler shut up
662 }
663
664 /** Numerical comparison: greater.
665  *
666  *  @exception invalid_argument (complex inequality) */ 
667 bool numeric::operator>(numeric const & other) const
668 {
669     if ( is_real() && other.is_real() ) {
670         return (bool)(The(cl_R)(*value) > The(cl_R)(*other.value));  // -> CLN
671     }
672     throw (std::invalid_argument("numeric::operator>(): complex inequality"));
673     return false;  // make compiler shut up
674 }
675
676 /** Numerical comparison: greater or equal.
677  *
678  *  @exception invalid_argument (complex inequality) */  
679 bool numeric::operator>=(numeric const & other) const
680 {
681     if ( is_real() && other.is_real() ) {
682         return (bool)(The(cl_R)(*value) >= The(cl_R)(*other.value));  // -> CLN
683     }
684     throw (std::invalid_argument("numeric::operator>=(): complex inequality"));
685     return false;  // make compiler shut up
686 }
687
688 /** Converts numeric types to machine's int. You should check with is_integer()
689  *  if the number is really an integer before calling this method. */
690 int numeric::to_int(void) const
691 {
692     ASSERT(is_integer());
693     return cl_I_to_int(The(cl_I)(*value));
694 }
695
696 /** Converts numeric types to machine's double. You should check with is_real()
697  *  if the number is really not complex before calling this method. */
698 double numeric::to_double(void) const
699 {
700     ASSERT(is_real());
701     return cl_double_approx(realpart(*value));
702 }
703
704 /** Real part of a number. */
705 numeric numeric::real(void) const
706 {
707     return numeric(realpart(*value));  // -> CLN
708 }
709
710 /** Imaginary part of a number. */
711 numeric numeric::imag(void) const
712 {
713     return numeric(imagpart(*value));  // -> CLN
714 }
715
716 #ifndef SANE_LINKER
717 // Unfortunately, CLN did not provide an official way to access the numerator
718 // or denominator of a rational number (cl_RA). Doing some excavations in CLN
719 // one finds how it works internally in src/rational/cl_RA.h:
720 struct cl_heap_ratio : cl_heap {
721     cl_I numerator;
722     cl_I denominator;
723 };
724
725 inline cl_heap_ratio* TheRatio (const cl_N& obj)
726 { return (cl_heap_ratio*)(obj.pointer); }
727 #endif // ndef SANE_LINKER
728
729 /** Numerator.  Computes the numerator of rational numbers, rationalized
730  *  numerator of complex if real and imaginary part are both rational numbers
731  *  (i.e numer(4/3+5/6*I) == 8+5*I), the number itself in all other cases. */
732 numeric numeric::numer(void) const
733 {
734     if (is_integer()) {
735         return numeric(*this);
736     }
737 #ifdef SANE_LINKER
738     else if (instanceof(*value, cl_RA_ring)) {
739         return numeric(numerator(The(cl_RA)(*value)));
740     }
741     else if (!is_real()) {  // complex case, handle Q(i):
742         cl_R r = realpart(*value);
743         cl_R i = imagpart(*value);
744         if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
745             return numeric(*this);
746         if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
747             return numeric(complex(r*denominator(The(cl_RA)(i)), numerator(The(cl_RA)(i))));
748         if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
749             return numeric(complex(numerator(The(cl_RA)(r)), i*denominator(The(cl_RA)(r))));
750         if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) {
751             cl_I s = lcm(denominator(The(cl_RA)(r)), denominator(The(cl_RA)(i)));
752             return numeric(complex(numerator(The(cl_RA)(r))*(exquo(s,denominator(The(cl_RA)(r)))),
753                                    numerator(The(cl_RA)(i))*(exquo(s,denominator(The(cl_RA)(i))))));
754         }
755     }
756 #else
757     else if (instanceof(*value, cl_RA_ring)) {
758         return numeric(TheRatio(*value)->numerator);
759     }
760     else if (!is_real()) {  // complex case, handle Q(i):
761         cl_R r = realpart(*value);
762         cl_R i = imagpart(*value);
763         if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
764             return numeric(*this);
765         if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
766             return numeric(complex(r*TheRatio(i)->denominator, TheRatio(i)->numerator));
767         if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
768             return numeric(complex(TheRatio(r)->numerator, i*TheRatio(r)->denominator));
769         if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) {
770             cl_I s = lcm(TheRatio(r)->denominator, TheRatio(i)->denominator);
771             return numeric(complex(TheRatio(r)->numerator*(exquo(s,TheRatio(r)->denominator)),
772                                    TheRatio(i)->numerator*(exquo(s,TheRatio(i)->denominator))));
773         }
774     }
775 #endif // def SANE_LINKER
776     // at least one float encountered
777     return numeric(*this);
778 }
779
780 /** Denominator.  Computes the denominator of rational numbers, common integer
781  *  denominator of complex if real and imaginary part are both rational numbers
782  *  (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
783 numeric numeric::denom(void) const
784 {
785     if (is_integer()) {
786         return numONE();
787     }
788 #ifdef SANE_LINKER
789     if (instanceof(*value, cl_RA_ring)) {
790         return numeric(denominator(The(cl_RA)(*value)));
791     }
792     if (!is_real()) {  // complex case, handle Q(i):
793         cl_R r = realpart(*value);
794         cl_R i = imagpart(*value);
795         if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
796             return numONE();
797         if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
798             return numeric(denominator(The(cl_RA)(i)));
799         if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
800             return numeric(denominator(The(cl_RA)(r)));
801         if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring))
802             return numeric(lcm(denominator(The(cl_RA)(r)), denominator(The(cl_RA)(i))));
803     }
804 #else
805     if (instanceof(*value, cl_RA_ring)) {
806         return numeric(TheRatio(*value)->denominator);
807     }
808     if (!is_real()) {  // complex case, handle Q(i):
809         cl_R r = realpart(*value);
810         cl_R i = imagpart(*value);
811         if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
812             return numONE();
813         if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
814             return numeric(TheRatio(i)->denominator);
815         if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
816             return numeric(TheRatio(r)->denominator);
817         if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring))
818             return numeric(lcm(TheRatio(r)->denominator, TheRatio(i)->denominator));
819     }
820 #endif // def SANE_LINKER
821     // at least one float encountered
822     return numONE();
823 }
824
825 /** Size in binary notation.  For integers, this is the smallest n >= 0 such
826  *  that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
827  *  2^(n-1) <= x < 2^n.
828  *
829  *  @return  number of bits (excluding sign) needed to represent that number
830  *  in two's complement if it is an integer, 0 otherwise. */    
831 int numeric::int_length(void) const
832 {
833     if (is_integer()) {
834         return integer_length(The(cl_I)(*value));  // -> CLN
835     } else {
836         return 0;
837     }
838 }
839
840
841 //////////
842 // static member variables
843 //////////
844
845 // protected
846
847 unsigned numeric::precedence = 30;
848
849 //////////
850 // global constants
851 //////////
852
853 const numeric some_numeric;
854 type_info const & typeid_numeric=typeid(some_numeric);
855 /** Imaginary unit.  This is not a constant but a numeric since we are
856  *  natively handing complex numbers anyways. */
857 const numeric I = numeric(complex(cl_I(0),cl_I(1)));
858
859 //////////
860 // global functions
861 //////////
862
863 numeric const & numZERO(void)
864 {
865     const static ex eZERO = ex((new numeric(0))->setflag(status_flags::dynallocated));
866     const static numeric * nZERO = static_cast<const numeric *>(eZERO.bp);
867     return *nZERO;
868 }
869
870 numeric const & numONE(void)
871 {
872     const static ex eONE = ex((new numeric(1))->setflag(status_flags::dynallocated));
873     const static numeric * nONE = static_cast<const numeric *>(eONE.bp);
874     return *nONE;
875 }
876
877 numeric const & numTWO(void)
878 {
879     const static ex eTWO = ex((new numeric(2))->setflag(status_flags::dynallocated));
880     const static numeric * nTWO = static_cast<const numeric *>(eTWO.bp);
881     return *nTWO;
882 }
883
884 numeric const & numTHREE(void)
885 {
886     const static ex eTHREE = ex((new numeric(3))->setflag(status_flags::dynallocated));
887     const static numeric * nTHREE = static_cast<const numeric *>(eTHREE.bp);
888     return *nTHREE;
889 }
890
891 numeric const & numMINUSONE(void)
892 {
893     const static ex eMINUSONE = ex((new numeric(-1))->setflag(status_flags::dynallocated));
894     const static numeric * nMINUSONE = static_cast<const numeric *>(eMINUSONE.bp);
895     return *nMINUSONE;
896 }
897
898 numeric const & numHALF(void)
899 {
900     const static ex eHALF = ex((new numeric(1, 2))->setflag(status_flags::dynallocated));
901     const static numeric * nHALF = static_cast<const numeric *>(eHALF.bp);
902     return *nHALF;
903 }
904
905 /** Exponential function.
906  *
907  *  @return  arbitrary precision numerical exp(x). */
908 numeric exp(numeric const & x)
909 {
910     return ::exp(*x.value);  // -> CLN
911 }
912
913 /** Natural logarithm.
914  *
915  *  @param z complex number
916  *  @return  arbitrary precision numerical log(x).
917  *  @exception overflow_error (logarithmic singularity) */
918 numeric log(numeric const & z)
919 {
920     if (z.is_zero())
921         throw (std::overflow_error("log(): logarithmic singularity"));
922     return ::log(*z.value);  // -> CLN
923 }
924
925 /** Numeric sine (trigonometric function).
926  *
927  *  @return  arbitrary precision numerical sin(x). */
928 numeric sin(numeric const & x)
929 {
930     return ::sin(*x.value);  // -> CLN
931 }
932
933 /** Numeric cosine (trigonometric function).
934  *
935  *  @return  arbitrary precision numerical cos(x). */
936 numeric cos(numeric const & x)
937 {
938     return ::cos(*x.value);  // -> CLN
939 }
940     
941 /** Numeric tangent (trigonometric function).
942  *
943  *  @return  arbitrary precision numerical tan(x). */
944 numeric tan(numeric const & x)
945 {
946     return ::tan(*x.value);  // -> CLN
947 }
948     
949 /** Numeric inverse sine (trigonometric function).
950  *
951  *  @return  arbitrary precision numerical asin(x). */
952 numeric asin(numeric const & x)
953 {
954     return ::asin(*x.value);  // -> CLN
955 }
956     
957 /** Numeric inverse cosine (trigonometric function).
958  *
959  *  @return  arbitrary precision numerical acos(x). */
960 numeric acos(numeric const & x)
961 {
962     return ::acos(*x.value);  // -> CLN
963 }
964     
965 /** Arcustangents.
966  *
967  *  @param z complex number
968  *  @return atan(z)
969  *  @exception overflow_error (logarithmic singularity) */
970 numeric atan(numeric const & x)
971 {
972     if (!x.is_real() &&
973         x.real().is_zero() &&
974         !abs(x.imag()).is_equal(numONE()))
975         throw (std::overflow_error("atan(): logarithmic singularity"));
976     return ::atan(*x.value);  // -> CLN
977 }
978
979 /** Arcustangents.
980  *
981  *  @param x real number
982  *  @param y real number
983  *  @return atan(y/x) */
984 numeric atan(numeric const & y, numeric const & x)
985 {
986     if (x.is_real() && y.is_real())
987         return ::atan(realpart(*x.value), realpart(*y.value));  // -> CLN
988     else
989         throw (std::invalid_argument("numeric::atan(): complex argument"));        
990 }
991
992 /** Numeric hyperbolic sine (trigonometric function).
993  *
994  *  @return  arbitrary precision numerical sinh(x). */
995 numeric sinh(numeric const & x)
996 {
997     return ::sinh(*x.value);  // -> CLN
998 }
999
1000 /** Numeric hyperbolic cosine (trigonometric function).
1001  *
1002  *  @return  arbitrary precision numerical cosh(x). */
1003 numeric cosh(numeric const & x)
1004 {
1005     return ::cosh(*x.value);  // -> CLN
1006 }
1007     
1008 /** Numeric hyperbolic tangent (trigonometric function).
1009  *
1010  *  @return  arbitrary precision numerical tanh(x). */
1011 numeric tanh(numeric const & x)
1012 {
1013     return ::tanh(*x.value);  // -> CLN
1014 }
1015     
1016 /** Numeric inverse hyperbolic sine (trigonometric function).
1017  *
1018  *  @return  arbitrary precision numerical asinh(x). */
1019 numeric asinh(numeric const & x)
1020 {
1021     return ::asinh(*x.value);  // -> CLN
1022 }
1023
1024 /** Numeric inverse hyperbolic cosine (trigonometric function).
1025  *
1026  *  @return  arbitrary precision numerical acosh(x). */
1027 numeric acosh(numeric const & x)
1028 {
1029     return ::acosh(*x.value);  // -> CLN
1030 }
1031
1032 /** Numeric inverse hyperbolic tangent (trigonometric function).
1033  *
1034  *  @return  arbitrary precision numerical atanh(x). */
1035 numeric atanh(numeric const & x)
1036 {
1037     return ::atanh(*x.value);  // -> CLN
1038 }
1039
1040 /** The gamma function.
1041  *  stub stub stub stub stub stub! */
1042 numeric gamma(numeric const & x)
1043 {
1044     clog << "gamma(): Nobody expects the Spanish inquisition" << endl;
1045     return numeric(0);
1046 }
1047
1048 /** Factorial combinatorial function.
1049  *
1050  *  @exception range_error (argument must be integer >= 0) */
1051 numeric factorial(numeric const & nn)
1052 {
1053     if ( !nn.is_nonneg_integer() ) {
1054         throw (std::range_error("numeric::factorial(): argument must be integer >= 0"));
1055     }
1056     
1057     return numeric(::factorial(nn.to_int()));  // -> CLN
1058 }
1059
1060 /** The double factorial combinatorial function.  (Scarcely used, but still
1061  *  useful in cases, like for exact results of Gamma(n+1/2) for instance.)
1062  *
1063  *  @param n  integer argument >= -1
1064  *  @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == 1 == (-1)!!
1065  *  @exception range_error (argument must be integer >= -1) */
1066 numeric doublefactorial(numeric const & nn)
1067 {
1068     // We store the results separately for even and odd arguments.  This has
1069     // the advantage that we don't have to compute any even result at all if
1070     // the function is always called with odd arguments and vice versa.  There
1071     // is no tradeoff involved in this, it is guaranteed to save time as well
1072     // as memory.  (If this is not enough justification consider the Gamma
1073     // function of half integer arguments: it only needs odd doublefactorials.)
1074     static vector<numeric> evenresults;
1075     static int highest_evenresult = -1;
1076     static vector<numeric> oddresults;
1077     static int highest_oddresult = -1;
1078     
1079     if ( nn == numeric(-1) ) {
1080         return numONE();
1081     }
1082     if ( !nn.is_nonneg_integer() ) {
1083         throw (std::range_error("numeric::doublefactorial(): argument must be integer >= -1"));
1084     }
1085     if ( nn.is_even() ) {
1086         int n = nn.div(numTWO()).to_int();
1087         if ( n <= highest_evenresult ) {
1088             return evenresults[n];
1089         }
1090         if ( evenresults.capacity() < (unsigned)(n+1) ) {
1091             evenresults.reserve(n+1);
1092         }
1093         if ( highest_evenresult < 0 ) {
1094             evenresults.push_back(numONE());
1095             highest_evenresult=0;
1096         }
1097         for (int i=highest_evenresult+1; i<=n; i++) {
1098             evenresults.push_back(numeric(evenresults[i-1].mul(numeric(i*2))));
1099         }
1100         highest_evenresult=n;
1101         return evenresults[n];
1102     } else {
1103         int n = nn.sub(numONE()).div(numTWO()).to_int();
1104         if ( n <= highest_oddresult ) {
1105             return oddresults[n];
1106         }
1107         if ( oddresults.capacity() < (unsigned)n ) {
1108             oddresults.reserve(n+1);
1109         }
1110         if ( highest_oddresult < 0 ) {
1111             oddresults.push_back(numONE());
1112             highest_oddresult=0;
1113         }
1114         for (int i=highest_oddresult+1; i<=n; i++) {
1115             oddresults.push_back(numeric(oddresults[i-1].mul(numeric(i*2+1))));
1116         }
1117         highest_oddresult=n;
1118         return oddresults[n];
1119     }
1120 }
1121
1122 /** The Binomial function. It computes the binomial coefficients. If the
1123  *  arguments are both nonnegative integers and 0 <= k <= n, then
1124  *  binomial(n, k) = n!/k!/(n-k)! which is the number of ways of choosing k
1125  *  objects from n distinct objects. If k > n, then binomial(n,k) returns 0. */
1126 numeric binomial(numeric const & n, numeric const & k)
1127 {
1128     if (n.is_nonneg_integer() && k.is_nonneg_integer()) {
1129         return numeric(::binomial(n.to_int(),k.to_int()));  // -> CLN
1130     } else {
1131         // should really be gamma(n+1)/(gamma(r+1)/gamma(n-r+1)
1132         return numeric(0);
1133     }
1134     // return factorial(n).div(factorial(k).mul(factorial(n.sub(k))));
1135 }
1136
1137 /** Absolute value. */
1138 numeric abs(numeric const & x)
1139 {
1140     return ::abs(*x.value);  // -> CLN
1141 }
1142
1143 /** Modulus (in positive representation).
1144  *  In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1145  *  sign of a or is zero. This is different from Maple's modp, where the sign
1146  *  of b is ignored. It is in agreement with Mathematica's Mod.
1147  *
1148  *  @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1149  *  integer, 0 otherwise. */
1150 numeric mod(numeric const & a, numeric const & b)
1151 {
1152     if (a.is_integer() && b.is_integer()) {
1153         return ::mod(The(cl_I)(*a.value), The(cl_I)(*b.value));  // -> CLN
1154     }
1155     else {
1156         return numZERO();  // Throw?
1157     }
1158 }
1159
1160 /** Modulus (in symmetric representation).
1161  *  Equivalent to Maple's mods.
1162  *
1163  *  @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1164 numeric smod(numeric const & a, numeric const & b)
1165 {
1166     if (a.is_integer() && b.is_integer()) {
1167         cl_I b2 = The(cl_I)(ceiling1(The(cl_I)(*b.value) / 2)) - 1;
1168         return ::mod(The(cl_I)(*a.value) + b2, The(cl_I)(*b.value)) - b2;
1169     } else {
1170         return numZERO();  // Throw?
1171     }
1172 }
1173
1174 /** Numeric integer remainder.
1175  *  Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1176  *  In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1177  *  sign of a or is zero.
1178  *
1179  *  @return remainder of a/b if both are integer, 0 otherwise. */
1180 numeric irem(numeric const & a, numeric const & b)
1181 {
1182     if (a.is_integer() && b.is_integer()) {
1183         return ::rem(The(cl_I)(*a.value), The(cl_I)(*b.value));  // -> CLN
1184     }
1185     else {
1186         return numZERO();  // Throw?
1187     }
1188 }
1189
1190 /** Numeric integer remainder.
1191  *  Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1192  *  irem(a,b,q) == a - q*b.  In general, mod(a,b) has the sign of b or is zero,
1193  *  and irem(a,b) has the sign of a or is zero.  
1194  *
1195  *  @return remainder of a/b and quotient stored in q if both are integer,
1196  *  0 otherwise. */
1197 numeric irem(numeric const & a, numeric const & b, numeric & q)
1198 {
1199     if (a.is_integer() && b.is_integer()) {  // -> CLN
1200         cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1201         q = rem_quo.quotient;
1202         return rem_quo.remainder;
1203     }
1204     else {
1205         q = numZERO();
1206         return numZERO();  // Throw?
1207     }
1208 }
1209
1210 /** Numeric integer quotient.
1211  *  Equivalent to Maple's iquo as far as sign conventions are concerned.
1212  *  
1213  *  @return truncated quotient of a/b if both are integer, 0 otherwise. */
1214 numeric iquo(numeric const & a, numeric const & b)
1215 {
1216     if (a.is_integer() && b.is_integer()) {
1217         return truncate1(The(cl_I)(*a.value), The(cl_I)(*b.value));  // -> CLN
1218     } else {
1219         return numZERO();  // Throw?
1220     }
1221 }
1222
1223 /** Numeric integer quotient.
1224  *  Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1225  *  r == a - iquo(a,b,r)*b.
1226  *
1227  *  @return truncated quotient of a/b and remainder stored in r if both are
1228  *  integer, 0 otherwise. */
1229 numeric iquo(numeric const & a, numeric const & b, numeric & r)
1230 {
1231     if (a.is_integer() && b.is_integer()) {  // -> CLN
1232         cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1233         r = rem_quo.remainder;
1234         return rem_quo.quotient;
1235     } else {
1236         r = numZERO();
1237         return numZERO();  // Throw?
1238     }
1239 }
1240
1241 /** Numeric square root.
1242  *  If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4)
1243  *  should return integer 2.
1244  *
1245  *  @param z numeric argument
1246  *  @return square root of z. Branch cut along negative real axis, the negative
1247  *  real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part
1248  *  where imag(z)>0. */
1249 numeric sqrt(numeric const & z)
1250 {
1251     return ::sqrt(*z.value);  // -> CLN
1252 }
1253
1254 /** Integer numeric square root. */
1255 numeric isqrt(numeric const & x)
1256 {
1257         if (x.is_integer()) {
1258                 cl_I root;
1259                 ::isqrt(The(cl_I)(*x.value), &root);    // -> CLN
1260                 return root;
1261         } else
1262                 return numZERO();  // Throw?
1263 }
1264
1265 /** Greatest Common Divisor.
1266  *   
1267  *  @return  The GCD of two numbers if both are integer, a numerical 1
1268  *  if they are not. */
1269 numeric gcd(numeric const & a, numeric const & b)
1270 {
1271     if (a.is_integer() && b.is_integer())
1272         return ::gcd(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1273     else
1274         return numONE();
1275 }
1276
1277 /** Least Common Multiple.
1278  *   
1279  *  @return  The LCM of two numbers if both are integer, the product of those
1280  *  two numbers if they are not. */
1281 numeric lcm(numeric const & a, numeric const & b)
1282 {
1283     if (a.is_integer() && b.is_integer())
1284         return ::lcm(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1285     else
1286         return *a.value * *b.value;
1287 }
1288
1289 ex PiEvalf(void)
1290
1291     return numeric(cl_pi(cl_default_float_format));  // -> CLN
1292 }
1293
1294 ex EulerGammaEvalf(void)
1295
1296     return numeric(cl_eulerconst(cl_default_float_format));  // -> CLN
1297 }
1298
1299 ex CatalanEvalf(void)
1300 {
1301     return numeric(cl_catalanconst(cl_default_float_format));  // -> CLN
1302 }
1303
1304 // It initializes to 17 digits, because in CLN cl_float_format(17) turns out to
1305 // be 61 (<64) while cl_float_format(18)=65.  We want to have a cl_LF instead 
1306 // of cl_SF, cl_FF or cl_DF but everything else is basically arbitrary.
1307 _numeric_digits::_numeric_digits()
1308     : digits(17)
1309 {
1310     assert(!too_late);
1311     too_late = true;
1312     cl_default_float_format = cl_float_format(17); 
1313 }
1314
1315 _numeric_digits& _numeric_digits::operator=(long prec)
1316 {
1317     digits=prec;
1318     cl_default_float_format = cl_float_format(prec); 
1319     return *this;
1320 }
1321
1322 _numeric_digits::operator long()
1323 {
1324     return (long)digits;
1325 }
1326
1327 void _numeric_digits::print(ostream & os) const
1328 {
1329     debugmsg("_numeric_digits print", LOGLEVEL_PRINT);
1330     os << digits;
1331 }
1332
1333 ostream& operator<<(ostream& os, _numeric_digits const & e)
1334 {
1335     e.print(os);
1336     return os;
1337 }
1338
1339 //////////
1340 // static member variables
1341 //////////
1342
1343 // private
1344
1345 bool _numeric_digits::too_late = false;
1346
1347 /** Accuracy in decimal digits.  Only object of this type!  Can be set using
1348  *  assignment from C++ unsigned ints and evaluated like any built-in type. */
1349 _numeric_digits Digits;
1350
1351 } // namespace GiNaC