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