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-2007 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 // The #if clause prevents compiler warnings on 64bit machines where the
96 // comparision is always true.
97 #if cl_value_len >= 32
100 if (i < (1L << (cl_value_len-1)) && i >= -(1L << (cl_value_len-1)))
101 value = cln::cl_I(i);
103 value = cln::cl_I(static_cast<long>(i));
105 setflag(status_flags::evaluated | status_flags::expanded);
109 numeric::numeric(unsigned int i) : basic(TINFO_numeric)
111 // Not the whole uint-range is available if we don't cast to ulong
112 // first. This is due to the behaviour of the cl_I-ctor, which
113 // emphasizes efficiency. However, if the integer is small enough
114 // we save space and dereferences by using an immediate type.
115 // (C.f. <cln/object.h>)
116 // The #if clause prevents compiler warnings on 64bit machines where the
117 // comparision is always true.
118 #if cl_value_len >= 32
119 value = cln::cl_I(i);
121 if (i < (1UL << (cl_value_len-1)))
122 value = cln::cl_I(i);
124 value = cln::cl_I(static_cast<unsigned long>(i));
126 setflag(status_flags::evaluated | status_flags::expanded);
130 numeric::numeric(long i) : basic(TINFO_numeric)
132 value = cln::cl_I(i);
133 setflag(status_flags::evaluated | status_flags::expanded);
137 numeric::numeric(unsigned long i) : basic(TINFO_numeric)
139 value = cln::cl_I(i);
140 setflag(status_flags::evaluated | status_flags::expanded);
144 /** Constructor for rational numerics a/b.
146 * @exception overflow_error (division by zero) */
147 numeric::numeric(long numer, long denom) : basic(TINFO_numeric)
150 throw std::overflow_error("division by zero");
151 value = cln::cl_I(numer) / cln::cl_I(denom);
152 setflag(status_flags::evaluated | status_flags::expanded);
156 numeric::numeric(double d) : basic(TINFO_numeric)
158 // We really want to explicitly use the type cl_LF instead of the
159 // more general cl_F, since that would give us a cl_DF only which
160 // will not be promoted to cl_LF if overflow occurs:
161 value = cln::cl_float(d, cln::default_float_format);
162 setflag(status_flags::evaluated | status_flags::expanded);
166 /** ctor from C-style string. It also accepts complex numbers in GiNaC
167 * notation like "2+5*I". */
168 numeric::numeric(const char *s) : basic(TINFO_numeric)
170 cln::cl_N ctorval = 0;
171 // parse complex numbers (functional but not completely safe, unfortunately
172 // std::string does not understand regexpese):
173 // ss should represent a simple sum like 2+5*I
175 std::string::size_type delim;
177 // make this implementation safe by adding explicit sign
178 if (ss.at(0) != '+' && ss.at(0) != '-' && ss.at(0) != '#')
181 // We use 'E' as exponent marker in the output, but some people insist on
182 // writing 'e' at input, so let's substitute them right at the beginning:
183 while ((delim = ss.find("e"))!=std::string::npos)
184 ss.replace(delim,1,"E");
188 // chop ss into terms from left to right
190 bool imaginary = false;
191 delim = ss.find_first_of(std::string("+-"),1);
192 // Do we have an exponent marker like "31.415E-1"? If so, hop on!
193 if (delim!=std::string::npos && ss.at(delim-1)=='E')
194 delim = ss.find_first_of(std::string("+-"),delim+1);
195 term = ss.substr(0,delim);
196 if (delim!=std::string::npos)
197 ss = ss.substr(delim);
198 // is the term imaginary?
199 if (term.find("I")!=std::string::npos) {
201 term.erase(term.find("I"),1);
203 if (term.find("*")!=std::string::npos)
204 term.erase(term.find("*"),1);
205 // correct for trivial +/-I without explicit factor on I:
210 if (term.find('.')!=std::string::npos || term.find('E')!=std::string::npos) {
211 // CLN's short type cl_SF is not very useful within the GiNaC
212 // framework where we are mainly interested in the arbitrary
213 // precision type cl_LF. Hence we go straight to the construction
214 // of generic floats. In order to create them we have to convert
215 // our own floating point notation used for output and construction
216 // from char * to CLN's generic notation:
217 // 3.14 --> 3.14e0_<Digits>
218 // 31.4E-1 --> 31.4e-1_<Digits>
220 // No exponent marker? Let's add a trivial one.
221 if (term.find("E")==std::string::npos)
224 term = term.replace(term.find("E"),1,"e");
225 // append _<Digits> to term
226 term += "_" + ToString((unsigned)Digits);
227 // construct float using cln::cl_F(const char *) ctor.
229 ctorval = ctorval + cln::complex(cln::cl_I(0),cln::cl_F(term.c_str()));
231 ctorval = ctorval + cln::cl_F(term.c_str());
233 // this is not a floating point number...
235 ctorval = ctorval + cln::complex(cln::cl_I(0),cln::cl_R(term.c_str()));
237 ctorval = ctorval + cln::cl_R(term.c_str());
239 } while (delim != std::string::npos);
241 setflag(status_flags::evaluated | status_flags::expanded);
245 /** Ctor from CLN types. This is for the initiated user or internal use
247 numeric::numeric(const cln::cl_N &z) : basic(TINFO_numeric)
250 setflag(status_flags::evaluated | status_flags::expanded);
258 numeric::numeric(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
260 cln::cl_N ctorval = 0;
262 // Read number as string
264 if (n.find_string("number", str)) {
265 std::istringstream s(str);
266 cln::cl_idecoded_float re, im;
270 case 'R': // Integer-decoded real number
271 s >> re.sign >> re.mantissa >> re.exponent;
272 ctorval = re.sign * re.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), re.exponent);
274 case 'C': // Integer-decoded complex number
275 s >> re.sign >> re.mantissa >> re.exponent;
276 s >> im.sign >> im.mantissa >> im.exponent;
277 ctorval = cln::complex(re.sign * re.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), re.exponent),
278 im.sign * im.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), im.exponent));
280 default: // Ordinary number
287 setflag(status_flags::evaluated | status_flags::expanded);
290 void numeric::archive(archive_node &n) const
292 inherited::archive(n);
294 // Write number as string
295 std::ostringstream s;
296 if (this->is_crational())
299 // Non-rational numbers are written in an integer-decoded format
300 // to preserve the precision
301 if (this->is_real()) {
302 cln::cl_idecoded_float re = cln::integer_decode_float(cln::the<cln::cl_F>(value));
304 s << re.sign << " " << re.mantissa << " " << re.exponent;
306 cln::cl_idecoded_float re = cln::integer_decode_float(cln::the<cln::cl_F>(cln::realpart(cln::the<cln::cl_N>(value))));
307 cln::cl_idecoded_float im = cln::integer_decode_float(cln::the<cln::cl_F>(cln::imagpart(cln::the<cln::cl_N>(value))));
309 s << re.sign << " " << re.mantissa << " " << re.exponent << " ";
310 s << im.sign << " " << im.mantissa << " " << im.exponent;
313 n.add_string("number", s.str());
316 DEFAULT_UNARCHIVE(numeric)
319 // functions overriding virtual functions from base classes
322 /** Helper function to print a real number in a nicer way than is CLN's
323 * default. Instead of printing 42.0L0 this just prints 42.0 to ostream os
324 * and instead of 3.99168L7 it prints 3.99168E7. This is fine in GiNaC as
325 * long as it only uses cl_LF and no other floating point types that we might
326 * want to visibly distinguish from cl_LF.
328 * @see numeric::print() */
329 static void print_real_number(const print_context & c, const cln::cl_R & x)
331 cln::cl_print_flags ourflags;
332 if (cln::instanceof(x, cln::cl_RA_ring)) {
333 // case 1: integer or rational
334 if (cln::instanceof(x, cln::cl_I_ring) ||
335 !is_a<print_latex>(c)) {
336 cln::print_real(c.s, ourflags, x);
337 } else { // rational output in LaTeX context
341 cln::print_real(c.s, ourflags, cln::abs(cln::numerator(cln::the<cln::cl_RA>(x))));
343 cln::print_real(c.s, ourflags, cln::denominator(cln::the<cln::cl_RA>(x)));
348 // make CLN believe this number has default_float_format, so it prints
349 // 'E' as exponent marker instead of 'L':
350 ourflags.default_float_format = cln::float_format(cln::the<cln::cl_F>(x));
351 cln::print_real(c.s, ourflags, x);
355 /** Helper function to print integer number in C++ source format.
357 * @see numeric::print() */
358 static void print_integer_csrc(const print_context & c, const cln::cl_I & x)
360 // Print small numbers in compact float format, but larger numbers in
362 const int max_cln_int = 536870911; // 2^29-1
363 if (x >= cln::cl_I(-max_cln_int) && x <= cln::cl_I(max_cln_int))
364 c.s << cln::cl_I_to_int(x) << ".0";
366 c.s << cln::double_approx(x);
369 /** Helper function to print real number in C++ source format.
371 * @see numeric::print() */
372 static void print_real_csrc(const print_context & c, const cln::cl_R & x)
374 if (cln::instanceof(x, cln::cl_I_ring)) {
377 print_integer_csrc(c, cln::the<cln::cl_I>(x));
379 } else if (cln::instanceof(x, cln::cl_RA_ring)) {
382 const cln::cl_I numer = cln::numerator(cln::the<cln::cl_RA>(x));
383 const cln::cl_I denom = cln::denominator(cln::the<cln::cl_RA>(x));
384 if (cln::plusp(x) > 0) {
386 print_integer_csrc(c, numer);
389 print_integer_csrc(c, -numer);
392 print_integer_csrc(c, denom);
398 c.s << cln::double_approx(x);
402 /** Helper function to print real number in C++ source format using cl_N types.
404 * @see numeric::print() */
405 static void print_real_cl_N(const print_context & c, const cln::cl_R & x)
407 if (cln::instanceof(x, cln::cl_I_ring)) {
410 c.s << "cln::cl_I(\"";
411 print_real_number(c, x);
414 } else if (cln::instanceof(x, cln::cl_RA_ring)) {
417 cln::cl_print_flags ourflags;
418 c.s << "cln::cl_RA(\"";
419 cln::print_rational(c.s, ourflags, cln::the<cln::cl_RA>(x));
425 c.s << "cln::cl_F(\"";
426 print_real_number(c, cln::cl_float(1.0, cln::default_float_format) * x);
427 c.s << "_" << Digits << "\")";
431 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
433 const cln::cl_R r = cln::realpart(value);
434 const cln::cl_R i = cln::imagpart(value);
438 // case 1, real: x or -x
439 if ((precedence() <= level) && (!this->is_nonneg_integer())) {
441 print_real_number(c, r);
444 print_real_number(c, r);
450 // case 2, imaginary: y*I or -y*I
454 if (precedence()<=level)
457 c.s << "-" << imag_sym;
459 print_real_number(c, i);
460 c.s << mul_sym << imag_sym;
462 if (precedence()<=level)
468 // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I
469 if (precedence() <= level)
471 print_real_number(c, r);
474 c.s << "-" << imag_sym;
476 print_real_number(c, i);
477 c.s << mul_sym << imag_sym;
481 c.s << "+" << imag_sym;
484 print_real_number(c, i);
485 c.s << mul_sym << imag_sym;
488 if (precedence() <= level)
494 void numeric::do_print(const print_context & c, unsigned level) const
496 print_numeric(c, "(", ")", "I", "*", level);
499 void numeric::do_print_latex(const print_latex & c, unsigned level) const
501 print_numeric(c, "{(", ")}", "i", " ", level);
504 void numeric::do_print_csrc(const print_csrc & c, unsigned level) const
506 std::ios::fmtflags oldflags = c.s.flags();
507 c.s.setf(std::ios::scientific);
508 int oldprec = c.s.precision();
511 if (is_a<print_csrc_double>(c))
512 c.s.precision(std::numeric_limits<double>::digits10 + 1);
514 c.s.precision(std::numeric_limits<float>::digits10 + 1);
516 if (this->is_real()) {
519 print_real_csrc(c, cln::the<cln::cl_R>(value));
524 c.s << "std::complex<";
525 if (is_a<print_csrc_double>(c))
530 print_real_csrc(c, cln::realpart(value));
532 print_real_csrc(c, cln::imagpart(value));
537 c.s.precision(oldprec);
540 void numeric::do_print_csrc_cl_N(const print_csrc_cl_N & c, unsigned level) const
542 if (this->is_real()) {
545 print_real_cl_N(c, cln::the<cln::cl_R>(value));
550 c.s << "cln::complex(";
551 print_real_cl_N(c, cln::realpart(value));
553 print_real_cl_N(c, cln::imagpart(value));
558 void numeric::do_print_tree(const print_tree & c, unsigned level) const
560 c.s << std::string(level, ' ') << value
561 << " (" << class_name() << ")" << " @" << this
562 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
566 void numeric::do_print_python_repr(const print_python_repr & c, unsigned level) const
568 c.s << class_name() << "('";
569 print_numeric(c, "(", ")", "I", "*", level);
573 bool numeric::info(unsigned inf) const
576 case info_flags::numeric:
577 case info_flags::polynomial:
578 case info_flags::rational_function:
580 case info_flags::real:
582 case info_flags::rational:
583 case info_flags::rational_polynomial:
584 return is_rational();
585 case info_flags::crational:
586 case info_flags::crational_polynomial:
587 return is_crational();
588 case info_flags::integer:
589 case info_flags::integer_polynomial:
591 case info_flags::cinteger:
592 case info_flags::cinteger_polynomial:
593 return is_cinteger();
594 case info_flags::positive:
595 return is_positive();
596 case info_flags::negative:
597 return is_negative();
598 case info_flags::nonnegative:
599 return !is_negative();
600 case info_flags::posint:
601 return is_pos_integer();
602 case info_flags::negint:
603 return is_integer() && is_negative();
604 case info_flags::nonnegint:
605 return is_nonneg_integer();
606 case info_flags::even:
608 case info_flags::odd:
610 case info_flags::prime:
612 case info_flags::algebraic:
618 int numeric::degree(const ex & s) const
623 int numeric::ldegree(const ex & s) const
628 ex numeric::coeff(const ex & s, int n) const
630 return n==0 ? *this : _ex0;
633 /** Disassemble real part and imaginary part to scan for the occurrence of a
634 * single number. Also handles the imaginary unit. It ignores the sign on
635 * both this and the argument, which may lead to what might appear as funny
636 * results: (2+I).has(-2) -> true. But this is consistent, since we also
637 * would like to have (-2+I).has(2) -> true and we want to think about the
638 * sign as a multiplicative factor. */
639 bool numeric::has(const ex &other) const
641 if (!is_exactly_a<numeric>(other))
643 const numeric &o = ex_to<numeric>(other);
644 if (this->is_equal(o) || this->is_equal(-o))
646 if (o.imag().is_zero()) { // e.g. scan for 3 in -3*I
647 if (!this->real().is_equal(*_num0_p))
648 if (this->real().is_equal(o) || this->real().is_equal(-o))
650 if (!this->imag().is_equal(*_num0_p))
651 if (this->imag().is_equal(o) || this->imag().is_equal(-o))
656 if (o.is_equal(I)) // e.g scan for I in 42*I
657 return !this->is_real();
658 if (o.real().is_zero()) // e.g. scan for 2*I in 2*I+1
659 if (!this->imag().is_equal(*_num0_p))
660 if (this->imag().is_equal(o*I) || this->imag().is_equal(-o*I))
667 /** Evaluation of numbers doesn't do anything at all. */
668 ex numeric::eval(int level) const
670 // Warning: if this is ever gonna do something, the ex ctors from all kinds
671 // of numbers should be checking for status_flags::evaluated.
676 /** Cast numeric into a floating-point object. For example exact numeric(1) is
677 * returned as a 1.0000000000000000000000 and so on according to how Digits is
678 * currently set. In case the object already was a floating point number the
679 * precision is trimmed to match the currently set default.
681 * @param level ignored, only needed for overriding basic::evalf.
682 * @return an ex-handle to a numeric. */
683 ex numeric::evalf(int level) const
685 // level can safely be discarded for numeric objects.
686 return numeric(cln::cl_float(1.0, cln::default_float_format) * value);
689 ex numeric::conjugate() const
694 return numeric(cln::conjugate(this->value));
699 int numeric::compare_same_type(const basic &other) const
701 GINAC_ASSERT(is_exactly_a<numeric>(other));
702 const numeric &o = static_cast<const numeric &>(other);
704 return this->compare(o);
708 bool numeric::is_equal_same_type(const basic &other) const
710 GINAC_ASSERT(is_exactly_a<numeric>(other));
711 const numeric &o = static_cast<const numeric &>(other);
713 return this->is_equal(o);
717 unsigned numeric::calchash() const
719 // Base computation of hashvalue on CLN's hashcode. Note: That depends
720 // only on the number's value, not its type or precision (i.e. a true
721 // equivalence relation on numbers). As a consequence, 3 and 3.0 share
722 // the same hashvalue. That shouldn't really matter, though.
723 setflag(status_flags::hash_calculated);
724 hashvalue = golden_ratio_hash(cln::equal_hashcode(value));
730 // new virtual functions which can be overridden by derived classes
736 // non-virtual functions in this class
741 /** Numerical addition method. Adds argument to *this and returns result as
742 * a numeric object. */
743 const numeric numeric::add(const numeric &other) const
745 return numeric(value + other.value);
749 /** Numerical subtraction method. Subtracts argument from *this and returns
750 * result as a numeric object. */
751 const numeric numeric::sub(const numeric &other) const
753 return numeric(value - other.value);
757 /** Numerical multiplication method. Multiplies *this and argument and returns
758 * result as a numeric object. */
759 const numeric numeric::mul(const numeric &other) const
761 return numeric(value * other.value);
765 /** Numerical division method. Divides *this by argument and returns result as
768 * @exception overflow_error (division by zero) */
769 const numeric numeric::div(const numeric &other) const
771 if (cln::zerop(other.value))
772 throw std::overflow_error("numeric::div(): division by zero");
773 return numeric(value / other.value);
777 /** Numerical exponentiation. Raises *this to the power given as argument and
778 * returns result as a numeric object. */
779 const numeric numeric::power(const numeric &other) const
781 // Shortcut for efficiency and numeric stability (as in 1.0 exponent):
782 // trap the neutral exponent.
783 if (&other==_num1_p || cln::equal(other.value,_num1_p->value))
786 if (cln::zerop(value)) {
787 if (cln::zerop(other.value))
788 throw std::domain_error("numeric::eval(): pow(0,0) is undefined");
789 else if (cln::zerop(cln::realpart(other.value)))
790 throw std::domain_error("numeric::eval(): pow(0,I) is undefined");
791 else if (cln::minusp(cln::realpart(other.value)))
792 throw std::overflow_error("numeric::eval(): division by zero");
796 return numeric(cln::expt(value, other.value));
801 /** Numerical addition method. Adds argument to *this and returns result as
802 * a numeric object on the heap. Use internally only for direct wrapping into
803 * an ex object, where the result would end up on the heap anyways. */
804 const numeric &numeric::add_dyn(const numeric &other) const
806 // Efficiency shortcut: trap the neutral element by pointer. This hack
807 // is supposed to keep the number of distinct numeric objects low.
810 else if (&other==_num0_p)
813 return static_cast<const numeric &>((new numeric(value + other.value))->
814 setflag(status_flags::dynallocated));
818 /** Numerical subtraction method. Subtracts argument from *this and returns
819 * result as a numeric object on the heap. Use internally only for direct
820 * wrapping into an ex object, where the result would end up on the heap
822 const numeric &numeric::sub_dyn(const numeric &other) const
824 // Efficiency shortcut: trap the neutral exponent (first by pointer). This
825 // hack is supposed to keep the number of distinct numeric objects low.
826 if (&other==_num0_p || cln::zerop(other.value))
829 return static_cast<const numeric &>((new numeric(value - other.value))->
830 setflag(status_flags::dynallocated));
834 /** Numerical multiplication method. Multiplies *this and argument and returns
835 * result as a numeric object on the heap. Use internally only for direct
836 * wrapping into an ex object, where the result would end up on the heap
838 const numeric &numeric::mul_dyn(const numeric &other) const
840 // Efficiency shortcut: trap the neutral element by pointer. This hack
841 // is supposed to keep the number of distinct numeric objects low.
844 else if (&other==_num1_p)
847 return static_cast<const numeric &>((new numeric(value * other.value))->
848 setflag(status_flags::dynallocated));
852 /** Numerical division method. Divides *this by argument and returns result as
853 * a numeric object on the heap. Use internally only for direct wrapping
854 * into an ex object, where the result would end up on the heap
857 * @exception overflow_error (division by zero) */
858 const numeric &numeric::div_dyn(const numeric &other) const
860 // Efficiency shortcut: trap the neutral element by pointer. This hack
861 // is supposed to keep the number of distinct numeric objects low.
864 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
865 throw std::overflow_error("division by zero");
866 return static_cast<const numeric &>((new numeric(value / other.value))->
867 setflag(status_flags::dynallocated));
871 /** Numerical exponentiation. Raises *this to the power given as argument and
872 * returns result as a numeric object on the heap. Use internally only for
873 * direct wrapping into an ex object, where the result would end up on the
875 const numeric &numeric::power_dyn(const numeric &other) const
877 // Efficiency shortcut: trap the neutral exponent (first try by pointer, then
878 // try harder, since calls to cln::expt() below may return amazing results for
879 // floating point exponent 1.0).
880 if (&other==_num1_p || cln::equal(other.value, _num1_p->value))
883 if (cln::zerop(value)) {
884 if (cln::zerop(other.value))
885 throw std::domain_error("numeric::eval(): pow(0,0) is undefined");
886 else if (cln::zerop(cln::realpart(other.value)))
887 throw std::domain_error("numeric::eval(): pow(0,I) is undefined");
888 else if (cln::minusp(cln::realpart(other.value)))
889 throw std::overflow_error("numeric::eval(): division by zero");
893 return static_cast<const numeric &>((new numeric(cln::expt(value, other.value)))->
894 setflag(status_flags::dynallocated));
898 const numeric &numeric::operator=(int i)
900 return operator=(numeric(i));
904 const numeric &numeric::operator=(unsigned int i)
906 return operator=(numeric(i));
910 const numeric &numeric::operator=(long i)
912 return operator=(numeric(i));
916 const numeric &numeric::operator=(unsigned long i)
918 return operator=(numeric(i));
922 const numeric &numeric::operator=(double d)
924 return operator=(numeric(d));
928 const numeric &numeric::operator=(const char * s)
930 return operator=(numeric(s));
934 /** Inverse of a number. */
935 const numeric numeric::inverse() const
937 if (cln::zerop(value))
938 throw std::overflow_error("numeric::inverse(): division by zero");
939 return numeric(cln::recip(value));
943 /** Return the complex half-plane (left or right) in which the number lies.
944 * csgn(x)==0 for x==0, csgn(x)==1 for Re(x)>0 or Re(x)=0 and Im(x)>0,
945 * csgn(x)==-1 for Re(x)<0 or Re(x)=0 and Im(x)<0.
947 * @see numeric::compare(const numeric &other) */
948 int numeric::csgn() const
950 if (cln::zerop(value))
952 cln::cl_R r = cln::realpart(value);
953 if (!cln::zerop(r)) {
959 if (cln::plusp(cln::imagpart(value)))
967 /** This method establishes a canonical order on all numbers. For complex
968 * numbers this is not possible in a mathematically consistent way but we need
969 * to establish some order and it ought to be fast. So we simply define it
970 * to be compatible with our method csgn.
972 * @return csgn(*this-other)
973 * @see numeric::csgn() */
974 int numeric::compare(const numeric &other) const
976 // Comparing two real numbers?
977 if (cln::instanceof(value, cln::cl_R_ring) &&
978 cln::instanceof(other.value, cln::cl_R_ring))
979 // Yes, so just cln::compare them
980 return cln::compare(cln::the<cln::cl_R>(value), cln::the<cln::cl_R>(other.value));
982 // No, first cln::compare real parts...
983 cl_signean real_cmp = cln::compare(cln::realpart(value), cln::realpart(other.value));
986 // ...and then the imaginary parts.
987 return cln::compare(cln::imagpart(value), cln::imagpart(other.value));
992 bool numeric::is_equal(const numeric &other) const
994 return cln::equal(value, other.value);
998 /** True if object is zero. */
999 bool numeric::is_zero() const
1001 return cln::zerop(value);
1005 /** True if object is not complex and greater than zero. */
1006 bool numeric::is_positive() const
1008 if (cln::instanceof(value, cln::cl_R_ring)) // real?
1009 return cln::plusp(cln::the<cln::cl_R>(value));
1014 /** True if object is not complex and less than zero. */
1015 bool numeric::is_negative() const
1017 if (cln::instanceof(value, cln::cl_R_ring)) // real?
1018 return cln::minusp(cln::the<cln::cl_R>(value));
1023 /** True if object is a non-complex integer. */
1024 bool numeric::is_integer() const
1026 return cln::instanceof(value, cln::cl_I_ring);
1030 /** True if object is an exact integer greater than zero. */
1031 bool numeric::is_pos_integer() const
1033 return (cln::instanceof(value, cln::cl_I_ring) && cln::plusp(cln::the<cln::cl_I>(value)));
1037 /** True if object is an exact integer greater or equal zero. */
1038 bool numeric::is_nonneg_integer() const
1040 return (cln::instanceof(value, cln::cl_I_ring) && !cln::minusp(cln::the<cln::cl_I>(value)));
1044 /** True if object is an exact even integer. */
1045 bool numeric::is_even() const
1047 return (cln::instanceof(value, cln::cl_I_ring) && cln::evenp(cln::the<cln::cl_I>(value)));
1051 /** True if object is an exact odd integer. */
1052 bool numeric::is_odd() const
1054 return (cln::instanceof(value, cln::cl_I_ring) && cln::oddp(cln::the<cln::cl_I>(value)));
1058 /** Probabilistic primality test.
1060 * @return true if object is exact integer and prime. */
1061 bool numeric::is_prime() const
1063 return (cln::instanceof(value, cln::cl_I_ring) // integer?
1064 && cln::plusp(cln::the<cln::cl_I>(value)) // positive?
1065 && cln::isprobprime(cln::the<cln::cl_I>(value)));
1069 /** True if object is an exact rational number, may even be complex
1070 * (denominator may be unity). */
1071 bool numeric::is_rational() const
1073 return cln::instanceof(value, cln::cl_RA_ring);
1077 /** True if object is a real integer, rational or float (but not complex). */
1078 bool numeric::is_real() const
1080 return cln::instanceof(value, cln::cl_R_ring);
1084 bool numeric::operator==(const numeric &other) const
1086 return cln::equal(value, other.value);
1090 bool numeric::operator!=(const numeric &other) const
1092 return !cln::equal(value, other.value);
1096 /** True if object is element of the domain of integers extended by I, i.e. is
1097 * of the form a+b*I, where a and b are integers. */
1098 bool numeric::is_cinteger() const
1100 if (cln::instanceof(value, cln::cl_I_ring))
1102 else if (!this->is_real()) { // complex case, handle n+m*I
1103 if (cln::instanceof(cln::realpart(value), cln::cl_I_ring) &&
1104 cln::instanceof(cln::imagpart(value), cln::cl_I_ring))
1111 /** True if object is an exact rational number, may even be complex
1112 * (denominator may be unity). */
1113 bool numeric::is_crational() const
1115 if (cln::instanceof(value, cln::cl_RA_ring))
1117 else if (!this->is_real()) { // complex case, handle Q(i):
1118 if (cln::instanceof(cln::realpart(value), cln::cl_RA_ring) &&
1119 cln::instanceof(cln::imagpart(value), cln::cl_RA_ring))
1126 /** Numerical comparison: less.
1128 * @exception invalid_argument (complex inequality) */
1129 bool numeric::operator<(const numeric &other) const
1131 if (this->is_real() && other.is_real())
1132 return (cln::the<cln::cl_R>(value) < cln::the<cln::cl_R>(other.value));
1133 throw std::invalid_argument("numeric::operator<(): complex inequality");
1137 /** Numerical comparison: less or equal.
1139 * @exception invalid_argument (complex inequality) */
1140 bool numeric::operator<=(const numeric &other) const
1142 if (this->is_real() && other.is_real())
1143 return (cln::the<cln::cl_R>(value) <= cln::the<cln::cl_R>(other.value));
1144 throw std::invalid_argument("numeric::operator<=(): complex inequality");
1148 /** Numerical comparison: greater.
1150 * @exception invalid_argument (complex inequality) */
1151 bool numeric::operator>(const numeric &other) const
1153 if (this->is_real() && other.is_real())
1154 return (cln::the<cln::cl_R>(value) > cln::the<cln::cl_R>(other.value));
1155 throw std::invalid_argument("numeric::operator>(): complex inequality");
1159 /** Numerical comparison: greater or equal.
1161 * @exception invalid_argument (complex inequality) */
1162 bool numeric::operator>=(const numeric &other) const
1164 if (this->is_real() && other.is_real())
1165 return (cln::the<cln::cl_R>(value) >= cln::the<cln::cl_R>(other.value));
1166 throw std::invalid_argument("numeric::operator>=(): complex inequality");
1170 /** Converts numeric types to machine's int. You should check with
1171 * is_integer() if the number is really an integer before calling this method.
1172 * You may also consider checking the range first. */
1173 int numeric::to_int() const
1175 GINAC_ASSERT(this->is_integer());
1176 return cln::cl_I_to_int(cln::the<cln::cl_I>(value));
1180 /** Converts numeric types to machine's long. You should check with
1181 * is_integer() if the number is really an integer before calling this method.
1182 * You may also consider checking the range first. */
1183 long numeric::to_long() const
1185 GINAC_ASSERT(this->is_integer());
1186 return cln::cl_I_to_long(cln::the<cln::cl_I>(value));
1190 /** Converts numeric types to machine's double. You should check with is_real()
1191 * if the number is really not complex before calling this method. */
1192 double numeric::to_double() const
1194 GINAC_ASSERT(this->is_real());
1195 return cln::double_approx(cln::realpart(value));
1199 /** Returns a new CLN object of type cl_N, representing the value of *this.
1200 * This method may be used when mixing GiNaC and CLN in one project.
1202 cln::cl_N numeric::to_cl_N() const
1208 /** Real part of a number. */
1209 const numeric numeric::real() const
1211 return numeric(cln::realpart(value));
1215 /** Imaginary part of a number. */
1216 const numeric numeric::imag() const
1218 return numeric(cln::imagpart(value));
1222 /** Numerator. Computes the numerator of rational numbers, rationalized
1223 * numerator of complex if real and imaginary part are both rational numbers
1224 * (i.e numer(4/3+5/6*I) == 8+5*I), the number carrying the sign in all other
1226 const numeric numeric::numer() const
1228 if (cln::instanceof(value, cln::cl_I_ring))
1229 return numeric(*this); // integer case
1231 else if (cln::instanceof(value, cln::cl_RA_ring))
1232 return numeric(cln::numerator(cln::the<cln::cl_RA>(value)));
1234 else if (!this->is_real()) { // complex case, handle Q(i):
1235 const cln::cl_RA r = cln::the<cln::cl_RA>(cln::realpart(value));
1236 const cln::cl_RA i = cln::the<cln::cl_RA>(cln::imagpart(value));
1237 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_I_ring))
1238 return numeric(*this);
1239 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_RA_ring))
1240 return numeric(cln::complex(r*cln::denominator(i), cln::numerator(i)));
1241 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_I_ring))
1242 return numeric(cln::complex(cln::numerator(r), i*cln::denominator(r)));
1243 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_RA_ring)) {
1244 const cln::cl_I s = cln::lcm(cln::denominator(r), cln::denominator(i));
1245 return numeric(cln::complex(cln::numerator(r)*(cln::exquo(s,cln::denominator(r))),
1246 cln::numerator(i)*(cln::exquo(s,cln::denominator(i)))));
1249 // at least one float encountered
1250 return numeric(*this);
1254 /** Denominator. Computes the denominator of rational numbers, common integer
1255 * denominator of complex if real and imaginary part are both rational numbers
1256 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
1257 const numeric numeric::denom() const
1259 if (cln::instanceof(value, cln::cl_I_ring))
1260 return *_num1_p; // integer case
1262 if (cln::instanceof(value, cln::cl_RA_ring))
1263 return numeric(cln::denominator(cln::the<cln::cl_RA>(value)));
1265 if (!this->is_real()) { // complex case, handle Q(i):
1266 const cln::cl_RA r = cln::the<cln::cl_RA>(cln::realpart(value));
1267 const cln::cl_RA i = cln::the<cln::cl_RA>(cln::imagpart(value));
1268 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_I_ring))
1270 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_RA_ring))
1271 return numeric(cln::denominator(i));
1272 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_I_ring))
1273 return numeric(cln::denominator(r));
1274 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_RA_ring))
1275 return numeric(cln::lcm(cln::denominator(r), cln::denominator(i)));
1277 // at least one float encountered
1282 /** Size in binary notation. For integers, this is the smallest n >= 0 such
1283 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
1284 * 2^(n-1) <= x < 2^n.
1286 * @return number of bits (excluding sign) needed to represent that number
1287 * in two's complement if it is an integer, 0 otherwise. */
1288 int numeric::int_length() const
1290 if (cln::instanceof(value, cln::cl_I_ring))
1291 return cln::integer_length(cln::the<cln::cl_I>(value));
1300 /** Imaginary unit. This is not a constant but a numeric since we are
1301 * natively handing complex numbers anyways, so in each expression containing
1302 * an I it is automatically eval'ed away anyhow. */
1303 const numeric I = numeric(cln::complex(cln::cl_I(0),cln::cl_I(1)));
1306 /** Exponential function.
1308 * @return arbitrary precision numerical exp(x). */
1309 const numeric exp(const numeric &x)
1311 return cln::exp(x.to_cl_N());
1315 /** Natural logarithm.
1317 * @param x complex number
1318 * @return arbitrary precision numerical log(x).
1319 * @exception pole_error("log(): logarithmic pole",0) */
1320 const numeric log(const numeric &x)
1323 throw pole_error("log(): logarithmic pole",0);
1324 return cln::log(x.to_cl_N());
1328 /** Numeric sine (trigonometric function).
1330 * @return arbitrary precision numerical sin(x). */
1331 const numeric sin(const numeric &x)
1333 return cln::sin(x.to_cl_N());
1337 /** Numeric cosine (trigonometric function).
1339 * @return arbitrary precision numerical cos(x). */
1340 const numeric cos(const numeric &x)
1342 return cln::cos(x.to_cl_N());
1346 /** Numeric tangent (trigonometric function).
1348 * @return arbitrary precision numerical tan(x). */
1349 const numeric tan(const numeric &x)
1351 return cln::tan(x.to_cl_N());
1355 /** Numeric inverse sine (trigonometric function).
1357 * @return arbitrary precision numerical asin(x). */
1358 const numeric asin(const numeric &x)
1360 return cln::asin(x.to_cl_N());
1364 /** Numeric inverse cosine (trigonometric function).
1366 * @return arbitrary precision numerical acos(x). */
1367 const numeric acos(const numeric &x)
1369 return cln::acos(x.to_cl_N());
1373 /** Numeric arcustangent.
1375 * @param x complex number
1377 * @exception pole_error("atan(): logarithmic pole",0) if x==I or x==-I. */
1378 const numeric atan(const numeric &x)
1381 x.real().is_zero() &&
1382 abs(x.imag()).is_equal(*_num1_p))
1383 throw pole_error("atan(): logarithmic pole",0);
1384 return cln::atan(x.to_cl_N());
1388 /** Numeric arcustangent of two arguments, analytically continued in a suitable way.
1390 * @param y complex number
1391 * @param x complex number
1392 * @return -I*log((x+I*y)/sqrt(x^2+y^2)), which is equal to atan(y/x) if y and
1394 * @exception pole_error("atan(): logarithmic pole",0) if y/x==+I or y/x==-I. */
1395 const numeric atan(const numeric &y, const numeric &x)
1397 if (x.is_zero() && y.is_zero())
1399 if (x.is_real() && y.is_real())
1400 return cln::atan(cln::the<cln::cl_R>(x.to_cl_N()),
1401 cln::the<cln::cl_R>(y.to_cl_N()));
1403 // Compute -I*log((x+I*y)/sqrt(x^2+y^2))
1404 // == -I*log((x+I*y)/sqrt((x+I*y)*(x-I*y)))
1405 // Do not "simplify" this to -I/2*log((x+I*y)/(x-I*y))) or likewise.
1406 // The branch cuts are easily messed up.
1407 const cln::cl_N aux_p = x.to_cl_N()+cln::complex(0,1)*y.to_cl_N();
1408 if (cln::zerop(aux_p)) {
1409 // x+I*y==0 => y/x==I, so this is a pole (we have x!=0).
1410 throw pole_error("atan(): logarithmic pole",0);
1412 const cln::cl_N aux_m = x.to_cl_N()-cln::complex(0,1)*y.to_cl_N();
1413 if (cln::zerop(aux_m)) {
1414 // x-I*y==0 => y/x==-I, so this is a pole (we have x!=0).
1415 throw pole_error("atan(): logarithmic pole",0);
1417 return cln::complex(0,-1)*cln::log(aux_p/cln::sqrt(aux_p*aux_m));
1421 /** Numeric hyperbolic sine (trigonometric function).
1423 * @return arbitrary precision numerical sinh(x). */
1424 const numeric sinh(const numeric &x)
1426 return cln::sinh(x.to_cl_N());
1430 /** Numeric hyperbolic cosine (trigonometric function).
1432 * @return arbitrary precision numerical cosh(x). */
1433 const numeric cosh(const numeric &x)
1435 return cln::cosh(x.to_cl_N());
1439 /** Numeric hyperbolic tangent (trigonometric function).
1441 * @return arbitrary precision numerical tanh(x). */
1442 const numeric tanh(const numeric &x)
1444 return cln::tanh(x.to_cl_N());
1448 /** Numeric inverse hyperbolic sine (trigonometric function).
1450 * @return arbitrary precision numerical asinh(x). */
1451 const numeric asinh(const numeric &x)
1453 return cln::asinh(x.to_cl_N());
1457 /** Numeric inverse hyperbolic cosine (trigonometric function).
1459 * @return arbitrary precision numerical acosh(x). */
1460 const numeric acosh(const numeric &x)
1462 return cln::acosh(x.to_cl_N());
1466 /** Numeric inverse hyperbolic tangent (trigonometric function).
1468 * @return arbitrary precision numerical atanh(x). */
1469 const numeric atanh(const numeric &x)
1471 return cln::atanh(x.to_cl_N());
1475 /*static cln::cl_N Li2_series(const ::cl_N &x,
1476 const ::float_format_t &prec)
1478 // Note: argument must be in the unit circle
1479 // This is very inefficient unless we have fast floating point Bernoulli
1480 // numbers implemented!
1481 cln::cl_N c1 = -cln::log(1-x);
1483 // hard-wire the first two Bernoulli numbers
1484 cln::cl_N acc = c1 - cln::square(c1)/4;
1486 cln::cl_F pisq = cln::square(cln::cl_pi(prec)); // pi^2
1487 cln::cl_F piac = cln::cl_float(1, prec); // accumulator: pi^(2*i)
1489 c1 = cln::square(c1);
1493 aug = c2 * (*(bernoulli(numeric(2*i)).clnptr())) / cln::factorial(2*i+1);
1494 // 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));
1497 } while (acc != acc+aug);
1501 /** Numeric evaluation of Dilogarithm within circle of convergence (unit
1502 * circle) using a power series. */
1503 static cln::cl_N Li2_series(const cln::cl_N &x,
1504 const cln::float_format_t &prec)
1506 // Note: argument must be in the unit circle
1508 cln::cl_N num = cln::complex(cln::cl_float(1, prec), 0);
1513 den = den + i; // 1, 4, 9, 16, ...
1517 } while (acc != acc+aug);
1521 /** Folds Li2's argument inside a small rectangle to enhance convergence. */
1522 static cln::cl_N Li2_projection(const cln::cl_N &x,
1523 const cln::float_format_t &prec)
1525 const cln::cl_R re = cln::realpart(x);
1526 const cln::cl_R im = cln::imagpart(x);
1527 if (re > cln::cl_F(".5"))
1528 // zeta(2) - Li2(1-x) - log(x)*log(1-x)
1530 - Li2_series(1-x, prec)
1531 - cln::log(x)*cln::log(1-x));
1532 if ((re <= 0 && cln::abs(im) > cln::cl_F(".75")) || (re < cln::cl_F("-.5")))
1533 // -log(1-x)^2 / 2 - Li2(x/(x-1))
1534 return(- cln::square(cln::log(1-x))/2
1535 - Li2_series(x/(x-1), prec));
1536 if (re > 0 && cln::abs(im) > cln::cl_LF(".75"))
1537 // Li2(x^2)/2 - Li2(-x)
1538 return(Li2_projection(cln::square(x), prec)/2
1539 - Li2_projection(-x, prec));
1540 return Li2_series(x, prec);
1543 /** Numeric evaluation of Dilogarithm. The domain is the entire complex plane,
1544 * the branch cut lies along the positive real axis, starting at 1 and
1545 * continuous with quadrant IV.
1547 * @return arbitrary precision numerical Li2(x). */
1548 const numeric Li2(const numeric &x)
1553 // what is the desired float format?
1554 // first guess: default format
1555 cln::float_format_t prec = cln::default_float_format;
1556 const cln::cl_N value = x.to_cl_N();
1557 // second guess: the argument's format
1558 if (!x.real().is_rational())
1559 prec = cln::float_format(cln::the<cln::cl_F>(cln::realpart(value)));
1560 else if (!x.imag().is_rational())
1561 prec = cln::float_format(cln::the<cln::cl_F>(cln::imagpart(value)));
1563 if (value==1) // may cause trouble with log(1-x)
1564 return cln::zeta(2, prec);
1566 if (cln::abs(value) > 1)
1567 // -log(-x)^2 / 2 - zeta(2) - Li2(1/x)
1568 return(- cln::square(cln::log(-value))/2
1569 - cln::zeta(2, prec)
1570 - Li2_projection(cln::recip(value), prec));
1572 return Li2_projection(x.to_cl_N(), prec);
1576 /** Numeric evaluation of Riemann's Zeta function. Currently works only for
1577 * integer arguments. */
1578 const numeric zeta(const numeric &x)
1580 // A dirty hack to allow for things like zeta(3.0), since CLN currently
1581 // only knows about integer arguments and zeta(3).evalf() automatically
1582 // cascades down to zeta(3.0).evalf(). The trick is to rely on 3.0-3
1583 // being an exact zero for CLN, which can be tested and then we can just
1584 // pass the number casted to an int:
1586 const int aux = (int)(cln::double_approx(cln::the<cln::cl_R>(x.to_cl_N())));
1587 if (cln::zerop(x.to_cl_N()-aux))
1588 return cln::zeta(aux);
1594 /** The Gamma function.
1595 * This is only a stub! */
1596 const numeric lgamma(const numeric &x)
1600 const numeric tgamma(const numeric &x)
1606 /** The psi function (aka polygamma function).
1607 * This is only a stub! */
1608 const numeric psi(const numeric &x)
1614 /** The psi functions (aka polygamma functions).
1615 * This is only a stub! */
1616 const numeric psi(const numeric &n, const numeric &x)
1622 /** Factorial combinatorial function.
1624 * @param n integer argument >= 0
1625 * @exception range_error (argument must be integer >= 0) */
1626 const numeric factorial(const numeric &n)
1628 if (!n.is_nonneg_integer())
1629 throw std::range_error("numeric::factorial(): argument must be integer >= 0");
1630 return numeric(cln::factorial(n.to_int()));
1634 /** The double factorial combinatorial function. (Scarcely used, but still
1635 * useful in cases, like for exact results of tgamma(n+1/2) for instance.)
1637 * @param n integer argument >= -1
1638 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == (-1)!! == 1
1639 * @exception range_error (argument must be integer >= -1) */
1640 const numeric doublefactorial(const numeric &n)
1642 if (n.is_equal(*_num_1_p))
1645 if (!n.is_nonneg_integer())
1646 throw std::range_error("numeric::doublefactorial(): argument must be integer >= -1");
1648 return numeric(cln::doublefactorial(n.to_int()));
1652 /** The Binomial coefficients. It computes the binomial coefficients. For
1653 * integer n and k and positive n this is the number of ways of choosing k
1654 * objects from n distinct objects. If n is negative, the formula
1655 * binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */
1656 const numeric binomial(const numeric &n, const numeric &k)
1658 if (n.is_integer() && k.is_integer()) {
1659 if (n.is_nonneg_integer()) {
1660 if (k.compare(n)!=1 && k.compare(*_num0_p)!=-1)
1661 return numeric(cln::binomial(n.to_int(),k.to_int()));
1665 return _num_1_p->power(k)*binomial(k-n-(*_num1_p),k);
1669 // should really be gamma(n+1)/gamma(k+1)/gamma(n-k+1) or a suitable limit
1670 throw std::range_error("numeric::binomial(): don't know how to evaluate that.");
1674 /** Bernoulli number. The nth Bernoulli number is the coefficient of x^n/n!
1675 * in the expansion of the function x/(e^x-1).
1677 * @return the nth Bernoulli number (a rational number).
1678 * @exception range_error (argument must be integer >= 0) */
1679 const numeric bernoulli(const numeric &nn)
1681 if (!nn.is_integer() || nn.is_negative())
1682 throw std::range_error("numeric::bernoulli(): argument must be integer >= 0");
1686 // The Bernoulli numbers are rational numbers that may be computed using
1689 // B_n = - 1/(n+1) * sum_{k=0}^{n-1}(binomial(n+1,k)*B_k)
1691 // with B(0) = 1. Since the n'th Bernoulli number depends on all the
1692 // previous ones, the computation is necessarily very expensive. There are
1693 // several other ways of computing them, a particularly good one being
1697 // for (unsigned i=0; i<n; i++) {
1698 // c = exquo(c*(i-n),(i+2));
1699 // Bern = Bern + c*s/(i+2);
1700 // s = s + expt_pos(cl_I(i+2),n);
1704 // But if somebody works with the n'th Bernoulli number she is likely to
1705 // also need all previous Bernoulli numbers. So we need a complete remember
1706 // table and above divide and conquer algorithm is not suited to build one
1707 // up. The formula below accomplishes this. It is a modification of the
1708 // defining formula above but the computation of the binomial coefficients
1709 // is carried along in an inline fashion. It also honors the fact that
1710 // B_n is zero when n is odd and greater than 1.
1712 // (There is an interesting relation with the tangent polynomials described
1713 // in `Concrete Mathematics', which leads to a program a little faster as
1714 // our implementation below, but it requires storing one such polynomial in
1715 // addition to the remember table. This doubles the memory footprint so
1716 // we don't use it.)
1718 const unsigned n = nn.to_int();
1720 // the special cases not covered by the algorithm below
1722 return (n==1) ? (*_num_1_2_p) : (*_num0_p);
1726 // store nonvanishing Bernoulli numbers here
1727 static std::vector< cln::cl_RA > results;
1728 static unsigned next_r = 0;
1730 // algorithm not applicable to B(2), so just store it
1732 results.push_back(cln::recip(cln::cl_RA(6)));
1736 return results[n/2-1];
1738 results.reserve(n/2);
1739 for (unsigned p=next_r; p<=n; p+=2) {
1740 cln::cl_I c = 1; // seed for binonmial coefficients
1741 cln::cl_RA b = cln::cl_RA(p-1)/-2;
1742 const unsigned p3 = p+3;
1743 const unsigned pm = p-2;
1745 // test if intermediate unsigned int can be represented by immediate
1746 // objects by CLN (i.e. < 2^29 for 32 Bit machines, see <cln/object.h>)
1747 if (p < (1UL<<cl_value_len/2)) {
1748 for (i=2, k=1, p_2=p/2; i<=pm; i+=2, ++k, --p_2) {
1749 c = cln::exquo(c * ((p3-i) * p_2), (i-1)*k);
1750 b = b + c*results[k-1];
1753 for (i=2, k=1, p_2=p/2; i<=pm; i+=2, ++k, --p_2) {
1754 c = cln::exquo((c * (p3-i)) * p_2, cln::cl_I(i-1)*k);
1755 b = b + c*results[k-1];
1758 results.push_back(-b/(p+1));
1761 return results[n/2-1];
1765 /** Fibonacci number. The nth Fibonacci number F(n) is defined by the
1766 * recurrence formula F(n)==F(n-1)+F(n-2) with F(0)==0 and F(1)==1.
1768 * @param n an integer
1769 * @return the nth Fibonacci number F(n) (an integer number)
1770 * @exception range_error (argument must be an integer) */
1771 const numeric fibonacci(const numeric &n)
1773 if (!n.is_integer())
1774 throw std::range_error("numeric::fibonacci(): argument must be integer");
1777 // The following addition formula holds:
1779 // F(n+m) = F(m-1)*F(n) + F(m)*F(n+1) for m >= 1, n >= 0.
1781 // (Proof: For fixed m, the LHS and the RHS satisfy the same recurrence
1782 // w.r.t. n, and the initial values (n=0, n=1) agree. Hence all values
1784 // Replace m by m+1:
1785 // F(n+m+1) = F(m)*F(n) + F(m+1)*F(n+1) for m >= 0, n >= 0
1786 // Now put in m = n, to get
1787 // F(2n) = (F(n+1)-F(n))*F(n) + F(n)*F(n+1) = F(n)*(2*F(n+1) - F(n))
1788 // F(2n+1) = F(n)^2 + F(n+1)^2
1790 // F(2n+2) = F(n+1)*(2*F(n) + F(n+1))
1793 if (n.is_negative())
1795 return -fibonacci(-n);
1797 return fibonacci(-n);
1801 cln::cl_I m = cln::the<cln::cl_I>(n.to_cl_N()) >> 1L; // floor(n/2);
1802 for (uintL bit=cln::integer_length(m); bit>0; --bit) {
1803 // Since a squaring is cheaper than a multiplication, better use
1804 // three squarings instead of one multiplication and two squarings.
1805 cln::cl_I u2 = cln::square(u);
1806 cln::cl_I v2 = cln::square(v);
1807 if (cln::logbitp(bit-1, m)) {
1808 v = cln::square(u + v) - u2;
1811 u = v2 - cln::square(v - u);
1816 // Here we don't use the squaring formula because one multiplication
1817 // is cheaper than two squarings.
1818 return u * ((v << 1) - u);
1820 return cln::square(u) + cln::square(v);
1824 /** Absolute value. */
1825 const numeric abs(const numeric& x)
1827 return cln::abs(x.to_cl_N());
1831 /** Modulus (in positive representation).
1832 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1833 * sign of a or is zero. This is different from Maple's modp, where the sign
1834 * of b is ignored. It is in agreement with Mathematica's Mod.
1836 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1837 * integer, 0 otherwise. */
1838 const numeric mod(const numeric &a, const numeric &b)
1840 if (a.is_integer() && b.is_integer())
1841 return cln::mod(cln::the<cln::cl_I>(a.to_cl_N()),
1842 cln::the<cln::cl_I>(b.to_cl_N()));
1848 /** Modulus (in symmetric representation).
1849 * Equivalent to Maple's mods.
1851 * @return a mod b in the range [-iquo(abs(b)-1,2), iquo(abs(b),2)]. */
1852 const numeric smod(const numeric &a, const numeric &b)
1854 if (a.is_integer() && b.is_integer()) {
1855 const cln::cl_I b2 = cln::ceiling1(cln::the<cln::cl_I>(b.to_cl_N()) >> 1) - 1;
1856 return cln::mod(cln::the<cln::cl_I>(a.to_cl_N()) + b2,
1857 cln::the<cln::cl_I>(b.to_cl_N())) - b2;
1863 /** Numeric integer remainder.
1864 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1865 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1866 * sign of a or is zero.
1868 * @return remainder of a/b if both are integer, 0 otherwise.
1869 * @exception overflow_error (division by zero) if b is zero. */
1870 const numeric irem(const numeric &a, const numeric &b)
1873 throw std::overflow_error("numeric::irem(): division by zero");
1874 if (a.is_integer() && b.is_integer())
1875 return cln::rem(cln::the<cln::cl_I>(a.to_cl_N()),
1876 cln::the<cln::cl_I>(b.to_cl_N()));
1882 /** Numeric integer remainder.
1883 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1884 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1885 * and irem(a,b) has the sign of a or is zero.
1887 * @return remainder of a/b and quotient stored in q if both are integer,
1889 * @exception overflow_error (division by zero) if b is zero. */
1890 const numeric irem(const numeric &a, const numeric &b, numeric &q)
1893 throw std::overflow_error("numeric::irem(): division by zero");
1894 if (a.is_integer() && b.is_integer()) {
1895 const cln::cl_I_div_t rem_quo = cln::truncate2(cln::the<cln::cl_I>(a.to_cl_N()),
1896 cln::the<cln::cl_I>(b.to_cl_N()));
1897 q = rem_quo.quotient;
1898 return rem_quo.remainder;
1906 /** Numeric integer quotient.
1907 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1909 * @return truncated quotient of a/b if both are integer, 0 otherwise.
1910 * @exception overflow_error (division by zero) if b is zero. */
1911 const numeric iquo(const numeric &a, const numeric &b)
1914 throw std::overflow_error("numeric::iquo(): division by zero");
1915 if (a.is_integer() && b.is_integer())
1916 return cln::truncate1(cln::the<cln::cl_I>(a.to_cl_N()),
1917 cln::the<cln::cl_I>(b.to_cl_N()));
1923 /** Numeric integer quotient.
1924 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1925 * r == a - iquo(a,b,r)*b.
1927 * @return truncated quotient of a/b and remainder stored in r if both are
1928 * integer, 0 otherwise.
1929 * @exception overflow_error (division by zero) if b is zero. */
1930 const numeric iquo(const numeric &a, const numeric &b, numeric &r)
1933 throw std::overflow_error("numeric::iquo(): division by zero");
1934 if (a.is_integer() && b.is_integer()) {
1935 const cln::cl_I_div_t rem_quo = cln::truncate2(cln::the<cln::cl_I>(a.to_cl_N()),
1936 cln::the<cln::cl_I>(b.to_cl_N()));
1937 r = rem_quo.remainder;
1938 return rem_quo.quotient;
1946 /** Greatest Common Divisor.
1948 * @return The GCD of two numbers if both are integer, a numerical 1
1949 * if they are not. */
1950 const numeric gcd(const numeric &a, const numeric &b)
1952 if (a.is_integer() && b.is_integer())
1953 return cln::gcd(cln::the<cln::cl_I>(a.to_cl_N()),
1954 cln::the<cln::cl_I>(b.to_cl_N()));
1960 /** Least Common Multiple.
1962 * @return The LCM of two numbers if both are integer, the product of those
1963 * two numbers if they are not. */
1964 const numeric lcm(const numeric &a, const numeric &b)
1966 if (a.is_integer() && b.is_integer())
1967 return cln::lcm(cln::the<cln::cl_I>(a.to_cl_N()),
1968 cln::the<cln::cl_I>(b.to_cl_N()));
1974 /** Numeric square root.
1975 * If possible, sqrt(x) should respect squares of exact numbers, i.e. sqrt(4)
1976 * should return integer 2.
1978 * @param x numeric argument
1979 * @return square root of x. Branch cut along negative real axis, the negative
1980 * real axis itself where imag(x)==0 and real(x)<0 belongs to the upper part
1981 * where imag(x)>0. */
1982 const numeric sqrt(const numeric &x)
1984 return cln::sqrt(x.to_cl_N());
1988 /** Integer numeric square root. */
1989 const numeric isqrt(const numeric &x)
1991 if (x.is_integer()) {
1993 cln::isqrt(cln::the<cln::cl_I>(x.to_cl_N()), &root);
2000 /** Floating point evaluation of Archimedes' constant Pi. */
2003 return numeric(cln::pi(cln::default_float_format));
2007 /** Floating point evaluation of Euler's constant gamma. */
2010 return numeric(cln::eulerconst(cln::default_float_format));
2014 /** Floating point evaluation of Catalan's constant. */
2017 return numeric(cln::catalanconst(cln::default_float_format));
2021 /** _numeric_digits default ctor, checking for singleton invariance. */
2022 _numeric_digits::_numeric_digits()
2025 // It initializes to 17 digits, because in CLN float_format(17) turns out
2026 // to be 61 (<64) while float_format(18)=65. The reason is we want to
2027 // have a cl_LF instead of cl_SF, cl_FF or cl_DF.
2029 throw(std::runtime_error("I told you not to do instantiate me!"));
2031 cln::default_float_format = cln::float_format(17);
2035 /** Assign a native long to global Digits object. */
2036 _numeric_digits& _numeric_digits::operator=(long prec)
2039 cln::default_float_format = cln::float_format(prec);
2044 /** Convert global Digits object to native type long. */
2045 _numeric_digits::operator long()
2047 // BTW, this is approx. unsigned(cln::default_float_format*0.301)-1
2048 return (long)digits;
2052 /** Append global Digits object to ostream. */
2053 void _numeric_digits::print(std::ostream &os) const
2059 std::ostream& operator<<(std::ostream &os, const _numeric_digits &e)
2066 // static member variables
2071 bool _numeric_digits::too_late = false;
2074 /** Accuracy in decimal digits. Only object of this type! Can be set using
2075 * assignment from C++ unsigned ints and evaluated like any built-in type. */
2076 _numeric_digits Digits;
2078 } // namespace GiNaC