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