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