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