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