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