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