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