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