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