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. */
10 * GiNaC Copyright (C) 1999-2003 Johannes Gutenberg University Mainz, Germany
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.
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.
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
38 #include "operators.h"
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
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>
64 GINAC_IMPLEMENT_REGISTERED_CLASS(numeric, basic)
67 // default ctor, dtor, copy ctor, assignment operator and helpers
70 /** default ctor. Numerically it initializes to an integer zero. */
71 numeric::numeric() : basic(TINFO_numeric)
74 setflag(status_flags::evaluated | status_flags::expanded);
77 void numeric::copy(const numeric &other)
79 inherited::copy(other);
83 DEFAULT_DESTROY(numeric)
91 numeric::numeric(int i) : basic(TINFO_numeric)
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)))
101 value = cln::cl_I(static_cast<long>(i));
102 setflag(status_flags::evaluated | status_flags::expanded);
106 numeric::numeric(unsigned int i) : basic(TINFO_numeric)
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);
116 value = cln::cl_I(static_cast<unsigned long>(i));
117 setflag(status_flags::evaluated | status_flags::expanded);
121 numeric::numeric(long i) : basic(TINFO_numeric)
123 value = cln::cl_I(i);
124 setflag(status_flags::evaluated | status_flags::expanded);
128 numeric::numeric(unsigned long i) : basic(TINFO_numeric)
130 value = cln::cl_I(i);
131 setflag(status_flags::evaluated | status_flags::expanded);
135 /** Constructor for rational numerics a/b.
137 * @exception overflow_error (division by zero) */
138 numeric::numeric(long numer, long denom) : basic(TINFO_numeric)
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);
147 numeric::numeric(double d) : basic(TINFO_numeric)
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);
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)
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
166 std::string::size_type delim;
168 // make this implementation safe by adding explicit sign
169 if (ss.at(0) != '+' && ss.at(0) != '-' && ss.at(0) != '#')
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");
179 // chop ss into terms from left to right
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) {
192 term.erase(term.find("I"),1);
194 if (term.find("*")!=std::string::npos)
195 term.erase(term.find("*"),1);
196 // correct for trivial +/-I without explicit factor on I:
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>
211 // No exponent marker? Let's add a trivial one.
212 if (term.find("E")==std::string::npos)
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.
220 ctorval = ctorval + cln::complex(cln::cl_I(0),cln::cl_F(term.c_str()));
222 ctorval = ctorval + cln::cl_F(term.c_str());
224 // this is not a floating point number...
226 ctorval = ctorval + cln::complex(cln::cl_I(0),cln::cl_R(term.c_str()));
228 ctorval = ctorval + cln::cl_R(term.c_str());
230 } while (delim != std::string::npos);
232 setflag(status_flags::evaluated | status_flags::expanded);
236 /** Ctor from CLN types. This is for the initiated user or internal use
238 numeric::numeric(const cln::cl_N &z) : basic(TINFO_numeric)
241 setflag(status_flags::evaluated | status_flags::expanded);
248 numeric::numeric(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
250 cln::cl_N ctorval = 0;
252 // Read number as string
254 if (n.find_string("number", str)) {
255 std::istringstream s(str);
256 cln::cl_idecoded_float re, im;
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);
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));
270 default: // Ordinary number
277 setflag(status_flags::evaluated | status_flags::expanded);
280 void numeric::archive(archive_node &n) const
282 inherited::archive(n);
284 // Write number as string
285 std::ostringstream s;
286 if (this->is_crational())
287 s << cln::the<cln::cl_N>(value);
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));
294 s << re.sign << " " << re.mantissa << " " << re.exponent;
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))));
299 s << re.sign << " " << re.mantissa << " " << re.exponent << " ";
300 s << im.sign << " " << im.mantissa << " " << im.exponent;
303 n.add_string("number", s.str());
306 DEFAULT_UNARCHIVE(numeric)
309 // functions overriding virtual functions from base classes
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.
318 * @see numeric::print() */
319 static void print_real_number(const print_context & c, const cln::cl_R & x)
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
331 cln::print_real(c.s, ourflags, cln::abs(cln::numerator(cln::the<cln::cl_RA>(x))));
333 cln::print_real(c.s, ourflags, cln::denominator(cln::the<cln::cl_RA>(x)));
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);
345 /** Helper function to print integer number in C++ source format.
347 * @see numeric::print() */
348 static void print_integer_csrc(const print_context & c, const cln::cl_I & x)
350 // Print small numbers in compact float format, but larger numbers in
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";
356 c.s << cln::double_approx(x);
359 /** Helper function to print real number in C++ source format.
361 * @see numeric::print() */
362 static void print_real_csrc(const print_context & c, const cln::cl_R & x)
364 if (cln::instanceof(x, cln::cl_I_ring)) {
367 print_integer_csrc(c, cln::the<cln::cl_I>(x));
369 } else if (cln::instanceof(x, cln::cl_RA_ring)) {
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) {
376 print_integer_csrc(c, numer);
379 print_integer_csrc(c, -numer);
382 print_integer_csrc(c, denom);
388 c.s << cln::double_approx(x);
392 /** Helper function to print real number in C++ source format using cl_N types.
394 * @see numeric::print() */
395 static void print_real_cl_N(const print_context & c, const cln::cl_R & x)
397 if (cln::instanceof(x, cln::cl_I_ring)) {
400 c.s << "cln::cl_I(\"";
401 print_real_number(c, x);
404 } else if (cln::instanceof(x, cln::cl_RA_ring)) {
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));
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 << "\")";
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.
424 * @see print_real_number() */
425 void numeric::print(const print_context & c, unsigned level) const
427 if (is_a<print_tree>(c)) {
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
434 } else if (is_a<print_csrc_cl_N>(c)) {
437 if (this->is_real()) {
440 print_real_cl_N(c, cln::the<cln::cl_R>(value));
445 c.s << "cln::complex(";
446 print_real_cl_N(c, cln::realpart(cln::the<cln::cl_N>(value)));
448 print_real_cl_N(c, cln::imagpart(cln::the<cln::cl_N>(value)));
452 } else if (is_a<print_csrc>(c)) {
455 std::ios::fmtflags oldflags = c.s.flags();
456 c.s.setf(std::ios::scientific);
457 int oldprec = c.s.precision();
460 if (is_a<print_csrc_double>(c))
461 c.s.precision(std::numeric_limits<double>::digits10 + 1);
463 c.s.precision(std::numeric_limits<float>::digits10 + 1);
465 if (this->is_real()) {
468 print_real_csrc(c, cln::the<cln::cl_R>(value));
473 c.s << "std::complex<";
474 if (is_a<print_csrc_double>(c))
479 print_real_csrc(c, cln::realpart(cln::the<cln::cl_N>(value)));
481 print_real_csrc(c, cln::imagpart(cln::the<cln::cl_N>(value)));
486 c.s.precision(oldprec);
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));
497 if (is_a<print_python_repr>(c))
498 c.s << class_name() << "('";
500 // case 1, real: x or -x
501 if ((precedence() <= level) && (!this->is_nonneg_integer())) {
503 print_real_number(c, r);
506 print_real_number(c, r);
510 // case 2, imaginary: y*I or -y*I
514 if (precedence()<=level)
517 c.s << "-" << imag_sym;
519 print_real_number(c, i);
520 c.s << mul_sym+imag_sym;
522 if (precedence()<=level)
526 // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I
527 if (precedence() <= level)
529 print_real_number(c, r);
534 print_real_number(c, i);
535 c.s << mul_sym+imag_sym;
542 print_real_number(c, i);
543 c.s << mul_sym+imag_sym;
546 if (precedence() <= level)
550 if (is_a<print_python_repr>(c))
555 bool numeric::info(unsigned inf) const
558 case info_flags::numeric:
559 case info_flags::polynomial:
560 case info_flags::rational_function:
562 case info_flags::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:
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:
590 case info_flags::odd:
592 case info_flags::prime:
594 case info_flags::algebraic:
600 int numeric::degree(const ex & s) const
605 int numeric::ldegree(const ex & s) const
610 ex numeric::coeff(const ex & s, int n) const
612 return n==0 ? *this : _ex0;
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
623 if (!is_exactly_a<numeric>(other))
625 const numeric &o = ex_to<numeric>(other);
626 if (this->is_equal(o) || this->is_equal(-o))
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));
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));
642 /** Evaluation of numbers doesn't do anything at all. */
643 ex numeric::eval(int level) const
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.
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.
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
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)));
667 int numeric::compare_same_type(const basic &other) const
669 GINAC_ASSERT(is_exactly_a<numeric>(other));
670 const numeric &o = static_cast<const numeric &>(other);
672 return this->compare(o);
676 bool numeric::is_equal_same_type(const basic &other) const
678 GINAC_ASSERT(is_exactly_a<numeric>(other));
679 const numeric &o = static_cast<const numeric &>(other);
681 return this->is_equal(o);
685 unsigned numeric::calchash(void) const
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)));
698 // new virtual functions which can be overridden by derived classes
704 // non-virtual functions in this class
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
713 // Efficiency shortcut: trap the neutral element by pointer.
716 else if (&other==_num0_p)
719 return numeric(cln::the<cln::cl_N>(value)+cln::the<cln::cl_N>(other.value));
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
727 return numeric(cln::the<cln::cl_N>(value)-cln::the<cln::cl_N>(other.value));
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
735 // Efficiency shortcut: trap the neutral element by pointer.
738 else if (&other==_num1_p)
741 return numeric(cln::the<cln::cl_N>(value)*cln::the<cln::cl_N>(other.value));
745 /** Numerical division method. Divides *this by argument and returns result as
748 * @exception overflow_error (division by zero) */
749 const numeric numeric::div(const numeric &other) const
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));
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
761 // Shortcut for efficiency and numeric stability (as in 1.0 exponent):
762 // trap the neutral exponent.
763 if (&other==_num1_p || cln::equal(cln::the<cln::cl_N>(other.value),cln::the<cln::cl_N>(_num1.value)))
766 if (cln::zerop(cln::the<cln::cl_N>(value))) {
767 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
768 throw std::domain_error("numeric::eval(): pow(0,0) is undefined");
769 else if (cln::zerop(cln::realpart(cln::the<cln::cl_N>(other.value))))
770 throw std::domain_error("numeric::eval(): pow(0,I) is undefined");
771 else if (cln::minusp(cln::realpart(cln::the<cln::cl_N>(other.value))))
772 throw std::overflow_error("numeric::eval(): division by zero");
776 return numeric(cln::expt(cln::the<cln::cl_N>(value),cln::the<cln::cl_N>(other.value)));
781 /** Numerical addition method. Adds argument to *this and returns result as
782 * a numeric object on the heap. Use internally only for direct wrapping into
783 * an ex object, where the result would end up on the heap anyways. */
784 const numeric &numeric::add_dyn(const numeric &other) const
786 // Efficiency shortcut: trap the neutral element by pointer. This hack
787 // is supposed to keep the number of distinct numeric objects low.
790 else if (&other==_num0_p)
793 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)+cln::the<cln::cl_N>(other.value)))->
794 setflag(status_flags::dynallocated));
798 /** Numerical subtraction method. Subtracts argument from *this and returns
799 * result as a numeric object on the heap. Use internally only for direct
800 * wrapping into an ex object, where the result would end up on the heap
802 const numeric &numeric::sub_dyn(const numeric &other) const
804 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)-cln::the<cln::cl_N>(other.value)))->
805 setflag(status_flags::dynallocated));
809 /** Numerical multiplication method. Multiplies *this and argument and returns
810 * result as a numeric object on the heap. Use internally only for direct
811 * wrapping into an ex object, where the result would end up on the heap
813 const numeric &numeric::mul_dyn(const numeric &other) const
815 // Efficiency shortcut: trap the neutral element by pointer.
818 else if (&other==_num1_p)
821 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)*cln::the<cln::cl_N>(other.value)))->
822 setflag(status_flags::dynallocated));
826 /** Numerical division method. Divides *this by argument and returns result as
827 * a numeric object on the heap. Use internally only for direct wrapping
828 * into an ex object, where the result would end up on the heap
831 * @exception overflow_error (division by zero) */
832 const numeric &numeric::div_dyn(const numeric &other) const
834 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
835 throw std::overflow_error("division by zero");
836 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)/cln::the<cln::cl_N>(other.value)))->
837 setflag(status_flags::dynallocated));
841 /** Numerical exponentiation. Raises *this to the power given as argument and
842 * returns result as a numeric object on the heap. Use internally only for
843 * direct wrapping into an ex object, where the result would end up on the
845 const numeric &numeric::power_dyn(const numeric &other) const
847 // Efficiency shortcut: trap the neutral exponent (first try by pointer, then
848 // try harder, since calls to cln::expt() below may return amazing results for
849 // floating point exponent 1.0).
850 if (&other==_num1_p || cln::equal(cln::the<cln::cl_N>(other.value),cln::the<cln::cl_N>(_num1.value)))
853 if (cln::zerop(cln::the<cln::cl_N>(value))) {
854 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
855 throw std::domain_error("numeric::eval(): pow(0,0) is undefined");
856 else if (cln::zerop(cln::realpart(cln::the<cln::cl_N>(other.value))))
857 throw std::domain_error("numeric::eval(): pow(0,I) is undefined");
858 else if (cln::minusp(cln::realpart(cln::the<cln::cl_N>(other.value))))
859 throw std::overflow_error("numeric::eval(): division by zero");
863 return static_cast<const numeric &>((new numeric(cln::expt(cln::the<cln::cl_N>(value),cln::the<cln::cl_N>(other.value))))->
864 setflag(status_flags::dynallocated));
868 const numeric &numeric::operator=(int i)
870 return operator=(numeric(i));
874 const numeric &numeric::operator=(unsigned int i)
876 return operator=(numeric(i));
880 const numeric &numeric::operator=(long i)
882 return operator=(numeric(i));
886 const numeric &numeric::operator=(unsigned long i)
888 return operator=(numeric(i));
892 const numeric &numeric::operator=(double d)
894 return operator=(numeric(d));
898 const numeric &numeric::operator=(const char * s)
900 return operator=(numeric(s));
904 /** Inverse of a number. */
905 const numeric numeric::inverse(void) const
907 if (cln::zerop(cln::the<cln::cl_N>(value)))
908 throw std::overflow_error("numeric::inverse(): division by zero");
909 return numeric(cln::recip(cln::the<cln::cl_N>(value)));
913 /** Return the complex half-plane (left or right) in which the number lies.
914 * csgn(x)==0 for x==0, csgn(x)==1 for Re(x)>0 or Re(x)=0 and Im(x)>0,
915 * csgn(x)==-1 for Re(x)<0 or Re(x)=0 and Im(x)<0.
917 * @see numeric::compare(const numeric &other) */
918 int numeric::csgn(void) const
920 if (cln::zerop(cln::the<cln::cl_N>(value)))
922 cln::cl_R r = cln::realpart(cln::the<cln::cl_N>(value));
923 if (!cln::zerop(r)) {
929 if (cln::plusp(cln::imagpart(cln::the<cln::cl_N>(value))))
937 /** This method establishes a canonical order on all numbers. For complex
938 * numbers this is not possible in a mathematically consistent way but we need
939 * to establish some order and it ought to be fast. So we simply define it
940 * to be compatible with our method csgn.
942 * @return csgn(*this-other)
943 * @see numeric::csgn(void) */
944 int numeric::compare(const numeric &other) const
946 // Comparing two real numbers?
947 if (cln::instanceof(value, cln::cl_R_ring) &&
948 cln::instanceof(other.value, cln::cl_R_ring))
949 // Yes, so just cln::compare them
950 return cln::compare(cln::the<cln::cl_R>(value), cln::the<cln::cl_R>(other.value));
952 // No, first cln::compare real parts...
953 cl_signean real_cmp = cln::compare(cln::realpart(cln::the<cln::cl_N>(value)), cln::realpart(cln::the<cln::cl_N>(other.value)));
956 // ...and then the imaginary parts.
957 return cln::compare(cln::imagpart(cln::the<cln::cl_N>(value)), cln::imagpart(cln::the<cln::cl_N>(other.value)));
962 bool numeric::is_equal(const numeric &other) const
964 return cln::equal(cln::the<cln::cl_N>(value),cln::the<cln::cl_N>(other.value));
968 /** True if object is zero. */
969 bool numeric::is_zero(void) const
971 return cln::zerop(cln::the<cln::cl_N>(value));
975 /** True if object is not complex and greater than zero. */
976 bool numeric::is_positive(void) const
978 if (cln::instanceof(value, cln::cl_R_ring)) // real?
979 return cln::plusp(cln::the<cln::cl_R>(value));
984 /** True if object is not complex and less than zero. */
985 bool numeric::is_negative(void) const
987 if (cln::instanceof(value, cln::cl_R_ring)) // real?
988 return cln::minusp(cln::the<cln::cl_R>(value));
993 /** True if object is a non-complex integer. */
994 bool numeric::is_integer(void) const
996 return cln::instanceof(value, cln::cl_I_ring);
1000 /** True if object is an exact integer greater than zero. */
1001 bool numeric::is_pos_integer(void) const
1003 return (cln::instanceof(value, cln::cl_I_ring) && cln::plusp(cln::the<cln::cl_I>(value)));
1007 /** True if object is an exact integer greater or equal zero. */
1008 bool numeric::is_nonneg_integer(void) const
1010 return (cln::instanceof(value, cln::cl_I_ring) && !cln::minusp(cln::the<cln::cl_I>(value)));
1014 /** True if object is an exact even integer. */
1015 bool numeric::is_even(void) const
1017 return (cln::instanceof(value, cln::cl_I_ring) && cln::evenp(cln::the<cln::cl_I>(value)));
1021 /** True if object is an exact odd integer. */
1022 bool numeric::is_odd(void) const
1024 return (cln::instanceof(value, cln::cl_I_ring) && cln::oddp(cln::the<cln::cl_I>(value)));
1028 /** Probabilistic primality test.
1030 * @return true if object is exact integer and prime. */
1031 bool numeric::is_prime(void) const
1033 return (cln::instanceof(value, cln::cl_I_ring) // integer?
1034 && cln::plusp(cln::the<cln::cl_I>(value)) // positive?
1035 && cln::isprobprime(cln::the<cln::cl_I>(value)));
1039 /** True if object is an exact rational number, may even be complex
1040 * (denominator may be unity). */
1041 bool numeric::is_rational(void) const
1043 return cln::instanceof(value, cln::cl_RA_ring);
1047 /** True if object is a real integer, rational or float (but not complex). */
1048 bool numeric::is_real(void) const
1050 return cln::instanceof(value, cln::cl_R_ring);
1054 bool numeric::operator==(const numeric &other) const
1056 return cln::equal(cln::the<cln::cl_N>(value), cln::the<cln::cl_N>(other.value));
1060 bool numeric::operator!=(const numeric &other) const
1062 return !cln::equal(cln::the<cln::cl_N>(value), cln::the<cln::cl_N>(other.value));
1066 /** True if object is element of the domain of integers extended by I, i.e. is
1067 * of the form a+b*I, where a and b are integers. */
1068 bool numeric::is_cinteger(void) const
1070 if (cln::instanceof(value, cln::cl_I_ring))
1072 else if (!this->is_real()) { // complex case, handle n+m*I
1073 if (cln::instanceof(cln::realpart(cln::the<cln::cl_N>(value)), cln::cl_I_ring) &&
1074 cln::instanceof(cln::imagpart(cln::the<cln::cl_N>(value)), cln::cl_I_ring))
1081 /** True if object is an exact rational number, may even be complex
1082 * (denominator may be unity). */
1083 bool numeric::is_crational(void) const
1085 if (cln::instanceof(value, cln::cl_RA_ring))
1087 else if (!this->is_real()) { // complex case, handle Q(i):
1088 if (cln::instanceof(cln::realpart(cln::the<cln::cl_N>(value)), cln::cl_RA_ring) &&
1089 cln::instanceof(cln::imagpart(cln::the<cln::cl_N>(value)), cln::cl_RA_ring))
1096 /** Numerical comparison: less.
1098 * @exception invalid_argument (complex inequality) */
1099 bool numeric::operator<(const numeric &other) const
1101 if (this->is_real() && other.is_real())
1102 return (cln::the<cln::cl_R>(value) < cln::the<cln::cl_R>(other.value));
1103 throw std::invalid_argument("numeric::operator<(): complex inequality");
1107 /** Numerical comparison: less or equal.
1109 * @exception invalid_argument (complex inequality) */
1110 bool numeric::operator<=(const numeric &other) const
1112 if (this->is_real() && other.is_real())
1113 return (cln::the<cln::cl_R>(value) <= cln::the<cln::cl_R>(other.value));
1114 throw std::invalid_argument("numeric::operator<=(): complex inequality");
1118 /** Numerical comparison: greater.
1120 * @exception invalid_argument (complex inequality) */
1121 bool numeric::operator>(const numeric &other) const
1123 if (this->is_real() && other.is_real())
1124 return (cln::the<cln::cl_R>(value) > cln::the<cln::cl_R>(other.value));
1125 throw std::invalid_argument("numeric::operator>(): complex inequality");
1129 /** Numerical comparison: greater or equal.
1131 * @exception invalid_argument (complex inequality) */
1132 bool numeric::operator>=(const numeric &other) const
1134 if (this->is_real() && other.is_real())
1135 return (cln::the<cln::cl_R>(value) >= cln::the<cln::cl_R>(other.value));
1136 throw std::invalid_argument("numeric::operator>=(): complex inequality");
1140 /** Converts numeric types to machine's int. You should check with
1141 * is_integer() if the number is really an integer before calling this method.
1142 * You may also consider checking the range first. */
1143 int numeric::to_int(void) const
1145 GINAC_ASSERT(this->is_integer());
1146 return cln::cl_I_to_int(cln::the<cln::cl_I>(value));
1150 /** Converts numeric types to machine's long. You should check with
1151 * is_integer() if the number is really an integer before calling this method.
1152 * You may also consider checking the range first. */
1153 long numeric::to_long(void) const
1155 GINAC_ASSERT(this->is_integer());
1156 return cln::cl_I_to_long(cln::the<cln::cl_I>(value));
1160 /** Converts numeric types to machine's double. You should check with is_real()
1161 * if the number is really not complex before calling this method. */
1162 double numeric::to_double(void) const
1164 GINAC_ASSERT(this->is_real());
1165 return cln::double_approx(cln::realpart(cln::the<cln::cl_N>(value)));
1169 /** Returns a new CLN object of type cl_N, representing the value of *this.
1170 * This method may be used when mixing GiNaC and CLN in one project.
1172 cln::cl_N numeric::to_cl_N(void) const
1174 return cln::cl_N(cln::the<cln::cl_N>(value));
1178 /** Real part of a number. */
1179 const numeric numeric::real(void) const
1181 return numeric(cln::realpart(cln::the<cln::cl_N>(value)));
1185 /** Imaginary part of a number. */
1186 const numeric numeric::imag(void) const
1188 return numeric(cln::imagpart(cln::the<cln::cl_N>(value)));
1192 /** Numerator. Computes the numerator of rational numbers, rationalized
1193 * numerator of complex if real and imaginary part are both rational numbers
1194 * (i.e numer(4/3+5/6*I) == 8+5*I), the number carrying the sign in all other
1196 const numeric numeric::numer(void) const
1198 if (cln::instanceof(value, cln::cl_I_ring))
1199 return numeric(*this); // integer case
1201 else if (cln::instanceof(value, cln::cl_RA_ring))
1202 return numeric(cln::numerator(cln::the<cln::cl_RA>(value)));
1204 else if (!this->is_real()) { // complex case, handle Q(i):
1205 const cln::cl_RA r = cln::the<cln::cl_RA>(cln::realpart(cln::the<cln::cl_N>(value)));
1206 const cln::cl_RA i = cln::the<cln::cl_RA>(cln::imagpart(cln::the<cln::cl_N>(value)));
1207 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_I_ring))
1208 return numeric(*this);
1209 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_RA_ring))
1210 return numeric(cln::complex(r*cln::denominator(i), cln::numerator(i)));
1211 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_I_ring))
1212 return numeric(cln::complex(cln::numerator(r), i*cln::denominator(r)));
1213 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_RA_ring)) {
1214 const cln::cl_I s = cln::lcm(cln::denominator(r), cln::denominator(i));
1215 return numeric(cln::complex(cln::numerator(r)*(cln::exquo(s,cln::denominator(r))),
1216 cln::numerator(i)*(cln::exquo(s,cln::denominator(i)))));
1219 // at least one float encountered
1220 return numeric(*this);
1224 /** Denominator. Computes the denominator of rational numbers, common integer
1225 * denominator of complex if real and imaginary part are both rational numbers
1226 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
1227 const numeric numeric::denom(void) const
1229 if (cln::instanceof(value, cln::cl_I_ring))
1230 return _num1; // integer case
1232 if (cln::instanceof(value, cln::cl_RA_ring))
1233 return numeric(cln::denominator(cln::the<cln::cl_RA>(value)));
1235 if (!this->is_real()) { // complex case, handle Q(i):
1236 const cln::cl_RA r = cln::the<cln::cl_RA>(cln::realpart(cln::the<cln::cl_N>(value)));
1237 const cln::cl_RA i = cln::the<cln::cl_RA>(cln::imagpart(cln::the<cln::cl_N>(value)));
1238 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_I_ring))
1240 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_RA_ring))
1241 return numeric(cln::denominator(i));
1242 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_I_ring))
1243 return numeric(cln::denominator(r));
1244 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_RA_ring))
1245 return numeric(cln::lcm(cln::denominator(r), cln::denominator(i)));
1247 // at least one float encountered
1252 /** Size in binary notation. For integers, this is the smallest n >= 0 such
1253 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
1254 * 2^(n-1) <= x < 2^n.
1256 * @return number of bits (excluding sign) needed to represent that number
1257 * in two's complement if it is an integer, 0 otherwise. */
1258 int numeric::int_length(void) const
1260 if (cln::instanceof(value, cln::cl_I_ring))
1261 return cln::integer_length(cln::the<cln::cl_I>(value));
1270 /** Imaginary unit. This is not a constant but a numeric since we are
1271 * natively handing complex numbers anyways, so in each expression containing
1272 * an I it is automatically eval'ed away anyhow. */
1273 const numeric I = numeric(cln::complex(cln::cl_I(0),cln::cl_I(1)));
1276 /** Exponential function.
1278 * @return arbitrary precision numerical exp(x). */
1279 const numeric exp(const numeric &x)
1281 return cln::exp(x.to_cl_N());
1285 /** Natural logarithm.
1287 * @param z complex number
1288 * @return arbitrary precision numerical log(x).
1289 * @exception pole_error("log(): logarithmic pole",0) */
1290 const numeric log(const numeric &z)
1293 throw pole_error("log(): logarithmic pole",0);
1294 return cln::log(z.to_cl_N());
1298 /** Numeric sine (trigonometric function).
1300 * @return arbitrary precision numerical sin(x). */
1301 const numeric sin(const numeric &x)
1303 return cln::sin(x.to_cl_N());
1307 /** Numeric cosine (trigonometric function).
1309 * @return arbitrary precision numerical cos(x). */
1310 const numeric cos(const numeric &x)
1312 return cln::cos(x.to_cl_N());
1316 /** Numeric tangent (trigonometric function).
1318 * @return arbitrary precision numerical tan(x). */
1319 const numeric tan(const numeric &x)
1321 return cln::tan(x.to_cl_N());
1325 /** Numeric inverse sine (trigonometric function).
1327 * @return arbitrary precision numerical asin(x). */
1328 const numeric asin(const numeric &x)
1330 return cln::asin(x.to_cl_N());
1334 /** Numeric inverse cosine (trigonometric function).
1336 * @return arbitrary precision numerical acos(x). */
1337 const numeric acos(const numeric &x)
1339 return cln::acos(x.to_cl_N());
1345 * @param z complex number
1347 * @exception pole_error("atan(): logarithmic pole",0) */
1348 const numeric atan(const numeric &x)
1351 x.real().is_zero() &&
1352 abs(x.imag()).is_equal(_num1))
1353 throw pole_error("atan(): logarithmic pole",0);
1354 return cln::atan(x.to_cl_N());
1360 * @param x real number
1361 * @param y real number
1362 * @return atan(y/x) */
1363 const numeric atan(const numeric &y, const numeric &x)
1365 if (x.is_real() && y.is_real())
1366 return cln::atan(cln::the<cln::cl_R>(x.to_cl_N()),
1367 cln::the<cln::cl_R>(y.to_cl_N()));
1369 throw std::invalid_argument("atan(): complex argument");
1373 /** Numeric hyperbolic sine (trigonometric function).
1375 * @return arbitrary precision numerical sinh(x). */
1376 const numeric sinh(const numeric &x)
1378 return cln::sinh(x.to_cl_N());
1382 /** Numeric hyperbolic cosine (trigonometric function).
1384 * @return arbitrary precision numerical cosh(x). */
1385 const numeric cosh(const numeric &x)
1387 return cln::cosh(x.to_cl_N());
1391 /** Numeric hyperbolic tangent (trigonometric function).
1393 * @return arbitrary precision numerical tanh(x). */
1394 const numeric tanh(const numeric &x)
1396 return cln::tanh(x.to_cl_N());
1400 /** Numeric inverse hyperbolic sine (trigonometric function).
1402 * @return arbitrary precision numerical asinh(x). */
1403 const numeric asinh(const numeric &x)
1405 return cln::asinh(x.to_cl_N());
1409 /** Numeric inverse hyperbolic cosine (trigonometric function).
1411 * @return arbitrary precision numerical acosh(x). */
1412 const numeric acosh(const numeric &x)
1414 return cln::acosh(x.to_cl_N());
1418 /** Numeric inverse hyperbolic tangent (trigonometric function).
1420 * @return arbitrary precision numerical atanh(x). */
1421 const numeric atanh(const numeric &x)
1423 return cln::atanh(x.to_cl_N());
1427 /*static cln::cl_N Li2_series(const ::cl_N &x,
1428 const ::float_format_t &prec)
1430 // Note: argument must be in the unit circle
1431 // This is very inefficient unless we have fast floating point Bernoulli
1432 // numbers implemented!
1433 cln::cl_N c1 = -cln::log(1-x);
1435 // hard-wire the first two Bernoulli numbers
1436 cln::cl_N acc = c1 - cln::square(c1)/4;
1438 cln::cl_F pisq = cln::square(cln::cl_pi(prec)); // pi^2
1439 cln::cl_F piac = cln::cl_float(1, prec); // accumulator: pi^(2*i)
1441 c1 = cln::square(c1);
1445 aug = c2 * (*(bernoulli(numeric(2*i)).clnptr())) / cln::factorial(2*i+1);
1446 // aug = c2 * cln::cl_I(i%2 ? 1 : -1) / cln::cl_I(2*i+1) * cln::cl_zeta(2*i, prec) / piac / (cln::cl_I(1)<<(2*i-1));
1449 } while (acc != acc+aug);
1453 /** Numeric evaluation of Dilogarithm within circle of convergence (unit
1454 * circle) using a power series. */
1455 static cln::cl_N Li2_series(const cln::cl_N &x,
1456 const cln::float_format_t &prec)
1458 // Note: argument must be in the unit circle
1460 cln::cl_N num = cln::complex(cln::cl_float(1, prec), 0);
1465 den = den + i; // 1, 4, 9, 16, ...
1469 } while (acc != acc+aug);
1473 /** Folds Li2's argument inside a small rectangle to enhance convergence. */
1474 static cln::cl_N Li2_projection(const cln::cl_N &x,
1475 const cln::float_format_t &prec)
1477 const cln::cl_R re = cln::realpart(x);
1478 const cln::cl_R im = cln::imagpart(x);
1479 if (re > cln::cl_F(".5"))
1480 // zeta(2) - Li2(1-x) - log(x)*log(1-x)
1482 - Li2_series(1-x, prec)
1483 - cln::log(x)*cln::log(1-x));
1484 if ((re <= 0 && cln::abs(im) > cln::cl_F(".75")) || (re < cln::cl_F("-.5")))
1485 // -log(1-x)^2 / 2 - Li2(x/(x-1))
1486 return(- cln::square(cln::log(1-x))/2
1487 - Li2_series(x/(x-1), prec));
1488 if (re > 0 && cln::abs(im) > cln::cl_LF(".75"))
1489 // Li2(x^2)/2 - Li2(-x)
1490 return(Li2_projection(cln::square(x), prec)/2
1491 - Li2_projection(-x, prec));
1492 return Li2_series(x, prec);
1495 /** Numeric evaluation of Dilogarithm. The domain is the entire complex plane,
1496 * the branch cut lies along the positive real axis, starting at 1 and
1497 * continuous with quadrant IV.
1499 * @return arbitrary precision numerical Li2(x). */
1500 const numeric Li2(const numeric &x)
1505 // what is the desired float format?
1506 // first guess: default format
1507 cln::float_format_t prec = cln::default_float_format;
1508 const cln::cl_N value = x.to_cl_N();
1509 // second guess: the argument's format
1510 if (!x.real().is_rational())
1511 prec = cln::float_format(cln::the<cln::cl_F>(cln::realpart(value)));
1512 else if (!x.imag().is_rational())
1513 prec = cln::float_format(cln::the<cln::cl_F>(cln::imagpart(value)));
1515 if (cln::the<cln::cl_N>(value)==1) // may cause trouble with log(1-x)
1516 return cln::zeta(2, prec);
1518 if (cln::abs(value) > 1)
1519 // -log(-x)^2 / 2 - zeta(2) - Li2(1/x)
1520 return(- cln::square(cln::log(-value))/2
1521 - cln::zeta(2, prec)
1522 - Li2_projection(cln::recip(value), prec));
1524 return Li2_projection(x.to_cl_N(), prec);
1528 /** Numeric evaluation of Riemann's Zeta function. Currently works only for
1529 * integer arguments. */
1530 const numeric zeta(const numeric &x)
1532 // A dirty hack to allow for things like zeta(3.0), since CLN currently
1533 // only knows about integer arguments and zeta(3).evalf() automatically
1534 // cascades down to zeta(3.0).evalf(). The trick is to rely on 3.0-3
1535 // being an exact zero for CLN, which can be tested and then we can just
1536 // pass the number casted to an int:
1538 const int aux = (int)(cln::double_approx(cln::the<cln::cl_R>(x.to_cl_N())));
1539 if (cln::zerop(x.to_cl_N()-aux))
1540 return cln::zeta(aux);
1546 /** The Gamma function.
1547 * This is only a stub! */
1548 const numeric lgamma(const numeric &x)
1552 const numeric tgamma(const numeric &x)
1558 /** The psi function (aka polygamma function).
1559 * This is only a stub! */
1560 const numeric psi(const numeric &x)
1566 /** The psi functions (aka polygamma functions).
1567 * This is only a stub! */
1568 const numeric psi(const numeric &n, const numeric &x)
1574 /** Factorial combinatorial function.
1576 * @param n integer argument >= 0
1577 * @exception range_error (argument must be integer >= 0) */
1578 const numeric factorial(const numeric &n)
1580 if (!n.is_nonneg_integer())
1581 throw std::range_error("numeric::factorial(): argument must be integer >= 0");
1582 return numeric(cln::factorial(n.to_int()));
1586 /** The double factorial combinatorial function. (Scarcely used, but still
1587 * useful in cases, like for exact results of tgamma(n+1/2) for instance.)
1589 * @param n integer argument >= -1
1590 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == (-1)!! == 1
1591 * @exception range_error (argument must be integer >= -1) */
1592 const numeric doublefactorial(const numeric &n)
1594 if (n.is_equal(_num_1))
1597 if (!n.is_nonneg_integer())
1598 throw std::range_error("numeric::doublefactorial(): argument must be integer >= -1");
1600 return numeric(cln::doublefactorial(n.to_int()));
1604 /** The Binomial coefficients. It computes the binomial coefficients. For
1605 * integer n and k and positive n this is the number of ways of choosing k
1606 * objects from n distinct objects. If n is negative, the formula
1607 * binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */
1608 const numeric binomial(const numeric &n, const numeric &k)
1610 if (n.is_integer() && k.is_integer()) {
1611 if (n.is_nonneg_integer()) {
1612 if (k.compare(n)!=1 && k.compare(_num0)!=-1)
1613 return numeric(cln::binomial(n.to_int(),k.to_int()));
1617 return _num_1.power(k)*binomial(k-n-_num1,k);
1621 // should really be gamma(n+1)/gamma(r+1)/gamma(n-r+1) or a suitable limit
1622 throw std::range_error("numeric::binomial(): don´t know how to evaluate that.");
1626 /** Bernoulli number. The nth Bernoulli number is the coefficient of x^n/n!
1627 * in the expansion of the function x/(e^x-1).
1629 * @return the nth Bernoulli number (a rational number).
1630 * @exception range_error (argument must be integer >= 0) */
1631 const numeric bernoulli(const numeric &nn)
1633 if (!nn.is_integer() || nn.is_negative())
1634 throw std::range_error("numeric::bernoulli(): argument must be integer >= 0");
1638 // The Bernoulli numbers are rational numbers that may be computed using
1641 // B_n = - 1/(n+1) * sum_{k=0}^{n-1}(binomial(n+1,k)*B_k)
1643 // with B(0) = 1. Since the n'th Bernoulli number depends on all the
1644 // previous ones, the computation is necessarily very expensive. There are
1645 // several other ways of computing them, a particularly good one being
1649 // for (unsigned i=0; i<n; i++) {
1650 // c = exquo(c*(i-n),(i+2));
1651 // Bern = Bern + c*s/(i+2);
1652 // s = s + expt_pos(cl_I(i+2),n);
1656 // But if somebody works with the n'th Bernoulli number she is likely to
1657 // also need all previous Bernoulli numbers. So we need a complete remember
1658 // table and above divide and conquer algorithm is not suited to build one
1659 // up. The formula below accomplishes this. It is a modification of the
1660 // defining formula above but the computation of the binomial coefficients
1661 // is carried along in an inline fashion. It also honors the fact that
1662 // B_n is zero when n is odd and greater than 1.
1664 // (There is an interesting relation with the tangent polynomials described
1665 // in `Concrete Mathematics', which leads to a program a little faster as
1666 // our implementation below, but it requires storing one such polynomial in
1667 // addition to the remember table. This doubles the memory footprint so
1668 // we don't use it.)
1670 const unsigned n = nn.to_int();
1672 // the special cases not covered by the algorithm below
1674 return (n==1) ? _num_1_2 : _num0;
1678 // store nonvanishing Bernoulli numbers here
1679 static std::vector< cln::cl_RA > results;
1680 static unsigned next_r = 0;
1682 // algorithm not applicable to B(2), so just store it
1684 results.push_back(cln::recip(cln::cl_RA(6)));
1688 return results[n/2-1];
1690 results.reserve(n/2);
1691 for (unsigned p=next_r; p<=n; p+=2) {
1692 cln::cl_I c = 1; // seed for binonmial coefficients
1693 cln::cl_RA b = cln::cl_RA(1-p)/2;
1694 const unsigned p3 = p+3;
1695 const unsigned pm = p-2;
1697 // test if intermediate unsigned int can be represented by immediate
1698 // objects by CLN (i.e. < 2^29 for 32 Bit machines, see <cln/object.h>)
1699 if (p < (1UL<<cl_value_len/2)) {
1700 for (i=2, k=1, p_2=p/2; i<=pm; i+=2, ++k, --p_2) {
1701 c = cln::exquo(c * ((p3-i) * p_2), (i-1)*k);
1702 b = b + c*results[k-1];
1705 for (i=2, k=1, p_2=p/2; i<=pm; i+=2, ++k, --p_2) {
1706 c = cln::exquo((c * (p3-i)) * p_2, cln::cl_I(i-1)*k);
1707 b = b + c*results[k-1];
1710 results.push_back(-b/(p+1));
1713 return results[n/2-1];
1717 /** Fibonacci number. The nth Fibonacci number F(n) is defined by the
1718 * recurrence formula F(n)==F(n-1)+F(n-2) with F(0)==0 and F(1)==1.
1720 * @param n an integer
1721 * @return the nth Fibonacci number F(n) (an integer number)
1722 * @exception range_error (argument must be an integer) */
1723 const numeric fibonacci(const numeric &n)
1725 if (!n.is_integer())
1726 throw std::range_error("numeric::fibonacci(): argument must be integer");
1729 // The following addition formula holds:
1731 // F(n+m) = F(m-1)*F(n) + F(m)*F(n+1) for m >= 1, n >= 0.
1733 // (Proof: For fixed m, the LHS and the RHS satisfy the same recurrence
1734 // w.r.t. n, and the initial values (n=0, n=1) agree. Hence all values
1736 // Replace m by m+1:
1737 // F(n+m+1) = F(m)*F(n) + F(m+1)*F(n+1) for m >= 0, n >= 0
1738 // Now put in m = n, to get
1739 // F(2n) = (F(n+1)-F(n))*F(n) + F(n)*F(n+1) = F(n)*(2*F(n+1) - F(n))
1740 // F(2n+1) = F(n)^2 + F(n+1)^2
1742 // F(2n+2) = F(n+1)*(2*F(n) + F(n+1))
1745 if (n.is_negative())
1747 return -fibonacci(-n);
1749 return fibonacci(-n);
1753 cln::cl_I m = cln::the<cln::cl_I>(n.to_cl_N()) >> 1L; // floor(n/2);
1754 for (uintL bit=cln::integer_length(m); bit>0; --bit) {
1755 // Since a squaring is cheaper than a multiplication, better use
1756 // three squarings instead of one multiplication and two squarings.
1757 cln::cl_I u2 = cln::square(u);
1758 cln::cl_I v2 = cln::square(v);
1759 if (cln::logbitp(bit-1, m)) {
1760 v = cln::square(u + v) - u2;
1763 u = v2 - cln::square(v - u);
1768 // Here we don't use the squaring formula because one multiplication
1769 // is cheaper than two squarings.
1770 return u * ((v << 1) - u);
1772 return cln::square(u) + cln::square(v);
1776 /** Absolute value. */
1777 const numeric abs(const numeric& x)
1779 return cln::abs(x.to_cl_N());
1783 /** Modulus (in positive representation).
1784 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1785 * sign of a or is zero. This is different from Maple's modp, where the sign
1786 * of b is ignored. It is in agreement with Mathematica's Mod.
1788 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1789 * integer, 0 otherwise. */
1790 const numeric mod(const numeric &a, const numeric &b)
1792 if (a.is_integer() && b.is_integer())
1793 return cln::mod(cln::the<cln::cl_I>(a.to_cl_N()),
1794 cln::the<cln::cl_I>(b.to_cl_N()));
1800 /** Modulus (in symmetric representation).
1801 * Equivalent to Maple's mods.
1803 * @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1804 const numeric smod(const numeric &a, const numeric &b)
1806 if (a.is_integer() && b.is_integer()) {
1807 const cln::cl_I b2 = cln::ceiling1(cln::the<cln::cl_I>(b.to_cl_N()) >> 1) - 1;
1808 return cln::mod(cln::the<cln::cl_I>(a.to_cl_N()) + b2,
1809 cln::the<cln::cl_I>(b.to_cl_N())) - b2;
1815 /** Numeric integer remainder.
1816 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1817 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1818 * sign of a or is zero.
1820 * @return remainder of a/b if both are integer, 0 otherwise.
1821 * @exception overflow_error (division by zero) if b is zero. */
1822 const numeric irem(const numeric &a, const numeric &b)
1825 throw std::overflow_error("numeric::irem(): division by zero");
1826 if (a.is_integer() && b.is_integer())
1827 return cln::rem(cln::the<cln::cl_I>(a.to_cl_N()),
1828 cln::the<cln::cl_I>(b.to_cl_N()));
1834 /** Numeric integer remainder.
1835 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1836 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1837 * and irem(a,b) has the sign of a or is zero.
1839 * @return remainder of a/b and quotient stored in q if both are integer,
1841 * @exception overflow_error (division by zero) if b is zero. */
1842 const numeric irem(const numeric &a, const numeric &b, numeric &q)
1845 throw std::overflow_error("numeric::irem(): division by zero");
1846 if (a.is_integer() && b.is_integer()) {
1847 const cln::cl_I_div_t rem_quo = cln::truncate2(cln::the<cln::cl_I>(a.to_cl_N()),
1848 cln::the<cln::cl_I>(b.to_cl_N()));
1849 q = rem_quo.quotient;
1850 return rem_quo.remainder;
1858 /** Numeric integer quotient.
1859 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1861 * @return truncated quotient of a/b if both are integer, 0 otherwise.
1862 * @exception overflow_error (division by zero) if b is zero. */
1863 const numeric iquo(const numeric &a, const numeric &b)
1866 throw std::overflow_error("numeric::iquo(): division by zero");
1867 if (a.is_integer() && b.is_integer())
1868 return cln::truncate1(cln::the<cln::cl_I>(a.to_cl_N()),
1869 cln::the<cln::cl_I>(b.to_cl_N()));
1875 /** Numeric integer quotient.
1876 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1877 * r == a - iquo(a,b,r)*b.
1879 * @return truncated quotient of a/b and remainder stored in r if both are
1880 * integer, 0 otherwise.
1881 * @exception overflow_error (division by zero) if b is zero. */
1882 const numeric iquo(const numeric &a, const numeric &b, numeric &r)
1885 throw std::overflow_error("numeric::iquo(): division by zero");
1886 if (a.is_integer() && b.is_integer()) {
1887 const cln::cl_I_div_t rem_quo = cln::truncate2(cln::the<cln::cl_I>(a.to_cl_N()),
1888 cln::the<cln::cl_I>(b.to_cl_N()));
1889 r = rem_quo.remainder;
1890 return rem_quo.quotient;
1898 /** Greatest Common Divisor.
1900 * @return The GCD of two numbers if both are integer, a numerical 1
1901 * if they are not. */
1902 const numeric gcd(const numeric &a, const numeric &b)
1904 if (a.is_integer() && b.is_integer())
1905 return cln::gcd(cln::the<cln::cl_I>(a.to_cl_N()),
1906 cln::the<cln::cl_I>(b.to_cl_N()));
1912 /** Least Common Multiple.
1914 * @return The LCM of two numbers if both are integer, the product of those
1915 * two numbers if they are not. */
1916 const numeric lcm(const numeric &a, const numeric &b)
1918 if (a.is_integer() && b.is_integer())
1919 return cln::lcm(cln::the<cln::cl_I>(a.to_cl_N()),
1920 cln::the<cln::cl_I>(b.to_cl_N()));
1926 /** Numeric square root.
1927 * If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4)
1928 * should return integer 2.
1930 * @param z numeric argument
1931 * @return square root of z. Branch cut along negative real axis, the negative
1932 * real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part
1933 * where imag(z)>0. */
1934 const numeric sqrt(const numeric &z)
1936 return cln::sqrt(z.to_cl_N());
1940 /** Integer numeric square root. */
1941 const numeric isqrt(const numeric &x)
1943 if (x.is_integer()) {
1945 cln::isqrt(cln::the<cln::cl_I>(x.to_cl_N()), &root);
1952 /** Floating point evaluation of Archimedes' constant Pi. */
1955 return numeric(cln::pi(cln::default_float_format));
1959 /** Floating point evaluation of Euler's constant gamma. */
1962 return numeric(cln::eulerconst(cln::default_float_format));
1966 /** Floating point evaluation of Catalan's constant. */
1967 ex CatalanEvalf(void)
1969 return numeric(cln::catalanconst(cln::default_float_format));
1973 /** _numeric_digits default ctor, checking for singleton invariance. */
1974 _numeric_digits::_numeric_digits()
1977 // It initializes to 17 digits, because in CLN float_format(17) turns out
1978 // to be 61 (<64) while float_format(18)=65. The reason is we want to
1979 // have a cl_LF instead of cl_SF, cl_FF or cl_DF.
1981 throw(std::runtime_error("I told you not to do instantiate me!"));
1983 cln::default_float_format = cln::float_format(17);
1987 /** Assign a native long to global Digits object. */
1988 _numeric_digits& _numeric_digits::operator=(long prec)
1991 cln::default_float_format = cln::float_format(prec);
1996 /** Convert global Digits object to native type long. */
1997 _numeric_digits::operator long()
1999 // BTW, this is approx. unsigned(cln::default_float_format*0.301)-1
2000 return (long)digits;
2004 /** Append global Digits object to ostream. */
2005 void _numeric_digits::print(std::ostream &os) const
2011 std::ostream& operator<<(std::ostream &os, const _numeric_digits &e)
2018 // static member variables
2023 bool _numeric_digits::too_late = false;
2026 /** Accuracy in decimal digits. Only object of this type! Can be set using
2027 * assignment from C++ unsigned ints and evaluated like any built-in type. */
2028 _numeric_digits Digits;
2030 } // namespace GiNaC