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