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