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