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