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