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