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