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