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