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