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