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