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