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