3 * This file contains the interface to the underlying bignum package.
4 * Its most important design principle is to completely hide the inner
5 * working of that other package from the user of GiNaC. It must either
6 * provide implementation of arithmetic operators and numerical evaluation
7 * of special functions or implement the interface to the bignum package. */
10 * GiNaC Copyright (C) 1999-2003 Johannes Gutenberg University Mainz, Germany
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
38 #include "operators.h"
43 // CLN should pollute the global namespace as little as possible. Hence, we
44 // include most of it here and include only the part needed for properly
45 // declaring cln::cl_number in numeric.h. This can only be safely done in
46 // namespaced versions of CLN, i.e. version > 1.1.0. Also, we only need a
47 // subset of CLN, so we don't include the complete <cln/cln.h> but only the
49 #include <cln/output.h>
50 #include <cln/integer_io.h>
51 #include <cln/integer_ring.h>
52 #include <cln/rational_io.h>
53 #include <cln/rational_ring.h>
54 #include <cln/lfloat_class.h>
55 #include <cln/lfloat_io.h>
56 #include <cln/real_io.h>
57 #include <cln/real_ring.h>
58 #include <cln/complex_io.h>
59 #include <cln/complex_ring.h>
60 #include <cln/numtheory.h>
64 GINAC_IMPLEMENT_REGISTERED_CLASS(numeric, basic)
67 // default constructor
70 /** default ctor. Numerically it initializes to an integer zero. */
71 numeric::numeric() : basic(TINFO_numeric)
74 setflag(status_flags::evaluated | status_flags::expanded);
83 numeric::numeric(int i) : basic(TINFO_numeric)
85 // Not the whole int-range is available if we don't cast to long
86 // first. This is due to the behaviour of the cl_I-ctor, which
87 // emphasizes efficiency. However, if the integer is small enough
88 // we save space and dereferences by using an immediate type.
89 // (C.f. <cln/object.h>)
90 if (i < (1L << (cl_value_len-1)) && i >= -(1L << (cl_value_len-1)))
93 value = cln::cl_I(static_cast<long>(i));
94 setflag(status_flags::evaluated | status_flags::expanded);
98 numeric::numeric(unsigned int i) : basic(TINFO_numeric)
100 // Not the whole uint-range is available if we don't cast to ulong
101 // first. This is due to the behaviour of the cl_I-ctor, which
102 // emphasizes efficiency. However, if the integer is small enough
103 // we save space and dereferences by using an immediate type.
104 // (C.f. <cln/object.h>)
105 if (i < (1U << (cl_value_len-1)))
106 value = cln::cl_I(i);
108 value = cln::cl_I(static_cast<unsigned long>(i));
109 setflag(status_flags::evaluated | status_flags::expanded);
113 numeric::numeric(long i) : basic(TINFO_numeric)
115 value = cln::cl_I(i);
116 setflag(status_flags::evaluated | status_flags::expanded);
120 numeric::numeric(unsigned long i) : basic(TINFO_numeric)
122 value = cln::cl_I(i);
123 setflag(status_flags::evaluated | status_flags::expanded);
127 /** Constructor for rational numerics a/b.
129 * @exception overflow_error (division by zero) */
130 numeric::numeric(long numer, long denom) : basic(TINFO_numeric)
133 throw std::overflow_error("division by zero");
134 value = cln::cl_I(numer) / cln::cl_I(denom);
135 setflag(status_flags::evaluated | status_flags::expanded);
139 numeric::numeric(double d) : basic(TINFO_numeric)
141 // We really want to explicitly use the type cl_LF instead of the
142 // more general cl_F, since that would give us a cl_DF only which
143 // will not be promoted to cl_LF if overflow occurs:
144 value = cln::cl_float(d, cln::default_float_format);
145 setflag(status_flags::evaluated | status_flags::expanded);
149 /** ctor from C-style string. It also accepts complex numbers in GiNaC
150 * notation like "2+5*I". */
151 numeric::numeric(const char *s) : basic(TINFO_numeric)
153 cln::cl_N ctorval = 0;
154 // parse complex numbers (functional but not completely safe, unfortunately
155 // std::string does not understand regexpese):
156 // ss should represent a simple sum like 2+5*I
158 std::string::size_type delim;
160 // make this implementation safe by adding explicit sign
161 if (ss.at(0) != '+' && ss.at(0) != '-' && ss.at(0) != '#')
164 // We use 'E' as exponent marker in the output, but some people insist on
165 // writing 'e' at input, so let's substitute them right at the beginning:
166 while ((delim = ss.find("e"))!=std::string::npos)
167 ss.replace(delim,1,"E");
171 // chop ss into terms from left to right
173 bool imaginary = false;
174 delim = ss.find_first_of(std::string("+-"),1);
175 // Do we have an exponent marker like "31.415E-1"? If so, hop on!
176 if (delim!=std::string::npos && ss.at(delim-1)=='E')
177 delim = ss.find_first_of(std::string("+-"),delim+1);
178 term = ss.substr(0,delim);
179 if (delim!=std::string::npos)
180 ss = ss.substr(delim);
181 // is the term imaginary?
182 if (term.find("I")!=std::string::npos) {
184 term.erase(term.find("I"),1);
186 if (term.find("*")!=std::string::npos)
187 term.erase(term.find("*"),1);
188 // correct for trivial +/-I without explicit factor on I:
193 if (term.find('.')!=std::string::npos || term.find('E')!=std::string::npos) {
194 // CLN's short type cl_SF is not very useful within the GiNaC
195 // framework where we are mainly interested in the arbitrary
196 // precision type cl_LF. Hence we go straight to the construction
197 // of generic floats. In order to create them we have to convert
198 // our own floating point notation used for output and construction
199 // from char * to CLN's generic notation:
200 // 3.14 --> 3.14e0_<Digits>
201 // 31.4E-1 --> 31.4e-1_<Digits>
203 // No exponent marker? Let's add a trivial one.
204 if (term.find("E")==std::string::npos)
207 term = term.replace(term.find("E"),1,"e");
208 // append _<Digits> to term
209 term += "_" + ToString((unsigned)Digits);
210 // construct float using cln::cl_F(const char *) ctor.
212 ctorval = ctorval + cln::complex(cln::cl_I(0),cln::cl_F(term.c_str()));
214 ctorval = ctorval + cln::cl_F(term.c_str());
216 // this is not a floating point number...
218 ctorval = ctorval + cln::complex(cln::cl_I(0),cln::cl_R(term.c_str()));
220 ctorval = ctorval + cln::cl_R(term.c_str());
222 } while (delim != std::string::npos);
224 setflag(status_flags::evaluated | status_flags::expanded);
228 /** Ctor from CLN types. This is for the initiated user or internal use
230 numeric::numeric(const cln::cl_N &z) : basic(TINFO_numeric)
233 setflag(status_flags::evaluated | status_flags::expanded);
240 numeric::numeric(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
242 cln::cl_N ctorval = 0;
244 // Read number as string
246 if (n.find_string("number", str)) {
247 std::istringstream s(str);
248 cln::cl_idecoded_float re, im;
252 case 'R': // Integer-decoded real number
253 s >> re.sign >> re.mantissa >> re.exponent;
254 ctorval = re.sign * re.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), re.exponent);
256 case 'C': // Integer-decoded complex number
257 s >> re.sign >> re.mantissa >> re.exponent;
258 s >> im.sign >> im.mantissa >> im.exponent;
259 ctorval = cln::complex(re.sign * re.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), re.exponent),
260 im.sign * im.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), im.exponent));
262 default: // Ordinary number
269 setflag(status_flags::evaluated | status_flags::expanded);
272 void numeric::archive(archive_node &n) const
274 inherited::archive(n);
276 // Write number as string
277 std::ostringstream s;
278 if (this->is_crational())
279 s << cln::the<cln::cl_N>(value);
281 // Non-rational numbers are written in an integer-decoded format
282 // to preserve the precision
283 if (this->is_real()) {
284 cln::cl_idecoded_float re = cln::integer_decode_float(cln::the<cln::cl_F>(value));
286 s << re.sign << " " << re.mantissa << " " << re.exponent;
288 cln::cl_idecoded_float re = cln::integer_decode_float(cln::the<cln::cl_F>(cln::realpart(cln::the<cln::cl_N>(value))));
289 cln::cl_idecoded_float im = cln::integer_decode_float(cln::the<cln::cl_F>(cln::imagpart(cln::the<cln::cl_N>(value))));
291 s << re.sign << " " << re.mantissa << " " << re.exponent << " ";
292 s << im.sign << " " << im.mantissa << " " << im.exponent;
295 n.add_string("number", s.str());
298 DEFAULT_UNARCHIVE(numeric)
301 // functions overriding virtual functions from base classes
304 /** Helper function to print a real number in a nicer way than is CLN's
305 * default. Instead of printing 42.0L0 this just prints 42.0 to ostream os
306 * and instead of 3.99168L7 it prints 3.99168E7. This is fine in GiNaC as
307 * long as it only uses cl_LF and no other floating point types that we might
308 * want to visibly distinguish from cl_LF.
310 * @see numeric::print() */
311 static void print_real_number(const print_context & c, const cln::cl_R & x)
313 cln::cl_print_flags ourflags;
314 if (cln::instanceof(x, cln::cl_RA_ring)) {
315 // case 1: integer or rational
316 if (cln::instanceof(x, cln::cl_I_ring) ||
317 !is_a<print_latex>(c)) {
318 cln::print_real(c.s, ourflags, x);
319 } else { // rational output in LaTeX context
323 cln::print_real(c.s, ourflags, cln::abs(cln::numerator(cln::the<cln::cl_RA>(x))));
325 cln::print_real(c.s, ourflags, cln::denominator(cln::the<cln::cl_RA>(x)));
330 // make CLN believe this number has default_float_format, so it prints
331 // 'E' as exponent marker instead of 'L':
332 ourflags.default_float_format = cln::float_format(cln::the<cln::cl_F>(x));
333 cln::print_real(c.s, ourflags, x);
337 /** Helper function to print integer number in C++ source format.
339 * @see numeric::print() */
340 static void print_integer_csrc(const print_context & c, const cln::cl_I & x)
342 // Print small numbers in compact float format, but larger numbers in
344 const int max_cln_int = 536870911; // 2^29-1
345 if (x >= cln::cl_I(-max_cln_int) && x <= cln::cl_I(max_cln_int))
346 c.s << cln::cl_I_to_int(x) << ".0";
348 c.s << cln::double_approx(x);
351 /** Helper function to print real number in C++ source format.
353 * @see numeric::print() */
354 static void print_real_csrc(const print_context & c, const cln::cl_R & x)
356 if (cln::instanceof(x, cln::cl_I_ring)) {
359 print_integer_csrc(c, cln::the<cln::cl_I>(x));
361 } else if (cln::instanceof(x, cln::cl_RA_ring)) {
364 const cln::cl_I numer = cln::numerator(cln::the<cln::cl_RA>(x));
365 const cln::cl_I denom = cln::denominator(cln::the<cln::cl_RA>(x));
366 if (cln::plusp(x) > 0) {
368 print_integer_csrc(c, numer);
371 print_integer_csrc(c, -numer);
374 print_integer_csrc(c, denom);
380 c.s << cln::double_approx(x);
384 /** Helper function to print real number in C++ source format using cl_N types.
386 * @see numeric::print() */
387 static void print_real_cl_N(const print_context & c, const cln::cl_R & x)
389 if (cln::instanceof(x, cln::cl_I_ring)) {
392 c.s << "cln::cl_I(\"";
393 print_real_number(c, x);
396 } else if (cln::instanceof(x, cln::cl_RA_ring)) {
399 cln::cl_print_flags ourflags;
400 c.s << "cln::cl_RA(\"";
401 cln::print_rational(c.s, ourflags, cln::the<cln::cl_RA>(x));
407 c.s << "cln::cl_F(\"";
408 print_real_number(c, cln::cl_float(1.0, cln::default_float_format) * x);
409 c.s << "_" << Digits << "\")";
413 /** This method adds to the output so it blends more consistently together
414 * with the other routines and produces something compatible to ginsh input.
416 * @see print_real_number() */
417 void numeric::print(const print_context & c, unsigned level) const
419 if (is_a<print_tree>(c)) {
421 c.s << std::string(level, ' ') << cln::the<cln::cl_N>(value)
422 << " (" << class_name() << ")"
423 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
426 } else if (is_a<print_csrc_cl_N>(c)) {
429 if (this->is_real()) {
432 print_real_cl_N(c, cln::the<cln::cl_R>(value));
437 c.s << "cln::complex(";
438 print_real_cl_N(c, cln::realpart(cln::the<cln::cl_N>(value)));
440 print_real_cl_N(c, cln::imagpart(cln::the<cln::cl_N>(value)));
444 } else if (is_a<print_csrc>(c)) {
447 std::ios::fmtflags oldflags = c.s.flags();
448 c.s.setf(std::ios::scientific);
449 int oldprec = c.s.precision();
452 if (is_a<print_csrc_double>(c))
453 c.s.precision(std::numeric_limits<double>::digits10 + 1);
455 c.s.precision(std::numeric_limits<float>::digits10 + 1);
457 if (this->is_real()) {
460 print_real_csrc(c, cln::the<cln::cl_R>(value));
465 c.s << "std::complex<";
466 if (is_a<print_csrc_double>(c))
471 print_real_csrc(c, cln::realpart(cln::the<cln::cl_N>(value)));
473 print_real_csrc(c, cln::imagpart(cln::the<cln::cl_N>(value)));
478 c.s.precision(oldprec);
482 const std::string par_open = is_a<print_latex>(c) ? "{(" : "(";
483 const std::string par_close = is_a<print_latex>(c) ? ")}" : ")";
484 const std::string imag_sym = is_a<print_latex>(c) ? "i" : "I";
485 const std::string mul_sym = is_a<print_latex>(c) ? " " : "*";
486 const cln::cl_R r = cln::realpart(cln::the<cln::cl_N>(value));
487 const cln::cl_R i = cln::imagpart(cln::the<cln::cl_N>(value));
489 if (is_a<print_python_repr>(c))
490 c.s << class_name() << "('";
492 // case 1, real: x or -x
493 if ((precedence() <= level) && (!this->is_nonneg_integer())) {
495 print_real_number(c, r);
498 print_real_number(c, r);
502 // case 2, imaginary: y*I or -y*I
506 if (precedence()<=level)
509 c.s << "-" << imag_sym;
511 print_real_number(c, i);
512 c.s << mul_sym+imag_sym;
514 if (precedence()<=level)
518 // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I
519 if (precedence() <= level)
521 print_real_number(c, r);
526 print_real_number(c, i);
527 c.s << mul_sym+imag_sym;
534 print_real_number(c, i);
535 c.s << mul_sym+imag_sym;
538 if (precedence() <= level)
542 if (is_a<print_python_repr>(c))
547 bool numeric::info(unsigned inf) const
550 case info_flags::numeric:
551 case info_flags::polynomial:
552 case info_flags::rational_function:
554 case info_flags::real:
556 case info_flags::rational:
557 case info_flags::rational_polynomial:
558 return is_rational();
559 case info_flags::crational:
560 case info_flags::crational_polynomial:
561 return is_crational();
562 case info_flags::integer:
563 case info_flags::integer_polynomial:
565 case info_flags::cinteger:
566 case info_flags::cinteger_polynomial:
567 return is_cinteger();
568 case info_flags::positive:
569 return is_positive();
570 case info_flags::negative:
571 return is_negative();
572 case info_flags::nonnegative:
573 return !is_negative();
574 case info_flags::posint:
575 return is_pos_integer();
576 case info_flags::negint:
577 return is_integer() && is_negative();
578 case info_flags::nonnegint:
579 return is_nonneg_integer();
580 case info_flags::even:
582 case info_flags::odd:
584 case info_flags::prime:
586 case info_flags::algebraic:
592 int numeric::degree(const ex & s) const
597 int numeric::ldegree(const ex & s) const
602 ex numeric::coeff(const ex & s, int n) const
604 return n==0 ? *this : _ex0;
607 /** Disassemble real part and imaginary part to scan for the occurrence of a
608 * single number. Also handles the imaginary unit. It ignores the sign on
609 * both this and the argument, which may lead to what might appear as funny
610 * results: (2+I).has(-2) -> true. But this is consistent, since we also
611 * would like to have (-2+I).has(2) -> true and we want to think about the
612 * sign as a multiplicative factor. */
613 bool numeric::has(const ex &other) const
615 if (!is_exactly_a<numeric>(other))
617 const numeric &o = ex_to<numeric>(other);
618 if (this->is_equal(o) || this->is_equal(-o))
620 if (o.imag().is_zero()) // e.g. scan for 3 in -3*I
621 return (this->real().is_equal(o) || this->imag().is_equal(o) ||
622 this->real().is_equal(-o) || this->imag().is_equal(-o));
624 if (o.is_equal(I)) // e.g scan for I in 42*I
625 return !this->is_real();
626 if (o.real().is_zero()) // e.g. scan for 2*I in 2*I+1
627 return (this->real().has(o*I) || this->imag().has(o*I) ||
628 this->real().has(-o*I) || this->imag().has(-o*I));
634 /** Evaluation of numbers doesn't do anything at all. */
635 ex numeric::eval(int level) const
637 // Warning: if this is ever gonna do something, the ex ctors from all kinds
638 // of numbers should be checking for status_flags::evaluated.
643 /** Cast numeric into a floating-point object. For example exact numeric(1) is
644 * returned as a 1.0000000000000000000000 and so on according to how Digits is
645 * currently set. In case the object already was a floating point number the
646 * precision is trimmed to match the currently set default.
648 * @param level ignored, only needed for overriding basic::evalf.
649 * @return an ex-handle to a numeric. */
650 ex numeric::evalf(int level) const
652 // level can safely be discarded for numeric objects.
653 return numeric(cln::cl_float(1.0, cln::default_float_format) *
654 (cln::the<cln::cl_N>(value)));
659 int numeric::compare_same_type(const basic &other) const
661 GINAC_ASSERT(is_exactly_a<numeric>(other));
662 const numeric &o = static_cast<const numeric &>(other);
664 return this->compare(o);
668 bool numeric::is_equal_same_type(const basic &other) const
670 GINAC_ASSERT(is_exactly_a<numeric>(other));
671 const numeric &o = static_cast<const numeric &>(other);
673 return this->is_equal(o);
677 unsigned numeric::calchash() const
679 // Base computation of hashvalue on CLN's hashcode. Note: That depends
680 // only on the number's value, not its type or precision (i.e. a true
681 // equivalence relation on numbers). As a consequence, 3 and 3.0 share
682 // the same hashvalue. That shouldn't really matter, though.
683 setflag(status_flags::hash_calculated);
684 hashvalue = golden_ratio_hash(cln::equal_hashcode(cln::the<cln::cl_N>(value)));
690 // new virtual functions which can be overridden by derived classes
696 // non-virtual functions in this class
701 /** Numerical addition method. Adds argument to *this and returns result as
702 * a numeric object. */
703 const numeric numeric::add(const numeric &other) const
705 return numeric(cln::the<cln::cl_N>(value)+cln::the<cln::cl_N>(other.value));
709 /** Numerical subtraction method. Subtracts argument from *this and returns
710 * result as a numeric object. */
711 const numeric numeric::sub(const numeric &other) const
713 return numeric(cln::the<cln::cl_N>(value)-cln::the<cln::cl_N>(other.value));
717 /** Numerical multiplication method. Multiplies *this and argument and returns
718 * result as a numeric object. */
719 const numeric numeric::mul(const numeric &other) const
721 return numeric(cln::the<cln::cl_N>(value)*cln::the<cln::cl_N>(other.value));
725 /** Numerical division method. Divides *this by argument and returns result as
728 * @exception overflow_error (division by zero) */
729 const numeric numeric::div(const numeric &other) const
731 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
732 throw std::overflow_error("numeric::div(): division by zero");
733 return numeric(cln::the<cln::cl_N>(value)/cln::the<cln::cl_N>(other.value));
737 /** Numerical exponentiation. Raises *this to the power given as argument and
738 * returns result as a numeric object. */
739 const numeric numeric::power(const numeric &other) const
741 // Shortcut for efficiency and numeric stability (as in 1.0 exponent):
742 // trap the neutral exponent.
743 if (&other==_num1_p || cln::equal(cln::the<cln::cl_N>(other.value),cln::the<cln::cl_N>(_num1.value)))
746 if (cln::zerop(cln::the<cln::cl_N>(value))) {
747 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
748 throw std::domain_error("numeric::eval(): pow(0,0) is undefined");
749 else if (cln::zerop(cln::realpart(cln::the<cln::cl_N>(other.value))))
750 throw std::domain_error("numeric::eval(): pow(0,I) is undefined");
751 else if (cln::minusp(cln::realpart(cln::the<cln::cl_N>(other.value))))
752 throw std::overflow_error("numeric::eval(): division by zero");
756 return numeric(cln::expt(cln::the<cln::cl_N>(value),cln::the<cln::cl_N>(other.value)));
761 /** Numerical addition method. Adds argument to *this and returns result as
762 * a numeric object on the heap. Use internally only for direct wrapping into
763 * an ex object, where the result would end up on the heap anyways. */
764 const numeric &numeric::add_dyn(const numeric &other) const
766 // Efficiency shortcut: trap the neutral element by pointer. This hack
767 // is supposed to keep the number of distinct numeric objects low.
770 else if (&other==_num0_p)
773 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)+cln::the<cln::cl_N>(other.value)))->
774 setflag(status_flags::dynallocated));
778 /** Numerical subtraction method. Subtracts argument from *this and returns
779 * result as a numeric object on the heap. Use internally only for direct
780 * wrapping into an ex object, where the result would end up on the heap
782 const numeric &numeric::sub_dyn(const numeric &other) const
784 // Efficiency shortcut: trap the neutral exponent (first by pointer). This
785 // hack is supposed to keep the number of distinct numeric objects low.
786 if (&other==_num0_p || cln::zerop(cln::the<cln::cl_N>(other.value)))
789 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)-cln::the<cln::cl_N>(other.value)))->
790 setflag(status_flags::dynallocated));
794 /** Numerical multiplication method. Multiplies *this and argument and returns
795 * result as a numeric object on the heap. Use internally only for direct
796 * wrapping into an ex object, where the result would end up on the heap
798 const numeric &numeric::mul_dyn(const numeric &other) const
800 // Efficiency shortcut: trap the neutral element by pointer. This hack
801 // is supposed to keep the number of distinct numeric objects low.
804 else if (&other==_num1_p)
807 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)*cln::the<cln::cl_N>(other.value)))->
808 setflag(status_flags::dynallocated));
812 /** Numerical division method. Divides *this by argument and returns result as
813 * a numeric object on the heap. Use internally only for direct wrapping
814 * into an ex object, where the result would end up on the heap
817 * @exception overflow_error (division by zero) */
818 const numeric &numeric::div_dyn(const numeric &other) const
820 // Efficiency shortcut: trap the neutral element by pointer. This hack
821 // is supposed to keep the number of distinct numeric objects low.
824 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
825 throw std::overflow_error("division by zero");
826 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)/cln::the<cln::cl_N>(other.value)))->
827 setflag(status_flags::dynallocated));
831 /** Numerical exponentiation. Raises *this to the power given as argument and
832 * returns result as a numeric object on the heap. Use internally only for
833 * direct wrapping into an ex object, where the result would end up on the
835 const numeric &numeric::power_dyn(const numeric &other) const
837 // Efficiency shortcut: trap the neutral exponent (first try by pointer, then
838 // try harder, since calls to cln::expt() below may return amazing results for
839 // floating point exponent 1.0).
840 if (&other==_num1_p || cln::equal(cln::the<cln::cl_N>(other.value),cln::the<cln::cl_N>(_num1.value)))
843 if (cln::zerop(cln::the<cln::cl_N>(value))) {
844 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
845 throw std::domain_error("numeric::eval(): pow(0,0) is undefined");
846 else if (cln::zerop(cln::realpart(cln::the<cln::cl_N>(other.value))))
847 throw std::domain_error("numeric::eval(): pow(0,I) is undefined");
848 else if (cln::minusp(cln::realpart(cln::the<cln::cl_N>(other.value))))
849 throw std::overflow_error("numeric::eval(): division by zero");
853 return static_cast<const numeric &>((new numeric(cln::expt(cln::the<cln::cl_N>(value),cln::the<cln::cl_N>(other.value))))->
854 setflag(status_flags::dynallocated));
858 const numeric &numeric::operator=(int i)
860 return operator=(numeric(i));
864 const numeric &numeric::operator=(unsigned int i)
866 return operator=(numeric(i));
870 const numeric &numeric::operator=(long i)
872 return operator=(numeric(i));
876 const numeric &numeric::operator=(unsigned long i)
878 return operator=(numeric(i));
882 const numeric &numeric::operator=(double d)
884 return operator=(numeric(d));
888 const numeric &numeric::operator=(const char * s)
890 return operator=(numeric(s));
894 /** Inverse of a number. */
895 const numeric numeric::inverse() const
897 if (cln::zerop(cln::the<cln::cl_N>(value)))
898 throw std::overflow_error("numeric::inverse(): division by zero");
899 return numeric(cln::recip(cln::the<cln::cl_N>(value)));
903 /** Return the complex half-plane (left or right) in which the number lies.
904 * csgn(x)==0 for x==0, csgn(x)==1 for Re(x)>0 or Re(x)=0 and Im(x)>0,
905 * csgn(x)==-1 for Re(x)<0 or Re(x)=0 and Im(x)<0.
907 * @see numeric::compare(const numeric &other) */
908 int numeric::csgn() const
910 if (cln::zerop(cln::the<cln::cl_N>(value)))
912 cln::cl_R r = cln::realpart(cln::the<cln::cl_N>(value));
913 if (!cln::zerop(r)) {
919 if (cln::plusp(cln::imagpart(cln::the<cln::cl_N>(value))))
927 /** This method establishes a canonical order on all numbers. For complex
928 * numbers this is not possible in a mathematically consistent way but we need
929 * to establish some order and it ought to be fast. So we simply define it
930 * to be compatible with our method csgn.
932 * @return csgn(*this-other)
933 * @see numeric::csgn() */
934 int numeric::compare(const numeric &other) const
936 // Comparing two real numbers?
937 if (cln::instanceof(value, cln::cl_R_ring) &&
938 cln::instanceof(other.value, cln::cl_R_ring))
939 // Yes, so just cln::compare them
940 return cln::compare(cln::the<cln::cl_R>(value), cln::the<cln::cl_R>(other.value));
942 // No, first cln::compare real parts...
943 cl_signean real_cmp = cln::compare(cln::realpart(cln::the<cln::cl_N>(value)), cln::realpart(cln::the<cln::cl_N>(other.value)));
946 // ...and then the imaginary parts.
947 return cln::compare(cln::imagpart(cln::the<cln::cl_N>(value)), cln::imagpart(cln::the<cln::cl_N>(other.value)));
952 bool numeric::is_equal(const numeric &other) const
954 return cln::equal(cln::the<cln::cl_N>(value),cln::the<cln::cl_N>(other.value));
958 /** True if object is zero. */
959 bool numeric::is_zero() const
961 return cln::zerop(cln::the<cln::cl_N>(value));
965 /** True if object is not complex and greater than zero. */
966 bool numeric::is_positive() const
968 if (cln::instanceof(value, cln::cl_R_ring)) // real?
969 return cln::plusp(cln::the<cln::cl_R>(value));
974 /** True if object is not complex and less than zero. */
975 bool numeric::is_negative() const
977 if (cln::instanceof(value, cln::cl_R_ring)) // real?
978 return cln::minusp(cln::the<cln::cl_R>(value));
983 /** True if object is a non-complex integer. */
984 bool numeric::is_integer() const
986 return cln::instanceof(value, cln::cl_I_ring);
990 /** True if object is an exact integer greater than zero. */
991 bool numeric::is_pos_integer() const
993 return (cln::instanceof(value, cln::cl_I_ring) && cln::plusp(cln::the<cln::cl_I>(value)));
997 /** True if object is an exact integer greater or equal zero. */
998 bool numeric::is_nonneg_integer() const
1000 return (cln::instanceof(value, cln::cl_I_ring) && !cln::minusp(cln::the<cln::cl_I>(value)));
1004 /** True if object is an exact even integer. */
1005 bool numeric::is_even() const
1007 return (cln::instanceof(value, cln::cl_I_ring) && cln::evenp(cln::the<cln::cl_I>(value)));
1011 /** True if object is an exact odd integer. */
1012 bool numeric::is_odd() const
1014 return (cln::instanceof(value, cln::cl_I_ring) && cln::oddp(cln::the<cln::cl_I>(value)));
1018 /** Probabilistic primality test.
1020 * @return true if object is exact integer and prime. */
1021 bool numeric::is_prime() const
1023 return (cln::instanceof(value, cln::cl_I_ring) // integer?
1024 && cln::plusp(cln::the<cln::cl_I>(value)) // positive?
1025 && cln::isprobprime(cln::the<cln::cl_I>(value)));
1029 /** True if object is an exact rational number, may even be complex
1030 * (denominator may be unity). */
1031 bool numeric::is_rational() const
1033 return cln::instanceof(value, cln::cl_RA_ring);
1037 /** True if object is a real integer, rational or float (but not complex). */
1038 bool numeric::is_real() const
1040 return cln::instanceof(value, cln::cl_R_ring);
1044 bool numeric::operator==(const numeric &other) const
1046 return cln::equal(cln::the<cln::cl_N>(value), cln::the<cln::cl_N>(other.value));
1050 bool numeric::operator!=(const numeric &other) const
1052 return !cln::equal(cln::the<cln::cl_N>(value), cln::the<cln::cl_N>(other.value));
1056 /** True if object is element of the domain of integers extended by I, i.e. is
1057 * of the form a+b*I, where a and b are integers. */
1058 bool numeric::is_cinteger() const
1060 if (cln::instanceof(value, cln::cl_I_ring))
1062 else if (!this->is_real()) { // complex case, handle n+m*I
1063 if (cln::instanceof(cln::realpart(cln::the<cln::cl_N>(value)), cln::cl_I_ring) &&
1064 cln::instanceof(cln::imagpart(cln::the<cln::cl_N>(value)), cln::cl_I_ring))
1071 /** True if object is an exact rational number, may even be complex
1072 * (denominator may be unity). */
1073 bool numeric::is_crational() const
1075 if (cln::instanceof(value, cln::cl_RA_ring))
1077 else if (!this->is_real()) { // complex case, handle Q(i):
1078 if (cln::instanceof(cln::realpart(cln::the<cln::cl_N>(value)), cln::cl_RA_ring) &&
1079 cln::instanceof(cln::imagpart(cln::the<cln::cl_N>(value)), cln::cl_RA_ring))
1086 /** Numerical comparison: less.
1088 * @exception invalid_argument (complex inequality) */
1089 bool numeric::operator<(const numeric &other) const
1091 if (this->is_real() && other.is_real())
1092 return (cln::the<cln::cl_R>(value) < cln::the<cln::cl_R>(other.value));
1093 throw std::invalid_argument("numeric::operator<(): complex inequality");
1097 /** Numerical comparison: less or equal.
1099 * @exception invalid_argument (complex inequality) */
1100 bool numeric::operator<=(const numeric &other) const
1102 if (this->is_real() && other.is_real())
1103 return (cln::the<cln::cl_R>(value) <= cln::the<cln::cl_R>(other.value));
1104 throw std::invalid_argument("numeric::operator<=(): complex inequality");
1108 /** Numerical comparison: greater.
1110 * @exception invalid_argument (complex inequality) */
1111 bool numeric::operator>(const numeric &other) const
1113 if (this->is_real() && other.is_real())
1114 return (cln::the<cln::cl_R>(value) > cln::the<cln::cl_R>(other.value));
1115 throw std::invalid_argument("numeric::operator>(): complex inequality");
1119 /** Numerical comparison: greater or equal.
1121 * @exception invalid_argument (complex inequality) */
1122 bool numeric::operator>=(const numeric &other) const
1124 if (this->is_real() && other.is_real())
1125 return (cln::the<cln::cl_R>(value) >= cln::the<cln::cl_R>(other.value));
1126 throw std::invalid_argument("numeric::operator>=(): complex inequality");
1130 /** Converts numeric types to machine's int. You should check with
1131 * is_integer() if the number is really an integer before calling this method.
1132 * You may also consider checking the range first. */
1133 int numeric::to_int() const
1135 GINAC_ASSERT(this->is_integer());
1136 return cln::cl_I_to_int(cln::the<cln::cl_I>(value));
1140 /** Converts numeric types to machine's long. You should check with
1141 * is_integer() if the number is really an integer before calling this method.
1142 * You may also consider checking the range first. */
1143 long numeric::to_long() const
1145 GINAC_ASSERT(this->is_integer());
1146 return cln::cl_I_to_long(cln::the<cln::cl_I>(value));
1150 /** Converts numeric types to machine's double. You should check with is_real()
1151 * if the number is really not complex before calling this method. */
1152 double numeric::to_double() const
1154 GINAC_ASSERT(this->is_real());
1155 return cln::double_approx(cln::realpart(cln::the<cln::cl_N>(value)));
1159 /** Returns a new CLN object of type cl_N, representing the value of *this.
1160 * This method may be used when mixing GiNaC and CLN in one project.
1162 cln::cl_N numeric::to_cl_N() const
1164 return cln::cl_N(cln::the<cln::cl_N>(value));
1168 /** Real part of a number. */
1169 const numeric numeric::real() const
1171 return numeric(cln::realpart(cln::the<cln::cl_N>(value)));
1175 /** Imaginary part of a number. */
1176 const numeric numeric::imag() const
1178 return numeric(cln::imagpart(cln::the<cln::cl_N>(value)));
1182 /** Numerator. Computes the numerator of rational numbers, rationalized
1183 * numerator of complex if real and imaginary part are both rational numbers
1184 * (i.e numer(4/3+5/6*I) == 8+5*I), the number carrying the sign in all other
1186 const numeric numeric::numer() const
1188 if (cln::instanceof(value, cln::cl_I_ring))
1189 return numeric(*this); // integer case
1191 else if (cln::instanceof(value, cln::cl_RA_ring))
1192 return numeric(cln::numerator(cln::the<cln::cl_RA>(value)));
1194 else if (!this->is_real()) { // complex case, handle Q(i):
1195 const cln::cl_RA r = cln::the<cln::cl_RA>(cln::realpart(cln::the<cln::cl_N>(value)));
1196 const cln::cl_RA i = cln::the<cln::cl_RA>(cln::imagpart(cln::the<cln::cl_N>(value)));
1197 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_I_ring))
1198 return numeric(*this);
1199 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_RA_ring))
1200 return numeric(cln::complex(r*cln::denominator(i), cln::numerator(i)));
1201 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_I_ring))
1202 return numeric(cln::complex(cln::numerator(r), i*cln::denominator(r)));
1203 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_RA_ring)) {
1204 const cln::cl_I s = cln::lcm(cln::denominator(r), cln::denominator(i));
1205 return numeric(cln::complex(cln::numerator(r)*(cln::exquo(s,cln::denominator(r))),
1206 cln::numerator(i)*(cln::exquo(s,cln::denominator(i)))));
1209 // at least one float encountered
1210 return numeric(*this);
1214 /** Denominator. Computes the denominator of rational numbers, common integer
1215 * denominator of complex if real and imaginary part are both rational numbers
1216 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
1217 const numeric numeric::denom() const
1219 if (cln::instanceof(value, cln::cl_I_ring))
1220 return _num1; // integer case
1222 if (cln::instanceof(value, cln::cl_RA_ring))
1223 return numeric(cln::denominator(cln::the<cln::cl_RA>(value)));
1225 if (!this->is_real()) { // complex case, handle Q(i):
1226 const cln::cl_RA r = cln::the<cln::cl_RA>(cln::realpart(cln::the<cln::cl_N>(value)));
1227 const cln::cl_RA i = cln::the<cln::cl_RA>(cln::imagpart(cln::the<cln::cl_N>(value)));
1228 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_I_ring))
1230 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_RA_ring))
1231 return numeric(cln::denominator(i));
1232 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_I_ring))
1233 return numeric(cln::denominator(r));
1234 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_RA_ring))
1235 return numeric(cln::lcm(cln::denominator(r), cln::denominator(i)));
1237 // at least one float encountered
1242 /** Size in binary notation. For integers, this is the smallest n >= 0 such
1243 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
1244 * 2^(n-1) <= x < 2^n.
1246 * @return number of bits (excluding sign) needed to represent that number
1247 * in two's complement if it is an integer, 0 otherwise. */
1248 int numeric::int_length() const
1250 if (cln::instanceof(value, cln::cl_I_ring))
1251 return cln::integer_length(cln::the<cln::cl_I>(value));
1260 /** Imaginary unit. This is not a constant but a numeric since we are
1261 * natively handing complex numbers anyways, so in each expression containing
1262 * an I it is automatically eval'ed away anyhow. */
1263 const numeric I = numeric(cln::complex(cln::cl_I(0),cln::cl_I(1)));
1266 /** Exponential function.
1268 * @return arbitrary precision numerical exp(x). */
1269 const numeric exp(const numeric &x)
1271 return cln::exp(x.to_cl_N());
1275 /** Natural logarithm.
1277 * @param z complex number
1278 * @return arbitrary precision numerical log(x).
1279 * @exception pole_error("log(): logarithmic pole",0) */
1280 const numeric log(const numeric &z)
1283 throw pole_error("log(): logarithmic pole",0);
1284 return cln::log(z.to_cl_N());
1288 /** Numeric sine (trigonometric function).
1290 * @return arbitrary precision numerical sin(x). */
1291 const numeric sin(const numeric &x)
1293 return cln::sin(x.to_cl_N());
1297 /** Numeric cosine (trigonometric function).
1299 * @return arbitrary precision numerical cos(x). */
1300 const numeric cos(const numeric &x)
1302 return cln::cos(x.to_cl_N());
1306 /** Numeric tangent (trigonometric function).
1308 * @return arbitrary precision numerical tan(x). */
1309 const numeric tan(const numeric &x)
1311 return cln::tan(x.to_cl_N());
1315 /** Numeric inverse sine (trigonometric function).
1317 * @return arbitrary precision numerical asin(x). */
1318 const numeric asin(const numeric &x)
1320 return cln::asin(x.to_cl_N());
1324 /** Numeric inverse cosine (trigonometric function).
1326 * @return arbitrary precision numerical acos(x). */
1327 const numeric acos(const numeric &x)
1329 return cln::acos(x.to_cl_N());
1335 * @param z complex number
1337 * @exception pole_error("atan(): logarithmic pole",0) */
1338 const numeric atan(const numeric &x)
1341 x.real().is_zero() &&
1342 abs(x.imag()).is_equal(_num1))
1343 throw pole_error("atan(): logarithmic pole",0);
1344 return cln::atan(x.to_cl_N());
1350 * @param x real number
1351 * @param y real number
1352 * @return atan(y/x) */
1353 const numeric atan(const numeric &y, const numeric &x)
1355 if (x.is_real() && y.is_real())
1356 return cln::atan(cln::the<cln::cl_R>(x.to_cl_N()),
1357 cln::the<cln::cl_R>(y.to_cl_N()));
1359 throw std::invalid_argument("atan(): complex argument");
1363 /** Numeric hyperbolic sine (trigonometric function).
1365 * @return arbitrary precision numerical sinh(x). */
1366 const numeric sinh(const numeric &x)
1368 return cln::sinh(x.to_cl_N());
1372 /** Numeric hyperbolic cosine (trigonometric function).
1374 * @return arbitrary precision numerical cosh(x). */
1375 const numeric cosh(const numeric &x)
1377 return cln::cosh(x.to_cl_N());
1381 /** Numeric hyperbolic tangent (trigonometric function).
1383 * @return arbitrary precision numerical tanh(x). */
1384 const numeric tanh(const numeric &x)
1386 return cln::tanh(x.to_cl_N());
1390 /** Numeric inverse hyperbolic sine (trigonometric function).
1392 * @return arbitrary precision numerical asinh(x). */
1393 const numeric asinh(const numeric &x)
1395 return cln::asinh(x.to_cl_N());
1399 /** Numeric inverse hyperbolic cosine (trigonometric function).
1401 * @return arbitrary precision numerical acosh(x). */
1402 const numeric acosh(const numeric &x)
1404 return cln::acosh(x.to_cl_N());
1408 /** Numeric inverse hyperbolic tangent (trigonometric function).
1410 * @return arbitrary precision numerical atanh(x). */
1411 const numeric atanh(const numeric &x)
1413 return cln::atanh(x.to_cl_N());
1417 /*static cln::cl_N Li2_series(const ::cl_N &x,
1418 const ::float_format_t &prec)
1420 // Note: argument must be in the unit circle
1421 // This is very inefficient unless we have fast floating point Bernoulli
1422 // numbers implemented!
1423 cln::cl_N c1 = -cln::log(1-x);
1425 // hard-wire the first two Bernoulli numbers
1426 cln::cl_N acc = c1 - cln::square(c1)/4;
1428 cln::cl_F pisq = cln::square(cln::cl_pi(prec)); // pi^2
1429 cln::cl_F piac = cln::cl_float(1, prec); // accumulator: pi^(2*i)
1431 c1 = cln::square(c1);
1435 aug = c2 * (*(bernoulli(numeric(2*i)).clnptr())) / cln::factorial(2*i+1);
1436 // aug = c2 * cln::cl_I(i%2 ? 1 : -1) / cln::cl_I(2*i+1) * cln::cl_zeta(2*i, prec) / piac / (cln::cl_I(1)<<(2*i-1));
1439 } while (acc != acc+aug);
1443 /** Numeric evaluation of Dilogarithm within circle of convergence (unit
1444 * circle) using a power series. */
1445 static cln::cl_N Li2_series(const cln::cl_N &x,
1446 const cln::float_format_t &prec)
1448 // Note: argument must be in the unit circle
1450 cln::cl_N num = cln::complex(cln::cl_float(1, prec), 0);
1455 den = den + i; // 1, 4, 9, 16, ...
1459 } while (acc != acc+aug);
1463 /** Folds Li2's argument inside a small rectangle to enhance convergence. */
1464 static cln::cl_N Li2_projection(const cln::cl_N &x,
1465 const cln::float_format_t &prec)
1467 const cln::cl_R re = cln::realpart(x);
1468 const cln::cl_R im = cln::imagpart(x);
1469 if (re > cln::cl_F(".5"))
1470 // zeta(2) - Li2(1-x) - log(x)*log(1-x)
1472 - Li2_series(1-x, prec)
1473 - cln::log(x)*cln::log(1-x));
1474 if ((re <= 0 && cln::abs(im) > cln::cl_F(".75")) || (re < cln::cl_F("-.5")))
1475 // -log(1-x)^2 / 2 - Li2(x/(x-1))
1476 return(- cln::square(cln::log(1-x))/2
1477 - Li2_series(x/(x-1), prec));
1478 if (re > 0 && cln::abs(im) > cln::cl_LF(".75"))
1479 // Li2(x^2)/2 - Li2(-x)
1480 return(Li2_projection(cln::square(x), prec)/2
1481 - Li2_projection(-x, prec));
1482 return Li2_series(x, prec);
1485 /** Numeric evaluation of Dilogarithm. The domain is the entire complex plane,
1486 * the branch cut lies along the positive real axis, starting at 1 and
1487 * continuous with quadrant IV.
1489 * @return arbitrary precision numerical Li2(x). */
1490 const numeric Li2(const numeric &x)
1495 // what is the desired float format?
1496 // first guess: default format
1497 cln::float_format_t prec = cln::default_float_format;
1498 const cln::cl_N value = x.to_cl_N();
1499 // second guess: the argument's format
1500 if (!x.real().is_rational())
1501 prec = cln::float_format(cln::the<cln::cl_F>(cln::realpart(value)));
1502 else if (!x.imag().is_rational())
1503 prec = cln::float_format(cln::the<cln::cl_F>(cln::imagpart(value)));
1505 if (cln::the<cln::cl_N>(value)==1) // may cause trouble with log(1-x)
1506 return cln::zeta(2, prec);
1508 if (cln::abs(value) > 1)
1509 // -log(-x)^2 / 2 - zeta(2) - Li2(1/x)
1510 return(- cln::square(cln::log(-value))/2
1511 - cln::zeta(2, prec)
1512 - Li2_projection(cln::recip(value), prec));
1514 return Li2_projection(x.to_cl_N(), prec);
1518 /** Numeric evaluation of Riemann's Zeta function. Currently works only for
1519 * integer arguments. */
1520 const numeric zeta(const numeric &x)
1522 // A dirty hack to allow for things like zeta(3.0), since CLN currently
1523 // only knows about integer arguments and zeta(3).evalf() automatically
1524 // cascades down to zeta(3.0).evalf(). The trick is to rely on 3.0-3
1525 // being an exact zero for CLN, which can be tested and then we can just
1526 // pass the number casted to an int:
1528 const int aux = (int)(cln::double_approx(cln::the<cln::cl_R>(x.to_cl_N())));
1529 if (cln::zerop(x.to_cl_N()-aux))
1530 return cln::zeta(aux);
1536 /** The Gamma function.
1537 * This is only a stub! */
1538 const numeric lgamma(const numeric &x)
1542 const numeric tgamma(const numeric &x)
1548 /** The psi function (aka polygamma function).
1549 * This is only a stub! */
1550 const numeric psi(const numeric &x)
1556 /** The psi functions (aka polygamma functions).
1557 * This is only a stub! */
1558 const numeric psi(const numeric &n, const numeric &x)
1564 /** Factorial combinatorial function.
1566 * @param n integer argument >= 0
1567 * @exception range_error (argument must be integer >= 0) */
1568 const numeric factorial(const numeric &n)
1570 if (!n.is_nonneg_integer())
1571 throw std::range_error("numeric::factorial(): argument must be integer >= 0");
1572 return numeric(cln::factorial(n.to_int()));
1576 /** The double factorial combinatorial function. (Scarcely used, but still
1577 * useful in cases, like for exact results of tgamma(n+1/2) for instance.)
1579 * @param n integer argument >= -1
1580 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == (-1)!! == 1
1581 * @exception range_error (argument must be integer >= -1) */
1582 const numeric doublefactorial(const numeric &n)
1584 if (n.is_equal(_num_1))
1587 if (!n.is_nonneg_integer())
1588 throw std::range_error("numeric::doublefactorial(): argument must be integer >= -1");
1590 return numeric(cln::doublefactorial(n.to_int()));
1594 /** The Binomial coefficients. It computes the binomial coefficients. For
1595 * integer n and k and positive n this is the number of ways of choosing k
1596 * objects from n distinct objects. If n is negative, the formula
1597 * binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */
1598 const numeric binomial(const numeric &n, const numeric &k)
1600 if (n.is_integer() && k.is_integer()) {
1601 if (n.is_nonneg_integer()) {
1602 if (k.compare(n)!=1 && k.compare(_num0)!=-1)
1603 return numeric(cln::binomial(n.to_int(),k.to_int()));
1607 return _num_1.power(k)*binomial(k-n-_num1,k);
1611 // should really be gamma(n+1)/gamma(r+1)/gamma(n-r+1) or a suitable limit
1612 throw std::range_error("numeric::binomial(): don´t know how to evaluate that.");
1616 /** Bernoulli number. The nth Bernoulli number is the coefficient of x^n/n!
1617 * in the expansion of the function x/(e^x-1).
1619 * @return the nth Bernoulli number (a rational number).
1620 * @exception range_error (argument must be integer >= 0) */
1621 const numeric bernoulli(const numeric &nn)
1623 if (!nn.is_integer() || nn.is_negative())
1624 throw std::range_error("numeric::bernoulli(): argument must be integer >= 0");
1628 // The Bernoulli numbers are rational numbers that may be computed using
1631 // B_n = - 1/(n+1) * sum_{k=0}^{n-1}(binomial(n+1,k)*B_k)
1633 // with B(0) = 1. Since the n'th Bernoulli number depends on all the
1634 // previous ones, the computation is necessarily very expensive. There are
1635 // several other ways of computing them, a particularly good one being
1639 // for (unsigned i=0; i<n; i++) {
1640 // c = exquo(c*(i-n),(i+2));
1641 // Bern = Bern + c*s/(i+2);
1642 // s = s + expt_pos(cl_I(i+2),n);
1646 // But if somebody works with the n'th Bernoulli number she is likely to
1647 // also need all previous Bernoulli numbers. So we need a complete remember
1648 // table and above divide and conquer algorithm is not suited to build one
1649 // up. The formula below accomplishes this. It is a modification of the
1650 // defining formula above but the computation of the binomial coefficients
1651 // is carried along in an inline fashion. It also honors the fact that
1652 // B_n is zero when n is odd and greater than 1.
1654 // (There is an interesting relation with the tangent polynomials described
1655 // in `Concrete Mathematics', which leads to a program a little faster as
1656 // our implementation below, but it requires storing one such polynomial in
1657 // addition to the remember table. This doubles the memory footprint so
1658 // we don't use it.)
1660 const unsigned n = nn.to_int();
1662 // the special cases not covered by the algorithm below
1664 return (n==1) ? _num_1_2 : _num0;
1668 // store nonvanishing Bernoulli numbers here
1669 static std::vector< cln::cl_RA > results;
1670 static unsigned next_r = 0;
1672 // algorithm not applicable to B(2), so just store it
1674 results.push_back(cln::recip(cln::cl_RA(6)));
1678 return results[n/2-1];
1680 results.reserve(n/2);
1681 for (unsigned p=next_r; p<=n; p+=2) {
1682 cln::cl_I c = 1; // seed for binonmial coefficients
1683 cln::cl_RA b = cln::cl_RA(1-p)/2;
1684 const unsigned p3 = p+3;
1685 const unsigned pm = p-2;
1687 // test if intermediate unsigned int can be represented by immediate
1688 // objects by CLN (i.e. < 2^29 for 32 Bit machines, see <cln/object.h>)
1689 if (p < (1UL<<cl_value_len/2)) {
1690 for (i=2, k=1, p_2=p/2; i<=pm; i+=2, ++k, --p_2) {
1691 c = cln::exquo(c * ((p3-i) * p_2), (i-1)*k);
1692 b = b + c*results[k-1];
1695 for (i=2, k=1, p_2=p/2; i<=pm; i+=2, ++k, --p_2) {
1696 c = cln::exquo((c * (p3-i)) * p_2, cln::cl_I(i-1)*k);
1697 b = b + c*results[k-1];
1700 results.push_back(-b/(p+1));
1703 return results[n/2-1];
1707 /** Fibonacci number. The nth Fibonacci number F(n) is defined by the
1708 * recurrence formula F(n)==F(n-1)+F(n-2) with F(0)==0 and F(1)==1.
1710 * @param n an integer
1711 * @return the nth Fibonacci number F(n) (an integer number)
1712 * @exception range_error (argument must be an integer) */
1713 const numeric fibonacci(const numeric &n)
1715 if (!n.is_integer())
1716 throw std::range_error("numeric::fibonacci(): argument must be integer");
1719 // The following addition formula holds:
1721 // F(n+m) = F(m-1)*F(n) + F(m)*F(n+1) for m >= 1, n >= 0.
1723 // (Proof: For fixed m, the LHS and the RHS satisfy the same recurrence
1724 // w.r.t. n, and the initial values (n=0, n=1) agree. Hence all values
1726 // Replace m by m+1:
1727 // F(n+m+1) = F(m)*F(n) + F(m+1)*F(n+1) for m >= 0, n >= 0
1728 // Now put in m = n, to get
1729 // F(2n) = (F(n+1)-F(n))*F(n) + F(n)*F(n+1) = F(n)*(2*F(n+1) - F(n))
1730 // F(2n+1) = F(n)^2 + F(n+1)^2
1732 // F(2n+2) = F(n+1)*(2*F(n) + F(n+1))
1735 if (n.is_negative())
1737 return -fibonacci(-n);
1739 return fibonacci(-n);
1743 cln::cl_I m = cln::the<cln::cl_I>(n.to_cl_N()) >> 1L; // floor(n/2);
1744 for (uintL bit=cln::integer_length(m); bit>0; --bit) {
1745 // Since a squaring is cheaper than a multiplication, better use
1746 // three squarings instead of one multiplication and two squarings.
1747 cln::cl_I u2 = cln::square(u);
1748 cln::cl_I v2 = cln::square(v);
1749 if (cln::logbitp(bit-1, m)) {
1750 v = cln::square(u + v) - u2;
1753 u = v2 - cln::square(v - u);
1758 // Here we don't use the squaring formula because one multiplication
1759 // is cheaper than two squarings.
1760 return u * ((v << 1) - u);
1762 return cln::square(u) + cln::square(v);
1766 /** Absolute value. */
1767 const numeric abs(const numeric& x)
1769 return cln::abs(x.to_cl_N());
1773 /** Modulus (in positive representation).
1774 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1775 * sign of a or is zero. This is different from Maple's modp, where the sign
1776 * of b is ignored. It is in agreement with Mathematica's Mod.
1778 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1779 * integer, 0 otherwise. */
1780 const numeric mod(const numeric &a, const numeric &b)
1782 if (a.is_integer() && b.is_integer())
1783 return cln::mod(cln::the<cln::cl_I>(a.to_cl_N()),
1784 cln::the<cln::cl_I>(b.to_cl_N()));
1790 /** Modulus (in symmetric representation).
1791 * Equivalent to Maple's mods.
1793 * @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1794 const numeric smod(const numeric &a, const numeric &b)
1796 if (a.is_integer() && b.is_integer()) {
1797 const cln::cl_I b2 = cln::ceiling1(cln::the<cln::cl_I>(b.to_cl_N()) >> 1) - 1;
1798 return cln::mod(cln::the<cln::cl_I>(a.to_cl_N()) + b2,
1799 cln::the<cln::cl_I>(b.to_cl_N())) - b2;
1805 /** Numeric integer remainder.
1806 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1807 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1808 * sign of a or is zero.
1810 * @return remainder of a/b if both are integer, 0 otherwise.
1811 * @exception overflow_error (division by zero) if b is zero. */
1812 const numeric irem(const numeric &a, const numeric &b)
1815 throw std::overflow_error("numeric::irem(): division by zero");
1816 if (a.is_integer() && b.is_integer())
1817 return cln::rem(cln::the<cln::cl_I>(a.to_cl_N()),
1818 cln::the<cln::cl_I>(b.to_cl_N()));
1824 /** Numeric integer remainder.
1825 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1826 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1827 * and irem(a,b) has the sign of a or is zero.
1829 * @return remainder of a/b and quotient stored in q if both are integer,
1831 * @exception overflow_error (division by zero) if b is zero. */
1832 const numeric irem(const numeric &a, const numeric &b, numeric &q)
1835 throw std::overflow_error("numeric::irem(): division by zero");
1836 if (a.is_integer() && b.is_integer()) {
1837 const cln::cl_I_div_t rem_quo = cln::truncate2(cln::the<cln::cl_I>(a.to_cl_N()),
1838 cln::the<cln::cl_I>(b.to_cl_N()));
1839 q = rem_quo.quotient;
1840 return rem_quo.remainder;
1848 /** Numeric integer quotient.
1849 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1851 * @return truncated quotient of a/b if both are integer, 0 otherwise.
1852 * @exception overflow_error (division by zero) if b is zero. */
1853 const numeric iquo(const numeric &a, const numeric &b)
1856 throw std::overflow_error("numeric::iquo(): division by zero");
1857 if (a.is_integer() && b.is_integer())
1858 return cln::truncate1(cln::the<cln::cl_I>(a.to_cl_N()),
1859 cln::the<cln::cl_I>(b.to_cl_N()));
1865 /** Numeric integer quotient.
1866 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1867 * r == a - iquo(a,b,r)*b.
1869 * @return truncated quotient of a/b and remainder stored in r if both are
1870 * integer, 0 otherwise.
1871 * @exception overflow_error (division by zero) if b is zero. */
1872 const numeric iquo(const numeric &a, const numeric &b, numeric &r)
1875 throw std::overflow_error("numeric::iquo(): division by zero");
1876 if (a.is_integer() && b.is_integer()) {
1877 const cln::cl_I_div_t rem_quo = cln::truncate2(cln::the<cln::cl_I>(a.to_cl_N()),
1878 cln::the<cln::cl_I>(b.to_cl_N()));
1879 r = rem_quo.remainder;
1880 return rem_quo.quotient;
1888 /** Greatest Common Divisor.
1890 * @return The GCD of two numbers if both are integer, a numerical 1
1891 * if they are not. */
1892 const numeric gcd(const numeric &a, const numeric &b)
1894 if (a.is_integer() && b.is_integer())
1895 return cln::gcd(cln::the<cln::cl_I>(a.to_cl_N()),
1896 cln::the<cln::cl_I>(b.to_cl_N()));
1902 /** Least Common Multiple.
1904 * @return The LCM of two numbers if both are integer, the product of those
1905 * two numbers if they are not. */
1906 const numeric lcm(const numeric &a, const numeric &b)
1908 if (a.is_integer() && b.is_integer())
1909 return cln::lcm(cln::the<cln::cl_I>(a.to_cl_N()),
1910 cln::the<cln::cl_I>(b.to_cl_N()));
1916 /** Numeric square root.
1917 * If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4)
1918 * should return integer 2.
1920 * @param z numeric argument
1921 * @return square root of z. Branch cut along negative real axis, the negative
1922 * real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part
1923 * where imag(z)>0. */
1924 const numeric sqrt(const numeric &z)
1926 return cln::sqrt(z.to_cl_N());
1930 /** Integer numeric square root. */
1931 const numeric isqrt(const numeric &x)
1933 if (x.is_integer()) {
1935 cln::isqrt(cln::the<cln::cl_I>(x.to_cl_N()), &root);
1942 /** Floating point evaluation of Archimedes' constant Pi. */
1945 return numeric(cln::pi(cln::default_float_format));
1949 /** Floating point evaluation of Euler's constant gamma. */
1952 return numeric(cln::eulerconst(cln::default_float_format));
1956 /** Floating point evaluation of Catalan's constant. */
1959 return numeric(cln::catalanconst(cln::default_float_format));
1963 /** _numeric_digits default ctor, checking for singleton invariance. */
1964 _numeric_digits::_numeric_digits()
1967 // It initializes to 17 digits, because in CLN float_format(17) turns out
1968 // to be 61 (<64) while float_format(18)=65. The reason is we want to
1969 // have a cl_LF instead of cl_SF, cl_FF or cl_DF.
1971 throw(std::runtime_error("I told you not to do instantiate me!"));
1973 cln::default_float_format = cln::float_format(17);
1977 /** Assign a native long to global Digits object. */
1978 _numeric_digits& _numeric_digits::operator=(long prec)
1981 cln::default_float_format = cln::float_format(prec);
1986 /** Convert global Digits object to native type long. */
1987 _numeric_digits::operator long()
1989 // BTW, this is approx. unsigned(cln::default_float_format*0.301)-1
1990 return (long)digits;
1994 /** Append global Digits object to ostream. */
1995 void _numeric_digits::print(std::ostream &os) const
2001 std::ostream& operator<<(std::ostream &os, const _numeric_digits &e)
2008 // static member variables
2013 bool _numeric_digits::too_late = false;
2016 /** Accuracy in decimal digits. Only object of this type! Can be set using
2017 * assignment from C++ unsigned ints and evaluated like any built-in type. */
2018 _numeric_digits Digits;
2020 } // namespace GiNaC