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