3 * This file contains the interface to the underlying bignum package.
4 * Its most important design principle is to completely hide the inner
5 * working of that other package from the user of GiNaC. It must either
6 * provide implementation of arithmetic operators and numerical evaluation
7 * of special functions or implement the interface to the bignum package. */
10 * GiNaC Copyright (C) 1999-2003 Johannes Gutenberg University Mainz, Germany
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
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);
245 numeric::numeric(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
247 cln::cl_N ctorval = 0;
249 // Read number as string
251 if (n.find_string("number", str)) {
252 std::istringstream s(str);
253 cln::cl_idecoded_float re, im;
257 case 'R': // Integer-decoded real number
258 s >> re.sign >> re.mantissa >> re.exponent;
259 ctorval = re.sign * re.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), re.exponent);
261 case 'C': // Integer-decoded complex number
262 s >> re.sign >> re.mantissa >> re.exponent;
263 s >> im.sign >> im.mantissa >> im.exponent;
264 ctorval = cln::complex(re.sign * re.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), re.exponent),
265 im.sign * im.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), im.exponent));
267 default: // Ordinary number
274 setflag(status_flags::evaluated | status_flags::expanded);
277 void numeric::archive(archive_node &n) const
279 inherited::archive(n);
281 // Write number as string
282 std::ostringstream s;
283 if (this->is_crational())
284 s << cln::the<cln::cl_N>(value);
286 // Non-rational numbers are written in an integer-decoded format
287 // to preserve the precision
288 if (this->is_real()) {
289 cln::cl_idecoded_float re = cln::integer_decode_float(cln::the<cln::cl_F>(value));
291 s << re.sign << " " << re.mantissa << " " << re.exponent;
293 cln::cl_idecoded_float re = cln::integer_decode_float(cln::the<cln::cl_F>(cln::realpart(cln::the<cln::cl_N>(value))));
294 cln::cl_idecoded_float im = cln::integer_decode_float(cln::the<cln::cl_F>(cln::imagpart(cln::the<cln::cl_N>(value))));
296 s << re.sign << " " << re.mantissa << " " << re.exponent << " ";
297 s << im.sign << " " << im.mantissa << " " << im.exponent;
300 n.add_string("number", s.str());
303 DEFAULT_UNARCHIVE(numeric)
306 // functions overriding virtual functions from base classes
309 /** Helper function to print a real number in a nicer way than is CLN's
310 * default. Instead of printing 42.0L0 this just prints 42.0 to ostream os
311 * and instead of 3.99168L7 it prints 3.99168E7. This is fine in GiNaC as
312 * long as it only uses cl_LF and no other floating point types that we might
313 * want to visibly distinguish from cl_LF.
315 * @see numeric::print() */
316 static void print_real_number(const print_context & c, const cln::cl_R & x)
318 cln::cl_print_flags ourflags;
319 if (cln::instanceof(x, cln::cl_RA_ring)) {
320 // case 1: integer or rational
321 if (cln::instanceof(x, cln::cl_I_ring) ||
322 !is_a<print_latex>(c)) {
323 cln::print_real(c.s, ourflags, x);
324 } else { // rational output in LaTeX context
328 cln::print_real(c.s, ourflags, cln::abs(cln::numerator(cln::the<cln::cl_RA>(x))));
330 cln::print_real(c.s, ourflags, cln::denominator(cln::the<cln::cl_RA>(x)));
335 // make CLN believe this number has default_float_format, so it prints
336 // 'E' as exponent marker instead of 'L':
337 ourflags.default_float_format = cln::float_format(cln::the<cln::cl_F>(x));
338 cln::print_real(c.s, ourflags, x);
342 /** Helper function to print integer number in C++ source format.
344 * @see numeric::print() */
345 static void print_integer_csrc(const print_context & c, const cln::cl_I & x)
347 // Print small numbers in compact float format, but larger numbers in
349 const int max_cln_int = 536870911; // 2^29-1
350 if (x >= cln::cl_I(-max_cln_int) && x <= cln::cl_I(max_cln_int))
351 c.s << cln::cl_I_to_int(x) << ".0";
353 c.s << cln::double_approx(x);
356 /** Helper function to print real number in C++ source format.
358 * @see numeric::print() */
359 static void print_real_csrc(const print_context & c, const cln::cl_R & x)
361 if (cln::instanceof(x, cln::cl_I_ring)) {
364 print_integer_csrc(c, cln::the<cln::cl_I>(x));
366 } else if (cln::instanceof(x, cln::cl_RA_ring)) {
369 const cln::cl_I numer = cln::numerator(cln::the<cln::cl_RA>(x));
370 const cln::cl_I denom = cln::denominator(cln::the<cln::cl_RA>(x));
371 if (cln::plusp(x) > 0) {
373 print_integer_csrc(c, numer);
376 print_integer_csrc(c, -numer);
379 print_integer_csrc(c, denom);
385 c.s << cln::double_approx(x);
389 /** Helper function to print real number in C++ source format using cl_N types.
391 * @see numeric::print() */
392 static void print_real_cl_N(const print_context & c, const cln::cl_R & x)
394 if (cln::instanceof(x, cln::cl_I_ring)) {
397 c.s << "cln::cl_I(\"";
398 print_real_number(c, x);
401 } else if (cln::instanceof(x, cln::cl_RA_ring)) {
404 cln::cl_print_flags ourflags;
405 c.s << "cln::cl_RA(\"";
406 cln::print_rational(c.s, ourflags, cln::the<cln::cl_RA>(x));
412 c.s << "cln::cl_F(\"";
413 print_real_number(c, cln::cl_float(1.0, cln::default_float_format) * x);
414 c.s << "_" << Digits << "\")";
418 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
420 const cln::cl_R r = cln::realpart(cln::the<cln::cl_N>(value));
421 const cln::cl_R i = cln::imagpart(cln::the<cln::cl_N>(value));
425 // case 1, real: x or -x
426 if ((precedence() <= level) && (!this->is_nonneg_integer())) {
428 print_real_number(c, r);
431 print_real_number(c, r);
437 // case 2, imaginary: y*I or -y*I
441 if (precedence()<=level)
444 c.s << "-" << imag_sym;
446 print_real_number(c, i);
447 c.s << mul_sym << imag_sym;
449 if (precedence()<=level)
455 // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I
456 if (precedence() <= level)
458 print_real_number(c, r);
461 c.s << "-" << imag_sym;
463 print_real_number(c, i);
464 c.s << mul_sym << imag_sym;
468 c.s << "+" << imag_sym;
471 print_real_number(c, i);
472 c.s << mul_sym << imag_sym;
475 if (precedence() <= level)
481 void numeric::do_print(const print_context & c, unsigned level) const
483 print_numeric(c, "(", ")", "I", "*", level);
486 void numeric::do_print_latex(const print_latex & c, unsigned level) const
488 print_numeric(c, "{(", ")}", "i", " ", level);
491 void numeric::do_print_csrc(const print_csrc & c, unsigned level) const
493 std::ios::fmtflags oldflags = c.s.flags();
494 c.s.setf(std::ios::scientific);
495 int oldprec = c.s.precision();
498 if (is_a<print_csrc_double>(c))
499 c.s.precision(std::numeric_limits<double>::digits10 + 1);
501 c.s.precision(std::numeric_limits<float>::digits10 + 1);
503 if (this->is_real()) {
506 print_real_csrc(c, cln::the<cln::cl_R>(value));
511 c.s << "std::complex<";
512 if (is_a<print_csrc_double>(c))
517 print_real_csrc(c, cln::realpart(cln::the<cln::cl_N>(value)));
519 print_real_csrc(c, cln::imagpart(cln::the<cln::cl_N>(value)));
524 c.s.precision(oldprec);
527 void numeric::do_print_csrc_cl_N(const print_csrc_cl_N & c, unsigned level) const
529 if (this->is_real()) {
532 print_real_cl_N(c, cln::the<cln::cl_R>(value));
537 c.s << "cln::complex(";
538 print_real_cl_N(c, cln::realpart(cln::the<cln::cl_N>(value)));
540 print_real_cl_N(c, cln::imagpart(cln::the<cln::cl_N>(value)));
545 void numeric::do_print_tree(const print_tree & c, unsigned level) const
547 c.s << std::string(level, ' ') << cln::the<cln::cl_N>(value)
548 << " (" << class_name() << ")" << " @" << this
549 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
553 void numeric::do_print_python_repr(const print_python_repr & c, unsigned level) const
555 c.s << class_name() << "('";
556 print_numeric(c, "(", ")", "I", "*", level);
560 bool numeric::info(unsigned inf) const
563 case info_flags::numeric:
564 case info_flags::polynomial:
565 case info_flags::rational_function:
567 case info_flags::real:
569 case info_flags::rational:
570 case info_flags::rational_polynomial:
571 return is_rational();
572 case info_flags::crational:
573 case info_flags::crational_polynomial:
574 return is_crational();
575 case info_flags::integer:
576 case info_flags::integer_polynomial:
578 case info_flags::cinteger:
579 case info_flags::cinteger_polynomial:
580 return is_cinteger();
581 case info_flags::positive:
582 return is_positive();
583 case info_flags::negative:
584 return is_negative();
585 case info_flags::nonnegative:
586 return !is_negative();
587 case info_flags::posint:
588 return is_pos_integer();
589 case info_flags::negint:
590 return is_integer() && is_negative();
591 case info_flags::nonnegint:
592 return is_nonneg_integer();
593 case info_flags::even:
595 case info_flags::odd:
597 case info_flags::prime:
599 case info_flags::algebraic:
605 int numeric::degree(const ex & s) const
610 int numeric::ldegree(const ex & s) const
615 ex numeric::coeff(const ex & s, int n) const
617 return n==0 ? *this : _ex0;
620 /** Disassemble real part and imaginary part to scan for the occurrence of a
621 * single number. Also handles the imaginary unit. It ignores the sign on
622 * both this and the argument, which may lead to what might appear as funny
623 * results: (2+I).has(-2) -> true. But this is consistent, since we also
624 * would like to have (-2+I).has(2) -> true and we want to think about the
625 * sign as a multiplicative factor. */
626 bool numeric::has(const ex &other) const
628 if (!is_exactly_a<numeric>(other))
630 const numeric &o = ex_to<numeric>(other);
631 if (this->is_equal(o) || this->is_equal(-o))
633 if (o.imag().is_zero()) // e.g. scan for 3 in -3*I
634 return (this->real().is_equal(o) || this->imag().is_equal(o) ||
635 this->real().is_equal(-o) || this->imag().is_equal(-o));
637 if (o.is_equal(I)) // e.g scan for I in 42*I
638 return !this->is_real();
639 if (o.real().is_zero()) // e.g. scan for 2*I in 2*I+1
640 return (this->real().has(o*I) || this->imag().has(o*I) ||
641 this->real().has(-o*I) || this->imag().has(-o*I));
647 /** Evaluation of numbers doesn't do anything at all. */
648 ex numeric::eval(int level) const
650 // Warning: if this is ever gonna do something, the ex ctors from all kinds
651 // of numbers should be checking for status_flags::evaluated.
656 /** Cast numeric into a floating-point object. For example exact numeric(1) is
657 * returned as a 1.0000000000000000000000 and so on according to how Digits is
658 * currently set. In case the object already was a floating point number the
659 * precision is trimmed to match the currently set default.
661 * @param level ignored, only needed for overriding basic::evalf.
662 * @return an ex-handle to a numeric. */
663 ex numeric::evalf(int level) const
665 // level can safely be discarded for numeric objects.
666 return numeric(cln::cl_float(1.0, cln::default_float_format) *
667 (cln::the<cln::cl_N>(value)));
672 int numeric::compare_same_type(const basic &other) const
674 GINAC_ASSERT(is_exactly_a<numeric>(other));
675 const numeric &o = static_cast<const numeric &>(other);
677 return this->compare(o);
681 bool numeric::is_equal_same_type(const basic &other) const
683 GINAC_ASSERT(is_exactly_a<numeric>(other));
684 const numeric &o = static_cast<const numeric &>(other);
686 return this->is_equal(o);
690 unsigned numeric::calchash() const
692 // Base computation of hashvalue on CLN's hashcode. Note: That depends
693 // only on the number's value, not its type or precision (i.e. a true
694 // equivalence relation on numbers). As a consequence, 3 and 3.0 share
695 // the same hashvalue. That shouldn't really matter, though.
696 setflag(status_flags::hash_calculated);
697 hashvalue = golden_ratio_hash(cln::equal_hashcode(cln::the<cln::cl_N>(value)));
703 // new virtual functions which can be overridden by derived classes
709 // non-virtual functions in this class
714 /** Numerical addition method. Adds argument to *this and returns result as
715 * a numeric object. */
716 const numeric numeric::add(const numeric &other) const
718 return numeric(cln::the<cln::cl_N>(value)+cln::the<cln::cl_N>(other.value));
722 /** Numerical subtraction method. Subtracts argument from *this and returns
723 * result as a numeric object. */
724 const numeric numeric::sub(const numeric &other) const
726 return numeric(cln::the<cln::cl_N>(value)-cln::the<cln::cl_N>(other.value));
730 /** Numerical multiplication method. Multiplies *this and argument and returns
731 * result as a numeric object. */
732 const numeric numeric::mul(const numeric &other) const
734 return numeric(cln::the<cln::cl_N>(value)*cln::the<cln::cl_N>(other.value));
738 /** Numerical division method. Divides *this by argument and returns result as
741 * @exception overflow_error (division by zero) */
742 const numeric numeric::div(const numeric &other) const
744 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
745 throw std::overflow_error("numeric::div(): division by zero");
746 return numeric(cln::the<cln::cl_N>(value)/cln::the<cln::cl_N>(other.value));
750 /** Numerical exponentiation. Raises *this to the power given as argument and
751 * returns result as a numeric object. */
752 const numeric numeric::power(const numeric &other) const
754 // Shortcut for efficiency and numeric stability (as in 1.0 exponent):
755 // trap the neutral exponent.
756 if (&other==_num1_p || cln::equal(cln::the<cln::cl_N>(other.value),cln::the<cln::cl_N>(_num1.value)))
759 if (cln::zerop(cln::the<cln::cl_N>(value))) {
760 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
761 throw std::domain_error("numeric::eval(): pow(0,0) is undefined");
762 else if (cln::zerop(cln::realpart(cln::the<cln::cl_N>(other.value))))
763 throw std::domain_error("numeric::eval(): pow(0,I) is undefined");
764 else if (cln::minusp(cln::realpart(cln::the<cln::cl_N>(other.value))))
765 throw std::overflow_error("numeric::eval(): division by zero");
769 return numeric(cln::expt(cln::the<cln::cl_N>(value),cln::the<cln::cl_N>(other.value)));
774 /** Numerical addition method. Adds argument to *this and returns result as
775 * a numeric object on the heap. Use internally only for direct wrapping into
776 * an ex object, where the result would end up on the heap anyways. */
777 const numeric &numeric::add_dyn(const numeric &other) const
779 // Efficiency shortcut: trap the neutral element by pointer. This hack
780 // is supposed to keep the number of distinct numeric objects low.
783 else if (&other==_num0_p)
786 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)+cln::the<cln::cl_N>(other.value)))->
787 setflag(status_flags::dynallocated));
791 /** Numerical subtraction method. Subtracts argument from *this and returns
792 * result as a numeric object on the heap. Use internally only for direct
793 * wrapping into an ex object, where the result would end up on the heap
795 const numeric &numeric::sub_dyn(const numeric &other) const
797 // Efficiency shortcut: trap the neutral exponent (first by pointer). This
798 // hack is supposed to keep the number of distinct numeric objects low.
799 if (&other==_num0_p || cln::zerop(cln::the<cln::cl_N>(other.value)))
802 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)-cln::the<cln::cl_N>(other.value)))->
803 setflag(status_flags::dynallocated));
807 /** Numerical multiplication method. Multiplies *this and argument and returns
808 * result as a numeric object on the heap. Use internally only for direct
809 * wrapping into an ex object, where the result would end up on the heap
811 const numeric &numeric::mul_dyn(const numeric &other) const
813 // Efficiency shortcut: trap the neutral element by pointer. This hack
814 // is supposed to keep the number of distinct numeric objects low.
817 else if (&other==_num1_p)
820 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)*cln::the<cln::cl_N>(other.value)))->
821 setflag(status_flags::dynallocated));
825 /** Numerical division method. Divides *this by argument and returns result as
826 * a numeric object on the heap. Use internally only for direct wrapping
827 * into an ex object, where the result would end up on the heap
830 * @exception overflow_error (division by zero) */
831 const numeric &numeric::div_dyn(const numeric &other) const
833 // Efficiency shortcut: trap the neutral element by pointer. This hack
834 // is supposed to keep the number of distinct numeric objects low.
837 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
838 throw std::overflow_error("division by zero");
839 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)/cln::the<cln::cl_N>(other.value)))->
840 setflag(status_flags::dynallocated));
844 /** Numerical exponentiation. Raises *this to the power given as argument and
845 * returns result as a numeric object on the heap. Use internally only for
846 * direct wrapping into an ex object, where the result would end up on the
848 const numeric &numeric::power_dyn(const numeric &other) const
850 // Efficiency shortcut: trap the neutral exponent (first try by pointer, then
851 // try harder, since calls to cln::expt() below may return amazing results for
852 // floating point exponent 1.0).
853 if (&other==_num1_p || cln::equal(cln::the<cln::cl_N>(other.value),cln::the<cln::cl_N>(_num1.value)))
856 if (cln::zerop(cln::the<cln::cl_N>(value))) {
857 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
858 throw std::domain_error("numeric::eval(): pow(0,0) is undefined");
859 else if (cln::zerop(cln::realpart(cln::the<cln::cl_N>(other.value))))
860 throw std::domain_error("numeric::eval(): pow(0,I) is undefined");
861 else if (cln::minusp(cln::realpart(cln::the<cln::cl_N>(other.value))))
862 throw std::overflow_error("numeric::eval(): division by zero");
866 return static_cast<const numeric &>((new numeric(cln::expt(cln::the<cln::cl_N>(value),cln::the<cln::cl_N>(other.value))))->
867 setflag(status_flags::dynallocated));
871 const numeric &numeric::operator=(int i)
873 return operator=(numeric(i));
877 const numeric &numeric::operator=(unsigned int i)
879 return operator=(numeric(i));
883 const numeric &numeric::operator=(long i)
885 return operator=(numeric(i));
889 const numeric &numeric::operator=(unsigned long i)
891 return operator=(numeric(i));
895 const numeric &numeric::operator=(double d)
897 return operator=(numeric(d));
901 const numeric &numeric::operator=(const char * s)
903 return operator=(numeric(s));
907 /** Inverse of a number. */
908 const numeric numeric::inverse() const
910 if (cln::zerop(cln::the<cln::cl_N>(value)))
911 throw std::overflow_error("numeric::inverse(): division by zero");
912 return numeric(cln::recip(cln::the<cln::cl_N>(value)));
916 /** Return the complex half-plane (left or right) in which the number lies.
917 * csgn(x)==0 for x==0, csgn(x)==1 for Re(x)>0 or Re(x)=0 and Im(x)>0,
918 * csgn(x)==-1 for Re(x)<0 or Re(x)=0 and Im(x)<0.
920 * @see numeric::compare(const numeric &other) */
921 int numeric::csgn() const
923 if (cln::zerop(cln::the<cln::cl_N>(value)))
925 cln::cl_R r = cln::realpart(cln::the<cln::cl_N>(value));
926 if (!cln::zerop(r)) {
932 if (cln::plusp(cln::imagpart(cln::the<cln::cl_N>(value))))
940 /** This method establishes a canonical order on all numbers. For complex
941 * numbers this is not possible in a mathematically consistent way but we need
942 * to establish some order and it ought to be fast. So we simply define it
943 * to be compatible with our method csgn.
945 * @return csgn(*this-other)
946 * @see numeric::csgn() */
947 int numeric::compare(const numeric &other) const
949 // Comparing two real numbers?
950 if (cln::instanceof(value, cln::cl_R_ring) &&
951 cln::instanceof(other.value, cln::cl_R_ring))
952 // Yes, so just cln::compare them
953 return cln::compare(cln::the<cln::cl_R>(value), cln::the<cln::cl_R>(other.value));
955 // No, first cln::compare real parts...
956 cl_signean real_cmp = cln::compare(cln::realpart(cln::the<cln::cl_N>(value)), cln::realpart(cln::the<cln::cl_N>(other.value)));
959 // ...and then the imaginary parts.
960 return cln::compare(cln::imagpart(cln::the<cln::cl_N>(value)), cln::imagpart(cln::the<cln::cl_N>(other.value)));
965 bool numeric::is_equal(const numeric &other) const
967 return cln::equal(cln::the<cln::cl_N>(value),cln::the<cln::cl_N>(other.value));
971 /** True if object is zero. */
972 bool numeric::is_zero() const
974 return cln::zerop(cln::the<cln::cl_N>(value));
978 /** True if object is not complex and greater than zero. */
979 bool numeric::is_positive() const
981 if (cln::instanceof(value, cln::cl_R_ring)) // real?
982 return cln::plusp(cln::the<cln::cl_R>(value));
987 /** True if object is not complex and less than zero. */
988 bool numeric::is_negative() const
990 if (cln::instanceof(value, cln::cl_R_ring)) // real?
991 return cln::minusp(cln::the<cln::cl_R>(value));
996 /** True if object is a non-complex integer. */
997 bool numeric::is_integer() const
999 return cln::instanceof(value, cln::cl_I_ring);
1003 /** True if object is an exact integer greater than zero. */
1004 bool numeric::is_pos_integer() const
1006 return (cln::instanceof(value, cln::cl_I_ring) && cln::plusp(cln::the<cln::cl_I>(value)));
1010 /** True if object is an exact integer greater or equal zero. */
1011 bool numeric::is_nonneg_integer() const
1013 return (cln::instanceof(value, cln::cl_I_ring) && !cln::minusp(cln::the<cln::cl_I>(value)));
1017 /** True if object is an exact even integer. */
1018 bool numeric::is_even() const
1020 return (cln::instanceof(value, cln::cl_I_ring) && cln::evenp(cln::the<cln::cl_I>(value)));
1024 /** True if object is an exact odd integer. */
1025 bool numeric::is_odd() const
1027 return (cln::instanceof(value, cln::cl_I_ring) && cln::oddp(cln::the<cln::cl_I>(value)));
1031 /** Probabilistic primality test.
1033 * @return true if object is exact integer and prime. */
1034 bool numeric::is_prime() const
1036 return (cln::instanceof(value, cln::cl_I_ring) // integer?
1037 && cln::plusp(cln::the<cln::cl_I>(value)) // positive?
1038 && cln::isprobprime(cln::the<cln::cl_I>(value)));
1042 /** True if object is an exact rational number, may even be complex
1043 * (denominator may be unity). */
1044 bool numeric::is_rational() const
1046 return cln::instanceof(value, cln::cl_RA_ring);
1050 /** True if object is a real integer, rational or float (but not complex). */
1051 bool numeric::is_real() const
1053 return cln::instanceof(value, cln::cl_R_ring);
1057 bool numeric::operator==(const numeric &other) const
1059 return cln::equal(cln::the<cln::cl_N>(value), cln::the<cln::cl_N>(other.value));
1063 bool numeric::operator!=(const numeric &other) const
1065 return !cln::equal(cln::the<cln::cl_N>(value), cln::the<cln::cl_N>(other.value));
1069 /** True if object is element of the domain of integers extended by I, i.e. is
1070 * of the form a+b*I, where a and b are integers. */
1071 bool numeric::is_cinteger() const
1073 if (cln::instanceof(value, cln::cl_I_ring))
1075 else if (!this->is_real()) { // complex case, handle n+m*I
1076 if (cln::instanceof(cln::realpart(cln::the<cln::cl_N>(value)), cln::cl_I_ring) &&
1077 cln::instanceof(cln::imagpart(cln::the<cln::cl_N>(value)), cln::cl_I_ring))
1084 /** True if object is an exact rational number, may even be complex
1085 * (denominator may be unity). */
1086 bool numeric::is_crational() const
1088 if (cln::instanceof(value, cln::cl_RA_ring))
1090 else if (!this->is_real()) { // complex case, handle Q(i):
1091 if (cln::instanceof(cln::realpart(cln::the<cln::cl_N>(value)), cln::cl_RA_ring) &&
1092 cln::instanceof(cln::imagpart(cln::the<cln::cl_N>(value)), cln::cl_RA_ring))
1099 /** Numerical comparison: less.
1101 * @exception invalid_argument (complex inequality) */
1102 bool numeric::operator<(const numeric &other) const
1104 if (this->is_real() && other.is_real())
1105 return (cln::the<cln::cl_R>(value) < cln::the<cln::cl_R>(other.value));
1106 throw std::invalid_argument("numeric::operator<(): complex inequality");
1110 /** Numerical comparison: less or equal.
1112 * @exception invalid_argument (complex inequality) */
1113 bool numeric::operator<=(const numeric &other) const
1115 if (this->is_real() && other.is_real())
1116 return (cln::the<cln::cl_R>(value) <= cln::the<cln::cl_R>(other.value));
1117 throw std::invalid_argument("numeric::operator<=(): complex inequality");
1121 /** Numerical comparison: greater.
1123 * @exception invalid_argument (complex inequality) */
1124 bool numeric::operator>(const numeric &other) const
1126 if (this->is_real() && other.is_real())
1127 return (cln::the<cln::cl_R>(value) > cln::the<cln::cl_R>(other.value));
1128 throw std::invalid_argument("numeric::operator>(): complex inequality");
1132 /** Numerical comparison: greater or equal.
1134 * @exception invalid_argument (complex inequality) */
1135 bool numeric::operator>=(const numeric &other) const
1137 if (this->is_real() && other.is_real())
1138 return (cln::the<cln::cl_R>(value) >= cln::the<cln::cl_R>(other.value));
1139 throw std::invalid_argument("numeric::operator>=(): complex inequality");
1143 /** Converts numeric types to machine's int. You should check with
1144 * is_integer() if the number is really an integer before calling this method.
1145 * You may also consider checking the range first. */
1146 int numeric::to_int() const
1148 GINAC_ASSERT(this->is_integer());
1149 return cln::cl_I_to_int(cln::the<cln::cl_I>(value));
1153 /** Converts numeric types to machine's long. You should check with
1154 * is_integer() if the number is really an integer before calling this method.
1155 * You may also consider checking the range first. */
1156 long numeric::to_long() const
1158 GINAC_ASSERT(this->is_integer());
1159 return cln::cl_I_to_long(cln::the<cln::cl_I>(value));
1163 /** Converts numeric types to machine's double. You should check with is_real()
1164 * if the number is really not complex before calling this method. */
1165 double numeric::to_double() const
1167 GINAC_ASSERT(this->is_real());
1168 return cln::double_approx(cln::realpart(cln::the<cln::cl_N>(value)));
1172 /** Returns a new CLN object of type cl_N, representing the value of *this.
1173 * This method may be used when mixing GiNaC and CLN in one project.
1175 cln::cl_N numeric::to_cl_N() const
1177 return cln::cl_N(cln::the<cln::cl_N>(value));
1181 /** Real part of a number. */
1182 const numeric numeric::real() const
1184 return numeric(cln::realpart(cln::the<cln::cl_N>(value)));
1188 /** Imaginary part of a number. */
1189 const numeric numeric::imag() const
1191 return numeric(cln::imagpart(cln::the<cln::cl_N>(value)));
1195 /** Numerator. Computes the numerator of rational numbers, rationalized
1196 * numerator of complex if real and imaginary part are both rational numbers
1197 * (i.e numer(4/3+5/6*I) == 8+5*I), the number carrying the sign in all other
1199 const numeric numeric::numer() const
1201 if (cln::instanceof(value, cln::cl_I_ring))
1202 return numeric(*this); // integer case
1204 else if (cln::instanceof(value, cln::cl_RA_ring))
1205 return numeric(cln::numerator(cln::the<cln::cl_RA>(value)));
1207 else if (!this->is_real()) { // complex case, handle Q(i):
1208 const cln::cl_RA r = cln::the<cln::cl_RA>(cln::realpart(cln::the<cln::cl_N>(value)));
1209 const cln::cl_RA i = cln::the<cln::cl_RA>(cln::imagpart(cln::the<cln::cl_N>(value)));
1210 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_I_ring))
1211 return numeric(*this);
1212 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_RA_ring))
1213 return numeric(cln::complex(r*cln::denominator(i), cln::numerator(i)));
1214 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_I_ring))
1215 return numeric(cln::complex(cln::numerator(r), i*cln::denominator(r)));
1216 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_RA_ring)) {
1217 const cln::cl_I s = cln::lcm(cln::denominator(r), cln::denominator(i));
1218 return numeric(cln::complex(cln::numerator(r)*(cln::exquo(s,cln::denominator(r))),
1219 cln::numerator(i)*(cln::exquo(s,cln::denominator(i)))));
1222 // at least one float encountered
1223 return numeric(*this);
1227 /** Denominator. Computes the denominator of rational numbers, common integer
1228 * denominator of complex if real and imaginary part are both rational numbers
1229 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
1230 const numeric numeric::denom() const
1232 if (cln::instanceof(value, cln::cl_I_ring))
1233 return _num1; // integer case
1235 if (cln::instanceof(value, cln::cl_RA_ring))
1236 return numeric(cln::denominator(cln::the<cln::cl_RA>(value)));
1238 if (!this->is_real()) { // complex case, handle Q(i):
1239 const cln::cl_RA r = cln::the<cln::cl_RA>(cln::realpart(cln::the<cln::cl_N>(value)));
1240 const cln::cl_RA i = cln::the<cln::cl_RA>(cln::imagpart(cln::the<cln::cl_N>(value)));
1241 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_I_ring))
1243 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_RA_ring))
1244 return numeric(cln::denominator(i));
1245 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_I_ring))
1246 return numeric(cln::denominator(r));
1247 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_RA_ring))
1248 return numeric(cln::lcm(cln::denominator(r), cln::denominator(i)));
1250 // at least one float encountered
1255 /** Size in binary notation. For integers, this is the smallest n >= 0 such
1256 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
1257 * 2^(n-1) <= x < 2^n.
1259 * @return number of bits (excluding sign) needed to represent that number
1260 * in two's complement if it is an integer, 0 otherwise. */
1261 int numeric::int_length() const
1263 if (cln::instanceof(value, cln::cl_I_ring))
1264 return cln::integer_length(cln::the<cln::cl_I>(value));
1273 /** Imaginary unit. This is not a constant but a numeric since we are
1274 * natively handing complex numbers anyways, so in each expression containing
1275 * an I it is automatically eval'ed away anyhow. */
1276 const numeric I = numeric(cln::complex(cln::cl_I(0),cln::cl_I(1)));
1279 /** Exponential function.
1281 * @return arbitrary precision numerical exp(x). */
1282 const numeric exp(const numeric &x)
1284 return cln::exp(x.to_cl_N());
1288 /** Natural logarithm.
1290 * @param x complex number
1291 * @return arbitrary precision numerical log(x).
1292 * @exception pole_error("log(): logarithmic pole",0) */
1293 const numeric log(const numeric &x)
1296 throw pole_error("log(): logarithmic pole",0);
1297 return cln::log(x.to_cl_N());
1301 /** Numeric sine (trigonometric function).
1303 * @return arbitrary precision numerical sin(x). */
1304 const numeric sin(const numeric &x)
1306 return cln::sin(x.to_cl_N());
1310 /** Numeric cosine (trigonometric function).
1312 * @return arbitrary precision numerical cos(x). */
1313 const numeric cos(const numeric &x)
1315 return cln::cos(x.to_cl_N());
1319 /** Numeric tangent (trigonometric function).
1321 * @return arbitrary precision numerical tan(x). */
1322 const numeric tan(const numeric &x)
1324 return cln::tan(x.to_cl_N());
1328 /** Numeric inverse sine (trigonometric function).
1330 * @return arbitrary precision numerical asin(x). */
1331 const numeric asin(const numeric &x)
1333 return cln::asin(x.to_cl_N());
1337 /** Numeric inverse cosine (trigonometric function).
1339 * @return arbitrary precision numerical acos(x). */
1340 const numeric acos(const numeric &x)
1342 return cln::acos(x.to_cl_N());
1348 * @param x complex number
1350 * @exception pole_error("atan(): logarithmic pole",0) */
1351 const numeric atan(const numeric &x)
1354 x.real().is_zero() &&
1355 abs(x.imag()).is_equal(_num1))
1356 throw pole_error("atan(): logarithmic pole",0);
1357 return cln::atan(x.to_cl_N());
1363 * @param x real number
1364 * @param y real number
1365 * @return atan(y/x) */
1366 const numeric atan(const numeric &y, const numeric &x)
1368 if (x.is_real() && y.is_real())
1369 return cln::atan(cln::the<cln::cl_R>(x.to_cl_N()),
1370 cln::the<cln::cl_R>(y.to_cl_N()));
1372 throw std::invalid_argument("atan(): complex argument");
1376 /** Numeric hyperbolic sine (trigonometric function).
1378 * @return arbitrary precision numerical sinh(x). */
1379 const numeric sinh(const numeric &x)
1381 return cln::sinh(x.to_cl_N());
1385 /** Numeric hyperbolic cosine (trigonometric function).
1387 * @return arbitrary precision numerical cosh(x). */
1388 const numeric cosh(const numeric &x)
1390 return cln::cosh(x.to_cl_N());
1394 /** Numeric hyperbolic tangent (trigonometric function).
1396 * @return arbitrary precision numerical tanh(x). */
1397 const numeric tanh(const numeric &x)
1399 return cln::tanh(x.to_cl_N());
1403 /** Numeric inverse hyperbolic sine (trigonometric function).
1405 * @return arbitrary precision numerical asinh(x). */
1406 const numeric asinh(const numeric &x)
1408 return cln::asinh(x.to_cl_N());
1412 /** Numeric inverse hyperbolic cosine (trigonometric function).
1414 * @return arbitrary precision numerical acosh(x). */
1415 const numeric acosh(const numeric &x)
1417 return cln::acosh(x.to_cl_N());
1421 /** Numeric inverse hyperbolic tangent (trigonometric function).
1423 * @return arbitrary precision numerical atanh(x). */
1424 const numeric atanh(const numeric &x)
1426 return cln::atanh(x.to_cl_N());
1430 /*static cln::cl_N Li2_series(const ::cl_N &x,
1431 const ::float_format_t &prec)
1433 // Note: argument must be in the unit circle
1434 // This is very inefficient unless we have fast floating point Bernoulli
1435 // numbers implemented!
1436 cln::cl_N c1 = -cln::log(1-x);
1438 // hard-wire the first two Bernoulli numbers
1439 cln::cl_N acc = c1 - cln::square(c1)/4;
1441 cln::cl_F pisq = cln::square(cln::cl_pi(prec)); // pi^2
1442 cln::cl_F piac = cln::cl_float(1, prec); // accumulator: pi^(2*i)
1444 c1 = cln::square(c1);
1448 aug = c2 * (*(bernoulli(numeric(2*i)).clnptr())) / cln::factorial(2*i+1);
1449 // 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));
1452 } while (acc != acc+aug);
1456 /** Numeric evaluation of Dilogarithm within circle of convergence (unit
1457 * circle) using a power series. */
1458 static cln::cl_N Li2_series(const cln::cl_N &x,
1459 const cln::float_format_t &prec)
1461 // Note: argument must be in the unit circle
1463 cln::cl_N num = cln::complex(cln::cl_float(1, prec), 0);
1468 den = den + i; // 1, 4, 9, 16, ...
1472 } while (acc != acc+aug);
1476 /** Folds Li2's argument inside a small rectangle to enhance convergence. */
1477 static cln::cl_N Li2_projection(const cln::cl_N &x,
1478 const cln::float_format_t &prec)
1480 const cln::cl_R re = cln::realpart(x);
1481 const cln::cl_R im = cln::imagpart(x);
1482 if (re > cln::cl_F(".5"))
1483 // zeta(2) - Li2(1-x) - log(x)*log(1-x)
1485 - Li2_series(1-x, prec)
1486 - cln::log(x)*cln::log(1-x));
1487 if ((re <= 0 && cln::abs(im) > cln::cl_F(".75")) || (re < cln::cl_F("-.5")))
1488 // -log(1-x)^2 / 2 - Li2(x/(x-1))
1489 return(- cln::square(cln::log(1-x))/2
1490 - Li2_series(x/(x-1), prec));
1491 if (re > 0 && cln::abs(im) > cln::cl_LF(".75"))
1492 // Li2(x^2)/2 - Li2(-x)
1493 return(Li2_projection(cln::square(x), prec)/2
1494 - Li2_projection(-x, prec));
1495 return Li2_series(x, prec);
1498 /** Numeric evaluation of Dilogarithm. The domain is the entire complex plane,
1499 * the branch cut lies along the positive real axis, starting at 1 and
1500 * continuous with quadrant IV.
1502 * @return arbitrary precision numerical Li2(x). */
1503 const numeric Li2(const numeric &x)
1508 // what is the desired float format?
1509 // first guess: default format
1510 cln::float_format_t prec = cln::default_float_format;
1511 const cln::cl_N value = x.to_cl_N();
1512 // second guess: the argument's format
1513 if (!x.real().is_rational())
1514 prec = cln::float_format(cln::the<cln::cl_F>(cln::realpart(value)));
1515 else if (!x.imag().is_rational())
1516 prec = cln::float_format(cln::the<cln::cl_F>(cln::imagpart(value)));
1518 if (cln::the<cln::cl_N>(value)==1) // may cause trouble with log(1-x)
1519 return cln::zeta(2, prec);
1521 if (cln::abs(value) > 1)
1522 // -log(-x)^2 / 2 - zeta(2) - Li2(1/x)
1523 return(- cln::square(cln::log(-value))/2
1524 - cln::zeta(2, prec)
1525 - Li2_projection(cln::recip(value), prec));
1527 return Li2_projection(x.to_cl_N(), prec);
1531 /** Numeric evaluation of Riemann's Zeta function. Currently works only for
1532 * integer arguments. */
1533 const numeric zeta(const numeric &x)
1535 // A dirty hack to allow for things like zeta(3.0), since CLN currently
1536 // only knows about integer arguments and zeta(3).evalf() automatically
1537 // cascades down to zeta(3.0).evalf(). The trick is to rely on 3.0-3
1538 // being an exact zero for CLN, which can be tested and then we can just
1539 // pass the number casted to an int:
1541 const int aux = (int)(cln::double_approx(cln::the<cln::cl_R>(x.to_cl_N())));
1542 if (cln::zerop(x.to_cl_N()-aux))
1543 return cln::zeta(aux);
1549 /** The Gamma function.
1550 * This is only a stub! */
1551 const numeric lgamma(const numeric &x)
1555 const numeric tgamma(const numeric &x)
1561 /** The psi function (aka polygamma function).
1562 * This is only a stub! */
1563 const numeric psi(const numeric &x)
1569 /** The psi functions (aka polygamma functions).
1570 * This is only a stub! */
1571 const numeric psi(const numeric &n, const numeric &x)
1577 /** Factorial combinatorial function.
1579 * @param n integer argument >= 0
1580 * @exception range_error (argument must be integer >= 0) */
1581 const numeric factorial(const numeric &n)
1583 if (!n.is_nonneg_integer())
1584 throw std::range_error("numeric::factorial(): argument must be integer >= 0");
1585 return numeric(cln::factorial(n.to_int()));
1589 /** The double factorial combinatorial function. (Scarcely used, but still
1590 * useful in cases, like for exact results of tgamma(n+1/2) for instance.)
1592 * @param n integer argument >= -1
1593 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == (-1)!! == 1
1594 * @exception range_error (argument must be integer >= -1) */
1595 const numeric doublefactorial(const numeric &n)
1597 if (n.is_equal(_num_1))
1600 if (!n.is_nonneg_integer())
1601 throw std::range_error("numeric::doublefactorial(): argument must be integer >= -1");
1603 return numeric(cln::doublefactorial(n.to_int()));
1607 /** The Binomial coefficients. It computes the binomial coefficients. For
1608 * integer n and k and positive n this is the number of ways of choosing k
1609 * objects from n distinct objects. If n is negative, the formula
1610 * binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */
1611 const numeric binomial(const numeric &n, const numeric &k)
1613 if (n.is_integer() && k.is_integer()) {
1614 if (n.is_nonneg_integer()) {
1615 if (k.compare(n)!=1 && k.compare(_num0)!=-1)
1616 return numeric(cln::binomial(n.to_int(),k.to_int()));
1620 return _num_1.power(k)*binomial(k-n-_num1,k);
1624 // should really be gamma(n+1)/gamma(r+1)/gamma(n-r+1) or a suitable limit
1625 throw std::range_error("numeric::binomial(): don´t know how to evaluate that.");
1629 /** Bernoulli number. The nth Bernoulli number is the coefficient of x^n/n!
1630 * in the expansion of the function x/(e^x-1).
1632 * @return the nth Bernoulli number (a rational number).
1633 * @exception range_error (argument must be integer >= 0) */
1634 const numeric bernoulli(const numeric &nn)
1636 if (!nn.is_integer() || nn.is_negative())
1637 throw std::range_error("numeric::bernoulli(): argument must be integer >= 0");
1641 // The Bernoulli numbers are rational numbers that may be computed using
1644 // B_n = - 1/(n+1) * sum_{k=0}^{n-1}(binomial(n+1,k)*B_k)
1646 // with B(0) = 1. Since the n'th Bernoulli number depends on all the
1647 // previous ones, the computation is necessarily very expensive. There are
1648 // several other ways of computing them, a particularly good one being
1652 // for (unsigned i=0; i<n; i++) {
1653 // c = exquo(c*(i-n),(i+2));
1654 // Bern = Bern + c*s/(i+2);
1655 // s = s + expt_pos(cl_I(i+2),n);
1659 // But if somebody works with the n'th Bernoulli number she is likely to
1660 // also need all previous Bernoulli numbers. So we need a complete remember
1661 // table and above divide and conquer algorithm is not suited to build one
1662 // up. The formula below accomplishes this. It is a modification of the
1663 // defining formula above but the computation of the binomial coefficients
1664 // is carried along in an inline fashion. It also honors the fact that
1665 // B_n is zero when n is odd and greater than 1.
1667 // (There is an interesting relation with the tangent polynomials described
1668 // in `Concrete Mathematics', which leads to a program a little faster as
1669 // our implementation below, but it requires storing one such polynomial in
1670 // addition to the remember table. This doubles the memory footprint so
1671 // we don't use it.)
1673 const unsigned n = nn.to_int();
1675 // the special cases not covered by the algorithm below
1677 return (n==1) ? _num_1_2 : _num0;
1681 // store nonvanishing Bernoulli numbers here
1682 static std::vector< cln::cl_RA > results;
1683 static unsigned next_r = 0;
1685 // algorithm not applicable to B(2), so just store it
1687 results.push_back(cln::recip(cln::cl_RA(6)));
1691 return results[n/2-1];
1693 results.reserve(n/2);
1694 for (unsigned p=next_r; p<=n; p+=2) {
1695 cln::cl_I c = 1; // seed for binonmial coefficients
1696 cln::cl_RA b = cln::cl_RA(1-p)/2;
1697 const unsigned p3 = p+3;
1698 const unsigned pm = p-2;
1700 // test if intermediate unsigned int can be represented by immediate
1701 // objects by CLN (i.e. < 2^29 for 32 Bit machines, see <cln/object.h>)
1702 if (p < (1UL<<cl_value_len/2)) {
1703 for (i=2, k=1, p_2=p/2; i<=pm; i+=2, ++k, --p_2) {
1704 c = cln::exquo(c * ((p3-i) * p_2), (i-1)*k);
1705 b = b + c*results[k-1];
1708 for (i=2, k=1, p_2=p/2; i<=pm; i+=2, ++k, --p_2) {
1709 c = cln::exquo((c * (p3-i)) * p_2, cln::cl_I(i-1)*k);
1710 b = b + c*results[k-1];
1713 results.push_back(-b/(p+1));
1716 return results[n/2-1];
1720 /** Fibonacci number. The nth Fibonacci number F(n) is defined by the
1721 * recurrence formula F(n)==F(n-1)+F(n-2) with F(0)==0 and F(1)==1.
1723 * @param n an integer
1724 * @return the nth Fibonacci number F(n) (an integer number)
1725 * @exception range_error (argument must be an integer) */
1726 const numeric fibonacci(const numeric &n)
1728 if (!n.is_integer())
1729 throw std::range_error("numeric::fibonacci(): argument must be integer");
1732 // The following addition formula holds:
1734 // F(n+m) = F(m-1)*F(n) + F(m)*F(n+1) for m >= 1, n >= 0.
1736 // (Proof: For fixed m, the LHS and the RHS satisfy the same recurrence
1737 // w.r.t. n, and the initial values (n=0, n=1) agree. Hence all values
1739 // Replace m by m+1:
1740 // F(n+m+1) = F(m)*F(n) + F(m+1)*F(n+1) for m >= 0, n >= 0
1741 // Now put in m = n, to get
1742 // F(2n) = (F(n+1)-F(n))*F(n) + F(n)*F(n+1) = F(n)*(2*F(n+1) - F(n))
1743 // F(2n+1) = F(n)^2 + F(n+1)^2
1745 // F(2n+2) = F(n+1)*(2*F(n) + F(n+1))
1748 if (n.is_negative())
1750 return -fibonacci(-n);
1752 return fibonacci(-n);
1756 cln::cl_I m = cln::the<cln::cl_I>(n.to_cl_N()) >> 1L; // floor(n/2);
1757 for (uintL bit=cln::integer_length(m); bit>0; --bit) {
1758 // Since a squaring is cheaper than a multiplication, better use
1759 // three squarings instead of one multiplication and two squarings.
1760 cln::cl_I u2 = cln::square(u);
1761 cln::cl_I v2 = cln::square(v);
1762 if (cln::logbitp(bit-1, m)) {
1763 v = cln::square(u + v) - u2;
1766 u = v2 - cln::square(v - u);
1771 // Here we don't use the squaring formula because one multiplication
1772 // is cheaper than two squarings.
1773 return u * ((v << 1) - u);
1775 return cln::square(u) + cln::square(v);
1779 /** Absolute value. */
1780 const numeric abs(const numeric& x)
1782 return cln::abs(x.to_cl_N());
1786 /** Modulus (in positive representation).
1787 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1788 * sign of a or is zero. This is different from Maple's modp, where the sign
1789 * of b is ignored. It is in agreement with Mathematica's Mod.
1791 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1792 * integer, 0 otherwise. */
1793 const numeric mod(const numeric &a, const numeric &b)
1795 if (a.is_integer() && b.is_integer())
1796 return cln::mod(cln::the<cln::cl_I>(a.to_cl_N()),
1797 cln::the<cln::cl_I>(b.to_cl_N()));
1803 /** Modulus (in symmetric representation).
1804 * Equivalent to Maple's mods.
1806 * @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1807 const numeric smod(const numeric &a, const numeric &b)
1809 if (a.is_integer() && b.is_integer()) {
1810 const cln::cl_I b2 = cln::ceiling1(cln::the<cln::cl_I>(b.to_cl_N()) >> 1) - 1;
1811 return cln::mod(cln::the<cln::cl_I>(a.to_cl_N()) + b2,
1812 cln::the<cln::cl_I>(b.to_cl_N())) - b2;
1818 /** Numeric integer remainder.
1819 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1820 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1821 * sign of a or is zero.
1823 * @return remainder of a/b if both are integer, 0 otherwise.
1824 * @exception overflow_error (division by zero) if b is zero. */
1825 const numeric irem(const numeric &a, const numeric &b)
1828 throw std::overflow_error("numeric::irem(): division by zero");
1829 if (a.is_integer() && b.is_integer())
1830 return cln::rem(cln::the<cln::cl_I>(a.to_cl_N()),
1831 cln::the<cln::cl_I>(b.to_cl_N()));
1837 /** Numeric integer remainder.
1838 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1839 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1840 * and irem(a,b) has the sign of a or is zero.
1842 * @return remainder of a/b and quotient stored in q if both are integer,
1844 * @exception overflow_error (division by zero) if b is zero. */
1845 const numeric irem(const numeric &a, const numeric &b, numeric &q)
1848 throw std::overflow_error("numeric::irem(): division by zero");
1849 if (a.is_integer() && b.is_integer()) {
1850 const cln::cl_I_div_t rem_quo = cln::truncate2(cln::the<cln::cl_I>(a.to_cl_N()),
1851 cln::the<cln::cl_I>(b.to_cl_N()));
1852 q = rem_quo.quotient;
1853 return rem_quo.remainder;
1861 /** Numeric integer quotient.
1862 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1864 * @return truncated quotient of a/b if both are integer, 0 otherwise.
1865 * @exception overflow_error (division by zero) if b is zero. */
1866 const numeric iquo(const numeric &a, const numeric &b)
1869 throw std::overflow_error("numeric::iquo(): division by zero");
1870 if (a.is_integer() && b.is_integer())
1871 return cln::truncate1(cln::the<cln::cl_I>(a.to_cl_N()),
1872 cln::the<cln::cl_I>(b.to_cl_N()));
1878 /** Numeric integer quotient.
1879 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1880 * r == a - iquo(a,b,r)*b.
1882 * @return truncated quotient of a/b and remainder stored in r if both are
1883 * integer, 0 otherwise.
1884 * @exception overflow_error (division by zero) if b is zero. */
1885 const numeric iquo(const numeric &a, const numeric &b, numeric &r)
1888 throw std::overflow_error("numeric::iquo(): division by zero");
1889 if (a.is_integer() && b.is_integer()) {
1890 const cln::cl_I_div_t rem_quo = cln::truncate2(cln::the<cln::cl_I>(a.to_cl_N()),
1891 cln::the<cln::cl_I>(b.to_cl_N()));
1892 r = rem_quo.remainder;
1893 return rem_quo.quotient;
1901 /** Greatest Common Divisor.
1903 * @return The GCD of two numbers if both are integer, a numerical 1
1904 * if they are not. */
1905 const numeric gcd(const numeric &a, const numeric &b)
1907 if (a.is_integer() && b.is_integer())
1908 return cln::gcd(cln::the<cln::cl_I>(a.to_cl_N()),
1909 cln::the<cln::cl_I>(b.to_cl_N()));
1915 /** Least Common Multiple.
1917 * @return The LCM of two numbers if both are integer, the product of those
1918 * two numbers if they are not. */
1919 const numeric lcm(const numeric &a, const numeric &b)
1921 if (a.is_integer() && b.is_integer())
1922 return cln::lcm(cln::the<cln::cl_I>(a.to_cl_N()),
1923 cln::the<cln::cl_I>(b.to_cl_N()));
1929 /** Numeric square root.
1930 * If possible, sqrt(x) should respect squares of exact numbers, i.e. sqrt(4)
1931 * should return integer 2.
1933 * @param x numeric argument
1934 * @return square root of x. Branch cut along negative real axis, the negative
1935 * real axis itself where imag(x)==0 and real(x)<0 belongs to the upper part
1936 * where imag(x)>0. */
1937 const numeric sqrt(const numeric &x)
1939 return cln::sqrt(x.to_cl_N());
1943 /** Integer numeric square root. */
1944 const numeric isqrt(const numeric &x)
1946 if (x.is_integer()) {
1948 cln::isqrt(cln::the<cln::cl_I>(x.to_cl_N()), &root);
1955 /** Floating point evaluation of Archimedes' constant Pi. */
1958 return numeric(cln::pi(cln::default_float_format));
1962 /** Floating point evaluation of Euler's constant gamma. */
1965 return numeric(cln::eulerconst(cln::default_float_format));
1969 /** Floating point evaluation of Catalan's constant. */
1972 return numeric(cln::catalanconst(cln::default_float_format));
1976 /** _numeric_digits default ctor, checking for singleton invariance. */
1977 _numeric_digits::_numeric_digits()
1980 // It initializes to 17 digits, because in CLN float_format(17) turns out
1981 // to be 61 (<64) while float_format(18)=65. The reason is we want to
1982 // have a cl_LF instead of cl_SF, cl_FF or cl_DF.
1984 throw(std::runtime_error("I told you not to do instantiate me!"));
1986 cln::default_float_format = cln::float_format(17);
1990 /** Assign a native long to global Digits object. */
1991 _numeric_digits& _numeric_digits::operator=(long prec)
1994 cln::default_float_format = cln::float_format(prec);
1999 /** Convert global Digits object to native type long. */
2000 _numeric_digits::operator long()
2002 // BTW, this is approx. unsigned(cln::default_float_format*0.301)-1
2003 return (long)digits;
2007 /** Append global Digits object to ostream. */
2008 void _numeric_digits::print(std::ostream &os) const
2014 std::ostream& operator<<(std::ostream &os, const _numeric_digits &e)
2021 // static member variables
2026 bool _numeric_digits::too_late = false;
2029 /** Accuracy in decimal digits. Only object of this type! Can be set using
2030 * assignment from C++ unsigned ints and evaluated like any built-in type. */
2031 _numeric_digits Digits;
2033 } // namespace GiNaC