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