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