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