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