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