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