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-2005 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
37 #include "operators.h"
42 // CLN should pollute the global namespace as little as possible. Hence, we
43 // include most of it here and include only the part needed for properly
44 // declaring cln::cl_number in numeric.h. This can only be safely done in
45 // namespaced versions of CLN, i.e. version > 1.1.0. Also, we only need a
46 // subset of CLN, so we don't include the complete <cln/cln.h> but only the
48 #include <cln/output.h>
49 #include <cln/integer_io.h>
50 #include <cln/integer_ring.h>
51 #include <cln/rational_io.h>
52 #include <cln/rational_ring.h>
53 #include <cln/lfloat_class.h>
54 #include <cln/lfloat_io.h>
55 #include <cln/real_io.h>
56 #include <cln/real_ring.h>
57 #include <cln/complex_io.h>
58 #include <cln/complex_ring.h>
59 #include <cln/numtheory.h>
63 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(numeric, basic,
64 print_func<print_context>(&numeric::do_print).
65 print_func<print_latex>(&numeric::do_print_latex).
66 print_func<print_csrc>(&numeric::do_print_csrc).
67 print_func<print_csrc_cl_N>(&numeric::do_print_csrc_cl_N).
68 print_func<print_tree>(&numeric::do_print_tree).
69 print_func<print_python_repr>(&numeric::do_print_python_repr))
72 // default constructor
75 /** default ctor. Numerically it initializes to an integer zero. */
76 numeric::numeric() : basic(TINFO_numeric)
79 setflag(status_flags::evaluated | status_flags::expanded);
88 numeric::numeric(int i) : basic(TINFO_numeric)
90 // Not the whole int-range is available if we don't cast to long
91 // first. This is due to the behaviour of the cl_I-ctor, which
92 // emphasizes efficiency. However, if the integer is small enough
93 // we save space and dereferences by using an immediate type.
94 // (C.f. <cln/object.h>)
95 if (i < (1L << (cl_value_len-1)) && i >= -(1L << (cl_value_len-1)))
98 value = cln::cl_I(static_cast<long>(i));
99 setflag(status_flags::evaluated | status_flags::expanded);
103 numeric::numeric(unsigned int i) : basic(TINFO_numeric)
105 // Not the whole uint-range is available if we don't cast to ulong
106 // first. This is due to the behaviour of the cl_I-ctor, which
107 // emphasizes efficiency. However, if the integer is small enough
108 // we save space and dereferences by using an immediate type.
109 // (C.f. <cln/object.h>)
110 if (i < (1U << (cl_value_len-1)))
111 value = cln::cl_I(i);
113 value = cln::cl_I(static_cast<unsigned long>(i));
114 setflag(status_flags::evaluated | status_flags::expanded);
118 numeric::numeric(long i) : basic(TINFO_numeric)
120 value = cln::cl_I(i);
121 setflag(status_flags::evaluated | status_flags::expanded);
125 numeric::numeric(unsigned long i) : basic(TINFO_numeric)
127 value = cln::cl_I(i);
128 setflag(status_flags::evaluated | status_flags::expanded);
132 /** Constructor for rational numerics a/b.
134 * @exception overflow_error (division by zero) */
135 numeric::numeric(long numer, long denom) : basic(TINFO_numeric)
138 throw std::overflow_error("division by zero");
139 value = cln::cl_I(numer) / cln::cl_I(denom);
140 setflag(status_flags::evaluated | status_flags::expanded);
144 numeric::numeric(double d) : basic(TINFO_numeric)
146 // We really want to explicitly use the type cl_LF instead of the
147 // more general cl_F, since that would give us a cl_DF only which
148 // will not be promoted to cl_LF if overflow occurs:
149 value = cln::cl_float(d, cln::default_float_format);
150 setflag(status_flags::evaluated | status_flags::expanded);
154 /** ctor from C-style string. It also accepts complex numbers in GiNaC
155 * notation like "2+5*I". */
156 numeric::numeric(const char *s) : basic(TINFO_numeric)
158 cln::cl_N ctorval = 0;
159 // parse complex numbers (functional but not completely safe, unfortunately
160 // std::string does not understand regexpese):
161 // ss should represent a simple sum like 2+5*I
163 std::string::size_type delim;
165 // make this implementation safe by adding explicit sign
166 if (ss.at(0) != '+' && ss.at(0) != '-' && ss.at(0) != '#')
169 // We use 'E' as exponent marker in the output, but some people insist on
170 // writing 'e' at input, so let's substitute them right at the beginning:
171 while ((delim = ss.find("e"))!=std::string::npos)
172 ss.replace(delim,1,"E");
176 // chop ss into terms from left to right
178 bool imaginary = false;
179 delim = ss.find_first_of(std::string("+-"),1);
180 // Do we have an exponent marker like "31.415E-1"? If so, hop on!
181 if (delim!=std::string::npos && ss.at(delim-1)=='E')
182 delim = ss.find_first_of(std::string("+-"),delim+1);
183 term = ss.substr(0,delim);
184 if (delim!=std::string::npos)
185 ss = ss.substr(delim);
186 // is the term imaginary?
187 if (term.find("I")!=std::string::npos) {
189 term.erase(term.find("I"),1);
191 if (term.find("*")!=std::string::npos)
192 term.erase(term.find("*"),1);
193 // correct for trivial +/-I without explicit factor on I:
198 if (term.find('.')!=std::string::npos || term.find('E')!=std::string::npos) {
199 // CLN's short type cl_SF is not very useful within the GiNaC
200 // framework where we are mainly interested in the arbitrary
201 // precision type cl_LF. Hence we go straight to the construction
202 // of generic floats. In order to create them we have to convert
203 // our own floating point notation used for output and construction
204 // from char * to CLN's generic notation:
205 // 3.14 --> 3.14e0_<Digits>
206 // 31.4E-1 --> 31.4e-1_<Digits>
208 // No exponent marker? Let's add a trivial one.
209 if (term.find("E")==std::string::npos)
212 term = term.replace(term.find("E"),1,"e");
213 // append _<Digits> to term
214 term += "_" + ToString((unsigned)Digits);
215 // construct float using cln::cl_F(const char *) ctor.
217 ctorval = ctorval + cln::complex(cln::cl_I(0),cln::cl_F(term.c_str()));
219 ctorval = ctorval + cln::cl_F(term.c_str());
221 // this is not a floating point number...
223 ctorval = ctorval + cln::complex(cln::cl_I(0),cln::cl_R(term.c_str()));
225 ctorval = ctorval + cln::cl_R(term.c_str());
227 } while (delim != std::string::npos);
229 setflag(status_flags::evaluated | status_flags::expanded);
233 /** Ctor from CLN types. This is for the initiated user or internal use
235 numeric::numeric(const cln::cl_N &z) : basic(TINFO_numeric)
238 setflag(status_flags::evaluated | status_flags::expanded);
246 numeric::numeric(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
248 cln::cl_N ctorval = 0;
250 // Read number as string
252 if (n.find_string("number", str)) {
253 std::istringstream s(str);
254 cln::cl_idecoded_float re, im;
258 case 'R': // Integer-decoded real number
259 s >> re.sign >> re.mantissa >> re.exponent;
260 ctorval = re.sign * re.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), re.exponent);
262 case 'C': // Integer-decoded complex number
263 s >> re.sign >> re.mantissa >> re.exponent;
264 s >> im.sign >> im.mantissa >> im.exponent;
265 ctorval = cln::complex(re.sign * re.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), re.exponent),
266 im.sign * im.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), im.exponent));
268 default: // Ordinary number
275 setflag(status_flags::evaluated | status_flags::expanded);
278 void numeric::archive(archive_node &n) const
280 inherited::archive(n);
282 // Write number as string
283 std::ostringstream s;
284 if (this->is_crational())
287 // Non-rational numbers are written in an integer-decoded format
288 // to preserve the precision
289 if (this->is_real()) {
290 cln::cl_idecoded_float re = cln::integer_decode_float(cln::the<cln::cl_F>(value));
292 s << re.sign << " " << re.mantissa << " " << re.exponent;
294 cln::cl_idecoded_float re = cln::integer_decode_float(cln::the<cln::cl_F>(cln::realpart(cln::the<cln::cl_N>(value))));
295 cln::cl_idecoded_float im = cln::integer_decode_float(cln::the<cln::cl_F>(cln::imagpart(cln::the<cln::cl_N>(value))));
297 s << re.sign << " " << re.mantissa << " " << re.exponent << " ";
298 s << im.sign << " " << im.mantissa << " " << im.exponent;
301 n.add_string("number", s.str());
304 DEFAULT_UNARCHIVE(numeric)
307 // functions overriding virtual functions from base classes
310 /** Helper function to print a real number in a nicer way than is CLN's
311 * default. Instead of printing 42.0L0 this just prints 42.0 to ostream os
312 * and instead of 3.99168L7 it prints 3.99168E7. This is fine in GiNaC as
313 * long as it only uses cl_LF and no other floating point types that we might
314 * want to visibly distinguish from cl_LF.
316 * @see numeric::print() */
317 static void print_real_number(const print_context & c, const cln::cl_R & x)
319 cln::cl_print_flags ourflags;
320 if (cln::instanceof(x, cln::cl_RA_ring)) {
321 // case 1: integer or rational
322 if (cln::instanceof(x, cln::cl_I_ring) ||
323 !is_a<print_latex>(c)) {
324 cln::print_real(c.s, ourflags, x);
325 } else { // rational output in LaTeX context
329 cln::print_real(c.s, ourflags, cln::abs(cln::numerator(cln::the<cln::cl_RA>(x))));
331 cln::print_real(c.s, ourflags, cln::denominator(cln::the<cln::cl_RA>(x)));
336 // make CLN believe this number has default_float_format, so it prints
337 // 'E' as exponent marker instead of 'L':
338 ourflags.default_float_format = cln::float_format(cln::the<cln::cl_F>(x));
339 cln::print_real(c.s, ourflags, x);
343 /** Helper function to print integer number in C++ source format.
345 * @see numeric::print() */
346 static void print_integer_csrc(const print_context & c, const cln::cl_I & x)
348 // Print small numbers in compact float format, but larger numbers in
350 const int max_cln_int = 536870911; // 2^29-1
351 if (x >= cln::cl_I(-max_cln_int) && x <= cln::cl_I(max_cln_int))
352 c.s << cln::cl_I_to_int(x) << ".0";
354 c.s << cln::double_approx(x);
357 /** Helper function to print real number in C++ source format.
359 * @see numeric::print() */
360 static void print_real_csrc(const print_context & c, const cln::cl_R & x)
362 if (cln::instanceof(x, cln::cl_I_ring)) {
365 print_integer_csrc(c, cln::the<cln::cl_I>(x));
367 } else if (cln::instanceof(x, cln::cl_RA_ring)) {
370 const cln::cl_I numer = cln::numerator(cln::the<cln::cl_RA>(x));
371 const cln::cl_I denom = cln::denominator(cln::the<cln::cl_RA>(x));
372 if (cln::plusp(x) > 0) {
374 print_integer_csrc(c, numer);
377 print_integer_csrc(c, -numer);
380 print_integer_csrc(c, denom);
386 c.s << cln::double_approx(x);
390 /** Helper function to print real number in C++ source format using cl_N types.
392 * @see numeric::print() */
393 static void print_real_cl_N(const print_context & c, const cln::cl_R & x)
395 if (cln::instanceof(x, cln::cl_I_ring)) {
398 c.s << "cln::cl_I(\"";
399 print_real_number(c, x);
402 } else if (cln::instanceof(x, cln::cl_RA_ring)) {
405 cln::cl_print_flags ourflags;
406 c.s << "cln::cl_RA(\"";
407 cln::print_rational(c.s, ourflags, cln::the<cln::cl_RA>(x));
413 c.s << "cln::cl_F(\"";
414 print_real_number(c, cln::cl_float(1.0, cln::default_float_format) * x);
415 c.s << "_" << Digits << "\")";
419 void numeric::print_numeric(const print_context & c, const char *par_open, const char *par_close, const char *imag_sym, const char *mul_sym, unsigned level) const
421 const cln::cl_R r = cln::realpart(value);
422 const cln::cl_R i = cln::imagpart(value);
426 // case 1, real: x or -x
427 if ((precedence() <= level) && (!this->is_nonneg_integer())) {
429 print_real_number(c, r);
432 print_real_number(c, r);
438 // case 2, imaginary: y*I or -y*I
442 if (precedence()<=level)
445 c.s << "-" << imag_sym;
447 print_real_number(c, i);
448 c.s << mul_sym << imag_sym;
450 if (precedence()<=level)
456 // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I
457 if (precedence() <= level)
459 print_real_number(c, r);
462 c.s << "-" << imag_sym;
464 print_real_number(c, i);
465 c.s << mul_sym << imag_sym;
469 c.s << "+" << imag_sym;
472 print_real_number(c, i);
473 c.s << mul_sym << imag_sym;
476 if (precedence() <= level)
482 void numeric::do_print(const print_context & c, unsigned level) const
484 print_numeric(c, "(", ")", "I", "*", level);
487 void numeric::do_print_latex(const print_latex & c, unsigned level) const
489 print_numeric(c, "{(", ")}", "i", " ", level);
492 void numeric::do_print_csrc(const print_csrc & c, unsigned level) const
494 std::ios::fmtflags oldflags = c.s.flags();
495 c.s.setf(std::ios::scientific);
496 int oldprec = c.s.precision();
499 if (is_a<print_csrc_double>(c))
500 c.s.precision(std::numeric_limits<double>::digits10 + 1);
502 c.s.precision(std::numeric_limits<float>::digits10 + 1);
504 if (this->is_real()) {
507 print_real_csrc(c, cln::the<cln::cl_R>(value));
512 c.s << "std::complex<";
513 if (is_a<print_csrc_double>(c))
518 print_real_csrc(c, cln::realpart(value));
520 print_real_csrc(c, cln::imagpart(value));
525 c.s.precision(oldprec);
528 void numeric::do_print_csrc_cl_N(const print_csrc_cl_N & c, unsigned level) const
530 if (this->is_real()) {
533 print_real_cl_N(c, cln::the<cln::cl_R>(value));
538 c.s << "cln::complex(";
539 print_real_cl_N(c, cln::realpart(value));
541 print_real_cl_N(c, cln::imagpart(value));
546 void numeric::do_print_tree(const print_tree & c, unsigned level) const
548 c.s << std::string(level, ' ') << value
549 << " (" << class_name() << ")" << " @" << this
550 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
554 void numeric::do_print_python_repr(const print_python_repr & c, unsigned level) const
556 c.s << class_name() << "('";
557 print_numeric(c, "(", ")", "I", "*", level);
561 bool numeric::info(unsigned inf) const
564 case info_flags::numeric:
565 case info_flags::polynomial:
566 case info_flags::rational_function:
568 case info_flags::real:
570 case info_flags::rational:
571 case info_flags::rational_polynomial:
572 return is_rational();
573 case info_flags::crational:
574 case info_flags::crational_polynomial:
575 return is_crational();
576 case info_flags::integer:
577 case info_flags::integer_polynomial:
579 case info_flags::cinteger:
580 case info_flags::cinteger_polynomial:
581 return is_cinteger();
582 case info_flags::positive:
583 return is_positive();
584 case info_flags::negative:
585 return is_negative();
586 case info_flags::nonnegative:
587 return !is_negative();
588 case info_flags::posint:
589 return is_pos_integer();
590 case info_flags::negint:
591 return is_integer() && is_negative();
592 case info_flags::nonnegint:
593 return is_nonneg_integer();
594 case info_flags::even:
596 case info_flags::odd:
598 case info_flags::prime:
600 case info_flags::algebraic:
606 int numeric::degree(const ex & s) const
611 int numeric::ldegree(const ex & s) const
616 ex numeric::coeff(const ex & s, int n) const
618 return n==0 ? *this : _ex0;
621 /** Disassemble real part and imaginary part to scan for the occurrence of a
622 * single number. Also handles the imaginary unit. It ignores the sign on
623 * both this and the argument, which may lead to what might appear as funny
624 * results: (2+I).has(-2) -> true. But this is consistent, since we also
625 * would like to have (-2+I).has(2) -> true and we want to think about the
626 * sign as a multiplicative factor. */
627 bool numeric::has(const ex &other) const
629 if (!is_exactly_a<numeric>(other))
631 const numeric &o = ex_to<numeric>(other);
632 if (this->is_equal(o) || this->is_equal(-o))
634 if (o.imag().is_zero()) // e.g. scan for 3 in -3*I
635 return (this->real().is_equal(o) || this->imag().is_equal(o) ||
636 this->real().is_equal(-o) || this->imag().is_equal(-o));
638 if (o.is_equal(I)) // e.g scan for I in 42*I
639 return !this->is_real();
640 if (o.real().is_zero()) // e.g. scan for 2*I in 2*I+1
641 return (this->real().has(o*I) || this->imag().has(o*I) ||
642 this->real().has(-o*I) || this->imag().has(-o*I));
648 /** Evaluation of numbers doesn't do anything at all. */
649 ex numeric::eval(int level) const
651 // Warning: if this is ever gonna do something, the ex ctors from all kinds
652 // of numbers should be checking for status_flags::evaluated.
657 /** Cast numeric into a floating-point object. For example exact numeric(1) is
658 * returned as a 1.0000000000000000000000 and so on according to how Digits is
659 * currently set. In case the object already was a floating point number the
660 * precision is trimmed to match the currently set default.
662 * @param level ignored, only needed for overriding basic::evalf.
663 * @return an ex-handle to a numeric. */
664 ex numeric::evalf(int level) const
666 // level can safely be discarded for numeric objects.
667 return numeric(cln::cl_float(1.0, cln::default_float_format) * value);
670 ex numeric::conjugate() const
675 return numeric(cln::conjugate(this->value));
680 int numeric::compare_same_type(const basic &other) const
682 GINAC_ASSERT(is_exactly_a<numeric>(other));
683 const numeric &o = static_cast<const numeric &>(other);
685 return this->compare(o);
689 bool numeric::is_equal_same_type(const basic &other) const
691 GINAC_ASSERT(is_exactly_a<numeric>(other));
692 const numeric &o = static_cast<const numeric &>(other);
694 return this->is_equal(o);
698 unsigned numeric::calchash() const
700 // Base computation of hashvalue on CLN's hashcode. Note: That depends
701 // only on the number's value, not its type or precision (i.e. a true
702 // equivalence relation on numbers). As a consequence, 3 and 3.0 share
703 // the same hashvalue. That shouldn't really matter, though.
704 setflag(status_flags::hash_calculated);
705 hashvalue = golden_ratio_hash(cln::equal_hashcode(value));
711 // new virtual functions which can be overridden by derived classes
717 // non-virtual functions in this class
722 /** Numerical addition method. Adds argument to *this and returns result as
723 * a numeric object. */
724 const numeric numeric::add(const numeric &other) const
726 return numeric(value + other.value);
730 /** Numerical subtraction method. Subtracts argument from *this and returns
731 * result as a numeric object. */
732 const numeric numeric::sub(const numeric &other) const
734 return numeric(value - other.value);
738 /** Numerical multiplication method. Multiplies *this and argument and returns
739 * result as a numeric object. */
740 const numeric numeric::mul(const numeric &other) const
742 return numeric(value * other.value);
746 /** Numerical division method. Divides *this by argument and returns result as
749 * @exception overflow_error (division by zero) */
750 const numeric numeric::div(const numeric &other) const
752 if (cln::zerop(other.value))
753 throw std::overflow_error("numeric::div(): division by zero");
754 return numeric(value / other.value);
758 /** Numerical exponentiation. Raises *this to the power given as argument and
759 * returns result as a numeric object. */
760 const numeric numeric::power(const numeric &other) const
762 // Shortcut for efficiency and numeric stability (as in 1.0 exponent):
763 // trap the neutral exponent.
764 if (&other==_num1_p || cln::equal(other.value,_num1_p->value))
767 if (cln::zerop(value)) {
768 if (cln::zerop(other.value))
769 throw std::domain_error("numeric::eval(): pow(0,0) is undefined");
770 else if (cln::zerop(cln::realpart(other.value)))
771 throw std::domain_error("numeric::eval(): pow(0,I) is undefined");
772 else if (cln::minusp(cln::realpart(other.value)))
773 throw std::overflow_error("numeric::eval(): division by zero");
777 return numeric(cln::expt(value, other.value));
782 /** Numerical addition method. Adds argument to *this and returns result as
783 * a numeric object on the heap. Use internally only for direct wrapping into
784 * an ex object, where the result would end up on the heap anyways. */
785 const numeric &numeric::add_dyn(const numeric &other) const
787 // Efficiency shortcut: trap the neutral element by pointer. This hack
788 // is supposed to keep the number of distinct numeric objects low.
791 else if (&other==_num0_p)
794 return static_cast<const numeric &>((new numeric(value + other.value))->
795 setflag(status_flags::dynallocated));
799 /** Numerical subtraction method. Subtracts argument from *this and returns
800 * result as a numeric object on the heap. Use internally only for direct
801 * wrapping into an ex object, where the result would end up on the heap
803 const numeric &numeric::sub_dyn(const numeric &other) const
805 // Efficiency shortcut: trap the neutral exponent (first by pointer). This
806 // hack is supposed to keep the number of distinct numeric objects low.
807 if (&other==_num0_p || cln::zerop(other.value))
810 return static_cast<const numeric &>((new numeric(value - other.value))->
811 setflag(status_flags::dynallocated));
815 /** Numerical multiplication method. Multiplies *this and argument and returns
816 * result as a numeric object on the heap. Use internally only for direct
817 * wrapping into an ex object, where the result would end up on the heap
819 const numeric &numeric::mul_dyn(const numeric &other) const
821 // Efficiency shortcut: trap the neutral element by pointer. This hack
822 // is supposed to keep the number of distinct numeric objects low.
825 else if (&other==_num1_p)
828 return static_cast<const numeric &>((new numeric(value * other.value))->
829 setflag(status_flags::dynallocated));
833 /** Numerical division method. Divides *this by argument and returns result as
834 * a numeric object on the heap. Use internally only for direct wrapping
835 * into an ex object, where the result would end up on the heap
838 * @exception overflow_error (division by zero) */
839 const numeric &numeric::div_dyn(const numeric &other) const
841 // Efficiency shortcut: trap the neutral element by pointer. This hack
842 // is supposed to keep the number of distinct numeric objects low.
845 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
846 throw std::overflow_error("division by zero");
847 return static_cast<const numeric &>((new numeric(value / other.value))->
848 setflag(status_flags::dynallocated));
852 /** Numerical exponentiation. Raises *this to the power given as argument and
853 * returns result as a numeric object on the heap. Use internally only for
854 * direct wrapping into an ex object, where the result would end up on the
856 const numeric &numeric::power_dyn(const numeric &other) const
858 // Efficiency shortcut: trap the neutral exponent (first try by pointer, then
859 // try harder, since calls to cln::expt() below may return amazing results for
860 // floating point exponent 1.0).
861 if (&other==_num1_p || cln::equal(other.value, _num1_p->value))
864 if (cln::zerop(value)) {
865 if (cln::zerop(other.value))
866 throw std::domain_error("numeric::eval(): pow(0,0) is undefined");
867 else if (cln::zerop(cln::realpart(other.value)))
868 throw std::domain_error("numeric::eval(): pow(0,I) is undefined");
869 else if (cln::minusp(cln::realpart(other.value)))
870 throw std::overflow_error("numeric::eval(): division by zero");
874 return static_cast<const numeric &>((new numeric(cln::expt(value, other.value)))->
875 setflag(status_flags::dynallocated));
879 const numeric &numeric::operator=(int i)
881 return operator=(numeric(i));
885 const numeric &numeric::operator=(unsigned int i)
887 return operator=(numeric(i));
891 const numeric &numeric::operator=(long i)
893 return operator=(numeric(i));
897 const numeric &numeric::operator=(unsigned long i)
899 return operator=(numeric(i));
903 const numeric &numeric::operator=(double d)
905 return operator=(numeric(d));
909 const numeric &numeric::operator=(const char * s)
911 return operator=(numeric(s));
915 /** Inverse of a number. */
916 const numeric numeric::inverse() const
918 if (cln::zerop(value))
919 throw std::overflow_error("numeric::inverse(): division by zero");
920 return numeric(cln::recip(value));
924 /** Return the complex half-plane (left or right) in which the number lies.
925 * csgn(x)==0 for x==0, csgn(x)==1 for Re(x)>0 or Re(x)=0 and Im(x)>0,
926 * csgn(x)==-1 for Re(x)<0 or Re(x)=0 and Im(x)<0.
928 * @see numeric::compare(const numeric &other) */
929 int numeric::csgn() const
931 if (cln::zerop(value))
933 cln::cl_R r = cln::realpart(value);
934 if (!cln::zerop(r)) {
940 if (cln::plusp(cln::imagpart(value)))
948 /** This method establishes a canonical order on all numbers. For complex
949 * numbers this is not possible in a mathematically consistent way but we need
950 * to establish some order and it ought to be fast. So we simply define it
951 * to be compatible with our method csgn.
953 * @return csgn(*this-other)
954 * @see numeric::csgn() */
955 int numeric::compare(const numeric &other) const
957 // Comparing two real numbers?
958 if (cln::instanceof(value, cln::cl_R_ring) &&
959 cln::instanceof(other.value, cln::cl_R_ring))
960 // Yes, so just cln::compare them
961 return cln::compare(cln::the<cln::cl_R>(value), cln::the<cln::cl_R>(other.value));
963 // No, first cln::compare real parts...
964 cl_signean real_cmp = cln::compare(cln::realpart(value), cln::realpart(other.value));
967 // ...and then the imaginary parts.
968 return cln::compare(cln::imagpart(value), cln::imagpart(other.value));
973 bool numeric::is_equal(const numeric &other) const
975 return cln::equal(value, other.value);
979 /** True if object is zero. */
980 bool numeric::is_zero() const
982 return cln::zerop(value);
986 /** True if object is not complex and greater than zero. */
987 bool numeric::is_positive() const
989 if (cln::instanceof(value, cln::cl_R_ring)) // real?
990 return cln::plusp(cln::the<cln::cl_R>(value));
995 /** True if object is not complex and less than zero. */
996 bool numeric::is_negative() const
998 if (cln::instanceof(value, cln::cl_R_ring)) // real?
999 return cln::minusp(cln::the<cln::cl_R>(value));
1004 /** True if object is a non-complex integer. */
1005 bool numeric::is_integer() const
1007 return cln::instanceof(value, cln::cl_I_ring);
1011 /** True if object is an exact integer greater than zero. */
1012 bool numeric::is_pos_integer() const
1014 return (cln::instanceof(value, cln::cl_I_ring) && cln::plusp(cln::the<cln::cl_I>(value)));
1018 /** True if object is an exact integer greater or equal zero. */
1019 bool numeric::is_nonneg_integer() const
1021 return (cln::instanceof(value, cln::cl_I_ring) && !cln::minusp(cln::the<cln::cl_I>(value)));
1025 /** True if object is an exact even integer. */
1026 bool numeric::is_even() const
1028 return (cln::instanceof(value, cln::cl_I_ring) && cln::evenp(cln::the<cln::cl_I>(value)));
1032 /** True if object is an exact odd integer. */
1033 bool numeric::is_odd() const
1035 return (cln::instanceof(value, cln::cl_I_ring) && cln::oddp(cln::the<cln::cl_I>(value)));
1039 /** Probabilistic primality test.
1041 * @return true if object is exact integer and prime. */
1042 bool numeric::is_prime() const
1044 return (cln::instanceof(value, cln::cl_I_ring) // integer?
1045 && cln::plusp(cln::the<cln::cl_I>(value)) // positive?
1046 && cln::isprobprime(cln::the<cln::cl_I>(value)));
1050 /** True if object is an exact rational number, may even be complex
1051 * (denominator may be unity). */
1052 bool numeric::is_rational() const
1054 return cln::instanceof(value, cln::cl_RA_ring);
1058 /** True if object is a real integer, rational or float (but not complex). */
1059 bool numeric::is_real() const
1061 return cln::instanceof(value, cln::cl_R_ring);
1065 bool numeric::operator==(const numeric &other) const
1067 return cln::equal(value, other.value);
1071 bool numeric::operator!=(const numeric &other) const
1073 return !cln::equal(value, other.value);
1077 /** True if object is element of the domain of integers extended by I, i.e. is
1078 * of the form a+b*I, where a and b are integers. */
1079 bool numeric::is_cinteger() const
1081 if (cln::instanceof(value, cln::cl_I_ring))
1083 else if (!this->is_real()) { // complex case, handle n+m*I
1084 if (cln::instanceof(cln::realpart(value), cln::cl_I_ring) &&
1085 cln::instanceof(cln::imagpart(value), cln::cl_I_ring))
1092 /** True if object is an exact rational number, may even be complex
1093 * (denominator may be unity). */
1094 bool numeric::is_crational() const
1096 if (cln::instanceof(value, cln::cl_RA_ring))
1098 else if (!this->is_real()) { // complex case, handle Q(i):
1099 if (cln::instanceof(cln::realpart(value), cln::cl_RA_ring) &&
1100 cln::instanceof(cln::imagpart(value), cln::cl_RA_ring))
1107 /** Numerical comparison: less.
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: less or equal.
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.
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 /** Numerical comparison: greater or equal.
1142 * @exception invalid_argument (complex inequality) */
1143 bool numeric::operator>=(const numeric &other) const
1145 if (this->is_real() && other.is_real())
1146 return (cln::the<cln::cl_R>(value) >= cln::the<cln::cl_R>(other.value));
1147 throw std::invalid_argument("numeric::operator>=(): complex inequality");
1151 /** Converts numeric types to machine's int. You should check with
1152 * is_integer() if the number is really an integer before calling this method.
1153 * You may also consider checking the range first. */
1154 int numeric::to_int() const
1156 GINAC_ASSERT(this->is_integer());
1157 return cln::cl_I_to_int(cln::the<cln::cl_I>(value));
1161 /** Converts numeric types to machine's long. You should check with
1162 * is_integer() if the number is really an integer before calling this method.
1163 * You may also consider checking the range first. */
1164 long numeric::to_long() const
1166 GINAC_ASSERT(this->is_integer());
1167 return cln::cl_I_to_long(cln::the<cln::cl_I>(value));
1171 /** Converts numeric types to machine's double. You should check with is_real()
1172 * if the number is really not complex before calling this method. */
1173 double numeric::to_double() const
1175 GINAC_ASSERT(this->is_real());
1176 return cln::double_approx(cln::realpart(value));
1180 /** Returns a new CLN object of type cl_N, representing the value of *this.
1181 * This method may be used when mixing GiNaC and CLN in one project.
1183 cln::cl_N numeric::to_cl_N() const
1189 /** Real part of a number. */
1190 const numeric numeric::real() const
1192 return numeric(cln::realpart(value));
1196 /** Imaginary part of a number. */
1197 const numeric numeric::imag() const
1199 return numeric(cln::imagpart(value));
1203 /** Numerator. Computes the numerator of rational numbers, rationalized
1204 * numerator of complex if real and imaginary part are both rational numbers
1205 * (i.e numer(4/3+5/6*I) == 8+5*I), the number carrying the sign in all other
1207 const numeric numeric::numer() const
1209 if (cln::instanceof(value, cln::cl_I_ring))
1210 return numeric(*this); // integer case
1212 else if (cln::instanceof(value, cln::cl_RA_ring))
1213 return numeric(cln::numerator(cln::the<cln::cl_RA>(value)));
1215 else if (!this->is_real()) { // complex case, handle Q(i):
1216 const cln::cl_RA r = cln::the<cln::cl_RA>(cln::realpart(value));
1217 const cln::cl_RA i = cln::the<cln::cl_RA>(cln::imagpart(value));
1218 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_I_ring))
1219 return numeric(*this);
1220 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_RA_ring))
1221 return numeric(cln::complex(r*cln::denominator(i), cln::numerator(i)));
1222 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_I_ring))
1223 return numeric(cln::complex(cln::numerator(r), i*cln::denominator(r)));
1224 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_RA_ring)) {
1225 const cln::cl_I s = cln::lcm(cln::denominator(r), cln::denominator(i));
1226 return numeric(cln::complex(cln::numerator(r)*(cln::exquo(s,cln::denominator(r))),
1227 cln::numerator(i)*(cln::exquo(s,cln::denominator(i)))));
1230 // at least one float encountered
1231 return numeric(*this);
1235 /** Denominator. Computes the denominator of rational numbers, common integer
1236 * denominator of complex if real and imaginary part are both rational numbers
1237 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
1238 const numeric numeric::denom() const
1240 if (cln::instanceof(value, cln::cl_I_ring))
1241 return *_num1_p; // integer case
1243 if (cln::instanceof(value, cln::cl_RA_ring))
1244 return numeric(cln::denominator(cln::the<cln::cl_RA>(value)));
1246 if (!this->is_real()) { // complex case, handle Q(i):
1247 const cln::cl_RA r = cln::the<cln::cl_RA>(cln::realpart(value));
1248 const cln::cl_RA i = cln::the<cln::cl_RA>(cln::imagpart(value));
1249 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_I_ring))
1251 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_RA_ring))
1252 return numeric(cln::denominator(i));
1253 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_I_ring))
1254 return numeric(cln::denominator(r));
1255 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_RA_ring))
1256 return numeric(cln::lcm(cln::denominator(r), cln::denominator(i)));
1258 // at least one float encountered
1263 /** Size in binary notation. For integers, this is the smallest n >= 0 such
1264 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
1265 * 2^(n-1) <= x < 2^n.
1267 * @return number of bits (excluding sign) needed to represent that number
1268 * in two's complement if it is an integer, 0 otherwise. */
1269 int numeric::int_length() const
1271 if (cln::instanceof(value, cln::cl_I_ring))
1272 return cln::integer_length(cln::the<cln::cl_I>(value));
1281 /** Imaginary unit. This is not a constant but a numeric since we are
1282 * natively handing complex numbers anyways, so in each expression containing
1283 * an I it is automatically eval'ed away anyhow. */
1284 const numeric I = numeric(cln::complex(cln::cl_I(0),cln::cl_I(1)));
1287 /** Exponential function.
1289 * @return arbitrary precision numerical exp(x). */
1290 const numeric exp(const numeric &x)
1292 return cln::exp(x.to_cl_N());
1296 /** Natural logarithm.
1298 * @param x complex number
1299 * @return arbitrary precision numerical log(x).
1300 * @exception pole_error("log(): logarithmic pole",0) */
1301 const numeric log(const numeric &x)
1304 throw pole_error("log(): logarithmic pole",0);
1305 return cln::log(x.to_cl_N());
1309 /** Numeric sine (trigonometric function).
1311 * @return arbitrary precision numerical sin(x). */
1312 const numeric sin(const numeric &x)
1314 return cln::sin(x.to_cl_N());
1318 /** Numeric cosine (trigonometric function).
1320 * @return arbitrary precision numerical cos(x). */
1321 const numeric cos(const numeric &x)
1323 return cln::cos(x.to_cl_N());
1327 /** Numeric tangent (trigonometric function).
1329 * @return arbitrary precision numerical tan(x). */
1330 const numeric tan(const numeric &x)
1332 return cln::tan(x.to_cl_N());
1336 /** Numeric inverse sine (trigonometric function).
1338 * @return arbitrary precision numerical asin(x). */
1339 const numeric asin(const numeric &x)
1341 return cln::asin(x.to_cl_N());
1345 /** Numeric inverse cosine (trigonometric function).
1347 * @return arbitrary precision numerical acos(x). */
1348 const numeric acos(const numeric &x)
1350 return cln::acos(x.to_cl_N());
1356 * @param x complex number
1358 * @exception pole_error("atan(): logarithmic pole",0) */
1359 const numeric atan(const numeric &x)
1362 x.real().is_zero() &&
1363 abs(x.imag()).is_equal(*_num1_p))
1364 throw pole_error("atan(): logarithmic pole",0);
1365 return cln::atan(x.to_cl_N());
1371 * @param x real number
1372 * @param y real number
1373 * @return atan(y/x) */
1374 const numeric atan(const numeric &y, const numeric &x)
1376 if (x.is_real() && y.is_real())
1377 return cln::atan(cln::the<cln::cl_R>(x.to_cl_N()),
1378 cln::the<cln::cl_R>(y.to_cl_N()));
1380 throw std::invalid_argument("atan(): complex argument");
1384 /** Numeric hyperbolic sine (trigonometric function).
1386 * @return arbitrary precision numerical sinh(x). */
1387 const numeric sinh(const numeric &x)
1389 return cln::sinh(x.to_cl_N());
1393 /** Numeric hyperbolic cosine (trigonometric function).
1395 * @return arbitrary precision numerical cosh(x). */
1396 const numeric cosh(const numeric &x)
1398 return cln::cosh(x.to_cl_N());
1402 /** Numeric hyperbolic tangent (trigonometric function).
1404 * @return arbitrary precision numerical tanh(x). */
1405 const numeric tanh(const numeric &x)
1407 return cln::tanh(x.to_cl_N());
1411 /** Numeric inverse hyperbolic sine (trigonometric function).
1413 * @return arbitrary precision numerical asinh(x). */
1414 const numeric asinh(const numeric &x)
1416 return cln::asinh(x.to_cl_N());
1420 /** Numeric inverse hyperbolic cosine (trigonometric function).
1422 * @return arbitrary precision numerical acosh(x). */
1423 const numeric acosh(const numeric &x)
1425 return cln::acosh(x.to_cl_N());
1429 /** Numeric inverse hyperbolic tangent (trigonometric function).
1431 * @return arbitrary precision numerical atanh(x). */
1432 const numeric atanh(const numeric &x)
1434 return cln::atanh(x.to_cl_N());
1438 /*static cln::cl_N Li2_series(const ::cl_N &x,
1439 const ::float_format_t &prec)
1441 // Note: argument must be in the unit circle
1442 // This is very inefficient unless we have fast floating point Bernoulli
1443 // numbers implemented!
1444 cln::cl_N c1 = -cln::log(1-x);
1446 // hard-wire the first two Bernoulli numbers
1447 cln::cl_N acc = c1 - cln::square(c1)/4;
1449 cln::cl_F pisq = cln::square(cln::cl_pi(prec)); // pi^2
1450 cln::cl_F piac = cln::cl_float(1, prec); // accumulator: pi^(2*i)
1452 c1 = cln::square(c1);
1456 aug = c2 * (*(bernoulli(numeric(2*i)).clnptr())) / cln::factorial(2*i+1);
1457 // 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));
1460 } while (acc != acc+aug);
1464 /** Numeric evaluation of Dilogarithm within circle of convergence (unit
1465 * circle) using a power series. */
1466 static cln::cl_N Li2_series(const cln::cl_N &x,
1467 const cln::float_format_t &prec)
1469 // Note: argument must be in the unit circle
1471 cln::cl_N num = cln::complex(cln::cl_float(1, prec), 0);
1476 den = den + i; // 1, 4, 9, 16, ...
1480 } while (acc != acc+aug);
1484 /** Folds Li2's argument inside a small rectangle to enhance convergence. */
1485 static cln::cl_N Li2_projection(const cln::cl_N &x,
1486 const cln::float_format_t &prec)
1488 const cln::cl_R re = cln::realpart(x);
1489 const cln::cl_R im = cln::imagpart(x);
1490 if (re > cln::cl_F(".5"))
1491 // zeta(2) - Li2(1-x) - log(x)*log(1-x)
1493 - Li2_series(1-x, prec)
1494 - cln::log(x)*cln::log(1-x));
1495 if ((re <= 0 && cln::abs(im) > cln::cl_F(".75")) || (re < cln::cl_F("-.5")))
1496 // -log(1-x)^2 / 2 - Li2(x/(x-1))
1497 return(- cln::square(cln::log(1-x))/2
1498 - Li2_series(x/(x-1), prec));
1499 if (re > 0 && cln::abs(im) > cln::cl_LF(".75"))
1500 // Li2(x^2)/2 - Li2(-x)
1501 return(Li2_projection(cln::square(x), prec)/2
1502 - Li2_projection(-x, prec));
1503 return Li2_series(x, prec);
1506 /** Numeric evaluation of Dilogarithm. The domain is the entire complex plane,
1507 * the branch cut lies along the positive real axis, starting at 1 and
1508 * continuous with quadrant IV.
1510 * @return arbitrary precision numerical Li2(x). */
1511 const numeric Li2(const numeric &x)
1516 // what is the desired float format?
1517 // first guess: default format
1518 cln::float_format_t prec = cln::default_float_format;
1519 const cln::cl_N value = x.to_cl_N();
1520 // second guess: the argument's format
1521 if (!x.real().is_rational())
1522 prec = cln::float_format(cln::the<cln::cl_F>(cln::realpart(value)));
1523 else if (!x.imag().is_rational())
1524 prec = cln::float_format(cln::the<cln::cl_F>(cln::imagpart(value)));
1526 if (value==1) // may cause trouble with log(1-x)
1527 return cln::zeta(2, prec);
1529 if (cln::abs(value) > 1)
1530 // -log(-x)^2 / 2 - zeta(2) - Li2(1/x)
1531 return(- cln::square(cln::log(-value))/2
1532 - cln::zeta(2, prec)
1533 - Li2_projection(cln::recip(value), prec));
1535 return Li2_projection(x.to_cl_N(), prec);
1539 /** Numeric evaluation of Riemann's Zeta function. Currently works only for
1540 * integer arguments. */
1541 const numeric zeta(const numeric &x)
1543 // A dirty hack to allow for things like zeta(3.0), since CLN currently
1544 // only knows about integer arguments and zeta(3).evalf() automatically
1545 // cascades down to zeta(3.0).evalf(). The trick is to rely on 3.0-3
1546 // being an exact zero for CLN, which can be tested and then we can just
1547 // pass the number casted to an int:
1549 const int aux = (int)(cln::double_approx(cln::the<cln::cl_R>(x.to_cl_N())));
1550 if (cln::zerop(x.to_cl_N()-aux))
1551 return cln::zeta(aux);
1557 /** The Gamma function.
1558 * This is only a stub! */
1559 const numeric lgamma(const numeric &x)
1563 const numeric tgamma(const numeric &x)
1569 /** The psi function (aka polygamma function).
1570 * This is only a stub! */
1571 const numeric psi(const numeric &x)
1577 /** The psi functions (aka polygamma functions).
1578 * This is only a stub! */
1579 const numeric psi(const numeric &n, const numeric &x)
1585 /** Factorial combinatorial function.
1587 * @param n integer argument >= 0
1588 * @exception range_error (argument must be integer >= 0) */
1589 const numeric factorial(const numeric &n)
1591 if (!n.is_nonneg_integer())
1592 throw std::range_error("numeric::factorial(): argument must be integer >= 0");
1593 return numeric(cln::factorial(n.to_int()));
1597 /** The double factorial combinatorial function. (Scarcely used, but still
1598 * useful in cases, like for exact results of tgamma(n+1/2) for instance.)
1600 * @param n integer argument >= -1
1601 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == (-1)!! == 1
1602 * @exception range_error (argument must be integer >= -1) */
1603 const numeric doublefactorial(const numeric &n)
1605 if (n.is_equal(*_num_1_p))
1608 if (!n.is_nonneg_integer())
1609 throw std::range_error("numeric::doublefactorial(): argument must be integer >= -1");
1611 return numeric(cln::doublefactorial(n.to_int()));
1615 /** The Binomial coefficients. It computes the binomial coefficients. For
1616 * integer n and k and positive n this is the number of ways of choosing k
1617 * objects from n distinct objects. If n is negative, the formula
1618 * binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */
1619 const numeric binomial(const numeric &n, const numeric &k)
1621 if (n.is_integer() && k.is_integer()) {
1622 if (n.is_nonneg_integer()) {
1623 if (k.compare(n)!=1 && k.compare(*_num0_p)!=-1)
1624 return numeric(cln::binomial(n.to_int(),k.to_int()));
1628 return _num_1_p->power(k)*binomial(k-n-(*_num1_p),k);
1632 // should really be gamma(n+1)/gamma(k+1)/gamma(n-k+1) or a suitable limit
1633 throw std::range_error("numeric::binomial(): don't know how to evaluate that.");
1637 /** Bernoulli number. The nth Bernoulli number is the coefficient of x^n/n!
1638 * in the expansion of the function x/(e^x-1).
1640 * @return the nth Bernoulli number (a rational number).
1641 * @exception range_error (argument must be integer >= 0) */
1642 const numeric bernoulli(const numeric &nn)
1644 if (!nn.is_integer() || nn.is_negative())
1645 throw std::range_error("numeric::bernoulli(): argument must be integer >= 0");
1649 // The Bernoulli numbers are rational numbers that may be computed using
1652 // B_n = - 1/(n+1) * sum_{k=0}^{n-1}(binomial(n+1,k)*B_k)
1654 // with B(0) = 1. Since the n'th Bernoulli number depends on all the
1655 // previous ones, the computation is necessarily very expensive. There are
1656 // several other ways of computing them, a particularly good one being
1660 // for (unsigned i=0; i<n; i++) {
1661 // c = exquo(c*(i-n),(i+2));
1662 // Bern = Bern + c*s/(i+2);
1663 // s = s + expt_pos(cl_I(i+2),n);
1667 // But if somebody works with the n'th Bernoulli number she is likely to
1668 // also need all previous Bernoulli numbers. So we need a complete remember
1669 // table and above divide and conquer algorithm is not suited to build one
1670 // up. The formula below accomplishes this. It is a modification of the
1671 // defining formula above but the computation of the binomial coefficients
1672 // is carried along in an inline fashion. It also honors the fact that
1673 // B_n is zero when n is odd and greater than 1.
1675 // (There is an interesting relation with the tangent polynomials described
1676 // in `Concrete Mathematics', which leads to a program a little faster as
1677 // our implementation below, but it requires storing one such polynomial in
1678 // addition to the remember table. This doubles the memory footprint so
1679 // we don't use it.)
1681 const unsigned n = nn.to_int();
1683 // the special cases not covered by the algorithm below
1685 return (n==1) ? (*_num_1_2_p) : (*_num0_p);
1689 // store nonvanishing Bernoulli numbers here
1690 static std::vector< cln::cl_RA > results;
1691 static unsigned next_r = 0;
1693 // algorithm not applicable to B(2), so just store it
1695 results.push_back(cln::recip(cln::cl_RA(6)));
1699 return results[n/2-1];
1701 results.reserve(n/2);
1702 for (unsigned p=next_r; p<=n; p+=2) {
1703 cln::cl_I c = 1; // seed for binonmial coefficients
1704 cln::cl_RA b = cln::cl_RA(1-p)/2;
1705 const unsigned p3 = p+3;
1706 const unsigned pm = p-2;
1708 // test if intermediate unsigned int can be represented by immediate
1709 // objects by CLN (i.e. < 2^29 for 32 Bit machines, see <cln/object.h>)
1710 if (p < (1UL<<cl_value_len/2)) {
1711 for (i=2, k=1, p_2=p/2; i<=pm; i+=2, ++k, --p_2) {
1712 c = cln::exquo(c * ((p3-i) * p_2), (i-1)*k);
1713 b = b + c*results[k-1];
1716 for (i=2, k=1, p_2=p/2; i<=pm; i+=2, ++k, --p_2) {
1717 c = cln::exquo((c * (p3-i)) * p_2, cln::cl_I(i-1)*k);
1718 b = b + c*results[k-1];
1721 results.push_back(-b/(p+1));
1724 return results[n/2-1];
1728 /** Fibonacci number. The nth Fibonacci number F(n) is defined by the
1729 * recurrence formula F(n)==F(n-1)+F(n-2) with F(0)==0 and F(1)==1.
1731 * @param n an integer
1732 * @return the nth Fibonacci number F(n) (an integer number)
1733 * @exception range_error (argument must be an integer) */
1734 const numeric fibonacci(const numeric &n)
1736 if (!n.is_integer())
1737 throw std::range_error("numeric::fibonacci(): argument must be integer");
1740 // The following addition formula holds:
1742 // F(n+m) = F(m-1)*F(n) + F(m)*F(n+1) for m >= 1, n >= 0.
1744 // (Proof: For fixed m, the LHS and the RHS satisfy the same recurrence
1745 // w.r.t. n, and the initial values (n=0, n=1) agree. Hence all values
1747 // Replace m by m+1:
1748 // F(n+m+1) = F(m)*F(n) + F(m+1)*F(n+1) for m >= 0, n >= 0
1749 // Now put in m = n, to get
1750 // F(2n) = (F(n+1)-F(n))*F(n) + F(n)*F(n+1) = F(n)*(2*F(n+1) - F(n))
1751 // F(2n+1) = F(n)^2 + F(n+1)^2
1753 // F(2n+2) = F(n+1)*(2*F(n) + F(n+1))
1756 if (n.is_negative())
1758 return -fibonacci(-n);
1760 return fibonacci(-n);
1764 cln::cl_I m = cln::the<cln::cl_I>(n.to_cl_N()) >> 1L; // floor(n/2);
1765 for (uintL bit=cln::integer_length(m); bit>0; --bit) {
1766 // Since a squaring is cheaper than a multiplication, better use
1767 // three squarings instead of one multiplication and two squarings.
1768 cln::cl_I u2 = cln::square(u);
1769 cln::cl_I v2 = cln::square(v);
1770 if (cln::logbitp(bit-1, m)) {
1771 v = cln::square(u + v) - u2;
1774 u = v2 - cln::square(v - u);
1779 // Here we don't use the squaring formula because one multiplication
1780 // is cheaper than two squarings.
1781 return u * ((v << 1) - u);
1783 return cln::square(u) + cln::square(v);
1787 /** Absolute value. */
1788 const numeric abs(const numeric& x)
1790 return cln::abs(x.to_cl_N());
1794 /** Modulus (in positive representation).
1795 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1796 * sign of a or is zero. This is different from Maple's modp, where the sign
1797 * of b is ignored. It is in agreement with Mathematica's Mod.
1799 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1800 * integer, 0 otherwise. */
1801 const numeric mod(const numeric &a, const numeric &b)
1803 if (a.is_integer() && b.is_integer())
1804 return cln::mod(cln::the<cln::cl_I>(a.to_cl_N()),
1805 cln::the<cln::cl_I>(b.to_cl_N()));
1811 /** Modulus (in symmetric representation).
1812 * Equivalent to Maple's mods.
1814 * @return a mod b in the range [-iquo(abs(b)-1,2), iquo(abs(b),2)]. */
1815 const numeric smod(const numeric &a, const numeric &b)
1817 if (a.is_integer() && b.is_integer()) {
1818 const cln::cl_I b2 = cln::ceiling1(cln::the<cln::cl_I>(b.to_cl_N()) >> 1) - 1;
1819 return cln::mod(cln::the<cln::cl_I>(a.to_cl_N()) + b2,
1820 cln::the<cln::cl_I>(b.to_cl_N())) - b2;
1826 /** Numeric integer remainder.
1827 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1828 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1829 * sign of a or is zero.
1831 * @return remainder of a/b if both are integer, 0 otherwise.
1832 * @exception overflow_error (division by zero) if b is zero. */
1833 const numeric irem(const numeric &a, const numeric &b)
1836 throw std::overflow_error("numeric::irem(): division by zero");
1837 if (a.is_integer() && b.is_integer())
1838 return cln::rem(cln::the<cln::cl_I>(a.to_cl_N()),
1839 cln::the<cln::cl_I>(b.to_cl_N()));
1845 /** Numeric integer remainder.
1846 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1847 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1848 * and irem(a,b) has the sign of a or is zero.
1850 * @return remainder of a/b and quotient stored in q if both are integer,
1852 * @exception overflow_error (division by zero) if b is zero. */
1853 const numeric irem(const numeric &a, const numeric &b, numeric &q)
1856 throw std::overflow_error("numeric::irem(): division by zero");
1857 if (a.is_integer() && b.is_integer()) {
1858 const cln::cl_I_div_t rem_quo = cln::truncate2(cln::the<cln::cl_I>(a.to_cl_N()),
1859 cln::the<cln::cl_I>(b.to_cl_N()));
1860 q = rem_quo.quotient;
1861 return rem_quo.remainder;
1869 /** Numeric integer quotient.
1870 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1872 * @return truncated quotient of a/b if both are integer, 0 otherwise.
1873 * @exception overflow_error (division by zero) if b is zero. */
1874 const numeric iquo(const numeric &a, const numeric &b)
1877 throw std::overflow_error("numeric::iquo(): division by zero");
1878 if (a.is_integer() && b.is_integer())
1879 return cln::truncate1(cln::the<cln::cl_I>(a.to_cl_N()),
1880 cln::the<cln::cl_I>(b.to_cl_N()));
1886 /** Numeric integer quotient.
1887 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1888 * r == a - iquo(a,b,r)*b.
1890 * @return truncated quotient of a/b and remainder stored in r if both are
1891 * integer, 0 otherwise.
1892 * @exception overflow_error (division by zero) if b is zero. */
1893 const numeric iquo(const numeric &a, const numeric &b, numeric &r)
1896 throw std::overflow_error("numeric::iquo(): division by zero");
1897 if (a.is_integer() && b.is_integer()) {
1898 const cln::cl_I_div_t rem_quo = cln::truncate2(cln::the<cln::cl_I>(a.to_cl_N()),
1899 cln::the<cln::cl_I>(b.to_cl_N()));
1900 r = rem_quo.remainder;
1901 return rem_quo.quotient;
1909 /** Greatest Common Divisor.
1911 * @return The GCD of two numbers if both are integer, a numerical 1
1912 * if they are not. */
1913 const numeric gcd(const numeric &a, const numeric &b)
1915 if (a.is_integer() && b.is_integer())
1916 return cln::gcd(cln::the<cln::cl_I>(a.to_cl_N()),
1917 cln::the<cln::cl_I>(b.to_cl_N()));
1923 /** Least Common Multiple.
1925 * @return The LCM of two numbers if both are integer, the product of those
1926 * two numbers if they are not. */
1927 const numeric lcm(const numeric &a, const numeric &b)
1929 if (a.is_integer() && b.is_integer())
1930 return cln::lcm(cln::the<cln::cl_I>(a.to_cl_N()),
1931 cln::the<cln::cl_I>(b.to_cl_N()));
1937 /** Numeric square root.
1938 * If possible, sqrt(x) should respect squares of exact numbers, i.e. sqrt(4)
1939 * should return integer 2.
1941 * @param x numeric argument
1942 * @return square root of x. Branch cut along negative real axis, the negative
1943 * real axis itself where imag(x)==0 and real(x)<0 belongs to the upper part
1944 * where imag(x)>0. */
1945 const numeric sqrt(const numeric &x)
1947 return cln::sqrt(x.to_cl_N());
1951 /** Integer numeric square root. */
1952 const numeric isqrt(const numeric &x)
1954 if (x.is_integer()) {
1956 cln::isqrt(cln::the<cln::cl_I>(x.to_cl_N()), &root);
1963 /** Floating point evaluation of Archimedes' constant Pi. */
1966 return numeric(cln::pi(cln::default_float_format));
1970 /** Floating point evaluation of Euler's constant gamma. */
1973 return numeric(cln::eulerconst(cln::default_float_format));
1977 /** Floating point evaluation of Catalan's constant. */
1980 return numeric(cln::catalanconst(cln::default_float_format));
1984 /** _numeric_digits default ctor, checking for singleton invariance. */
1985 _numeric_digits::_numeric_digits()
1988 // It initializes to 17 digits, because in CLN float_format(17) turns out
1989 // to be 61 (<64) while float_format(18)=65. The reason is we want to
1990 // have a cl_LF instead of cl_SF, cl_FF or cl_DF.
1992 throw(std::runtime_error("I told you not to do instantiate me!"));
1994 cln::default_float_format = cln::float_format(17);
1998 /** Assign a native long to global Digits object. */
1999 _numeric_digits& _numeric_digits::operator=(long prec)
2002 cln::default_float_format = cln::float_format(prec);
2007 /** Convert global Digits object to native type long. */
2008 _numeric_digits::operator long()
2010 // BTW, this is approx. unsigned(cln::default_float_format*0.301)-1
2011 return (long)digits;
2015 /** Append global Digits object to ostream. */
2016 void _numeric_digits::print(std::ostream &os) const
2022 std::ostream& operator<<(std::ostream &os, const _numeric_digits &e)
2029 // static member variables
2034 bool _numeric_digits::too_late = false;
2037 /** Accuracy in decimal digits. Only object of this type! Can be set using
2038 * assignment from C++ unsigned ints and evaluated like any built-in type. */
2039 _numeric_digits Digits;
2041 } // namespace GiNaC