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