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