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