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(numeric, basic)
66 // default ctor, dtor, copy ctor, assignment operator and helpers
69 /** default ctor. Numerically it initializes to an integer zero. */
70 numeric::numeric() : basic(TINFO_numeric)
73 setflag(status_flags::evaluated | status_flags::expanded);
76 void numeric::copy(const numeric &other)
78 inherited::copy(other);
82 DEFAULT_DESTROY(numeric)
90 numeric::numeric(int i) : basic(TINFO_numeric)
92 // Not the whole int-range is available if we don't cast to long
93 // first. This is due to the behaviour of the cl_I-ctor, which
94 // emphasizes efficiency. However, if the integer is small enough
95 // we save space and dereferences by using an immediate type.
96 // (C.f. <cln/object.h>)
97 if (i < (1U<<cl_value_len-1))
100 value = cln::cl_I((long) i);
101 setflag(status_flags::evaluated | status_flags::expanded);
105 numeric::numeric(unsigned int i) : basic(TINFO_numeric)
107 // Not the whole uint-range is available if we don't cast to ulong
108 // first. This is due to the behaviour of the cl_I-ctor, which
109 // emphasizes efficiency. However, if the integer is small enough
110 // we save space and dereferences by using an immediate type.
111 // (C.f. <cln/object.h>)
112 if (i < (1U<<cl_value_len-1))
113 value = cln::cl_I(i);
115 value = cln::cl_I((unsigned long) i);
116 setflag(status_flags::evaluated | status_flags::expanded);
120 numeric::numeric(long i) : basic(TINFO_numeric)
122 value = cln::cl_I(i);
123 setflag(status_flags::evaluated | status_flags::expanded);
127 numeric::numeric(unsigned long i) : basic(TINFO_numeric)
129 value = cln::cl_I(i);
130 setflag(status_flags::evaluated | status_flags::expanded);
133 /** Ctor for rational numerics a/b.
135 * @exception overflow_error (division by zero) */
136 numeric::numeric(long numer, long denom) : basic(TINFO_numeric)
139 throw std::overflow_error("division by zero");
140 value = cln::cl_I(numer) / cln::cl_I(denom);
141 setflag(status_flags::evaluated | status_flags::expanded);
145 numeric::numeric(double d) : basic(TINFO_numeric)
147 // We really want to explicitly use the type cl_LF instead of the
148 // more general cl_F, since that would give us a cl_DF only which
149 // will not be promoted to cl_LF if overflow occurs:
150 value = cln::cl_float(d, cln::default_float_format);
151 setflag(status_flags::evaluated | status_flags::expanded);
155 /** ctor from C-style string. It also accepts complex numbers in GiNaC
156 * notation like "2+5*I". */
157 numeric::numeric(const char *s) : basic(TINFO_numeric)
159 cln::cl_N ctorval = 0;
160 // parse complex numbers (functional but not completely safe, unfortunately
161 // std::string does not understand regexpese):
162 // ss should represent a simple sum like 2+5*I
164 std::string::size_type delim;
166 // make this implementation safe by adding explicit sign
167 if (ss.at(0) != '+' && ss.at(0) != '-' && ss.at(0) != '#')
170 // We use 'E' as exponent marker in the output, but some people insist on
171 // writing 'e' at input, so let's substitute them right at the beginning:
172 while ((delim = ss.find("e"))!=std::string::npos)
173 ss.replace(delim,1,"E");
177 // chop ss into terms from left to right
179 bool imaginary = false;
180 delim = ss.find_first_of(std::string("+-"),1);
181 // Do we have an exponent marker like "31.415E-1"? If so, hop on!
182 if (delim!=std::string::npos && ss.at(delim-1)=='E')
183 delim = ss.find_first_of(std::string("+-"),delim+1);
184 term = ss.substr(0,delim);
185 if (delim!=std::string::npos)
186 ss = ss.substr(delim);
187 // is the term imaginary?
188 if (term.find("I")!=std::string::npos) {
190 term.erase(term.find("I"),1);
192 if (term.find("*")!=std::string::npos)
193 term.erase(term.find("*"),1);
194 // correct for trivial +/-I without explicit factor on I:
199 if (term.find('.')!=std::string::npos || term.find('E')!=std::string::npos) {
200 // CLN's short type cl_SF is not very useful within the GiNaC
201 // framework where we are mainly interested in the arbitrary
202 // precision type cl_LF. Hence we go straight to the construction
203 // of generic floats. In order to create them we have to convert
204 // our own floating point notation used for output and construction
205 // from char * to CLN's generic notation:
206 // 3.14 --> 3.14e0_<Digits>
207 // 31.4E-1 --> 31.4e-1_<Digits>
209 // No exponent marker? Let's add a trivial one.
210 if (term.find("E")==std::string::npos)
213 term = term.replace(term.find("E"),1,"e");
214 // append _<Digits> to term
215 term += "_" + ToString((unsigned)Digits);
216 // construct float using cln::cl_F(const char *) ctor.
218 ctorval = ctorval + cln::complex(cln::cl_I(0),cln::cl_F(term.c_str()));
220 ctorval = ctorval + cln::cl_F(term.c_str());
222 // this is not a floating point number...
224 ctorval = ctorval + cln::complex(cln::cl_I(0),cln::cl_R(term.c_str()));
226 ctorval = ctorval + cln::cl_R(term.c_str());
228 } while (delim != std::string::npos);
230 setflag(status_flags::evaluated | status_flags::expanded);
234 /** Ctor from CLN types. This is for the initiated user or internal use
236 numeric::numeric(const cln::cl_N &z) : basic(TINFO_numeric)
239 setflag(status_flags::evaluated | status_flags::expanded);
246 numeric::numeric(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
248 cln::cl_N ctorval = 0;
250 // Read number as string
252 if (n.find_string("number", str)) {
253 std::istringstream s(str);
254 cln::cl_idecoded_float re, im;
258 case 'R': // Integer-decoded real number
259 s >> re.sign >> re.mantissa >> re.exponent;
260 ctorval = re.sign * re.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), re.exponent);
262 case 'C': // Integer-decoded complex number
263 s >> re.sign >> re.mantissa >> re.exponent;
264 s >> im.sign >> im.mantissa >> im.exponent;
265 ctorval = cln::complex(re.sign * re.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), re.exponent),
266 im.sign * im.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), im.exponent));
268 default: // Ordinary number
275 setflag(status_flags::evaluated | status_flags::expanded);
278 void numeric::archive(archive_node &n) const
280 inherited::archive(n);
282 // Write number as string
283 std::ostringstream s;
284 if (this->is_crational())
285 s << cln::the<cln::cl_N>(value);
287 // Non-rational numbers are written in an integer-decoded format
288 // to preserve the precision
289 if (this->is_real()) {
290 cln::cl_idecoded_float re = cln::integer_decode_float(cln::the<cln::cl_F>(value));
292 s << re.sign << " " << re.mantissa << " " << re.exponent;
294 cln::cl_idecoded_float re = cln::integer_decode_float(cln::the<cln::cl_F>(cln::realpart(cln::the<cln::cl_N>(value))));
295 cln::cl_idecoded_float im = cln::integer_decode_float(cln::the<cln::cl_F>(cln::imagpart(cln::the<cln::cl_N>(value))));
297 s << re.sign << " " << re.mantissa << " " << re.exponent << " ";
298 s << im.sign << " " << im.mantissa << " " << im.exponent;
301 n.add_string("number", s.str());
304 DEFAULT_UNARCHIVE(numeric)
307 // functions overriding virtual functions from base classes
310 /** Helper function to print a real number in a nicer way than is CLN's
311 * default. Instead of printing 42.0L0 this just prints 42.0 to ostream os
312 * and instead of 3.99168L7 it prints 3.99168E7. This is fine in GiNaC as
313 * long as it only uses cl_LF and no other floating point types that we might
314 * want to visibly distinguish from cl_LF.
316 * @see numeric::print() */
317 static void print_real_number(const print_context & c, const cln::cl_R &x)
319 cln::cl_print_flags ourflags;
320 if (cln::instanceof(x, cln::cl_RA_ring)) {
321 // case 1: integer or rational
322 if (cln::instanceof(x, cln::cl_I_ring) ||
323 !is_a<print_latex>(c)) {
324 cln::print_real(c.s, ourflags, x);
325 } else { // rational output in LaTeX context
329 cln::print_real(c.s, ourflags, cln::abs(cln::numerator(cln::the<cln::cl_RA>(x))));
331 cln::print_real(c.s, ourflags, cln::denominator(cln::the<cln::cl_RA>(x)));
336 // make CLN believe this number has default_float_format, so it prints
337 // 'E' as exponent marker instead of 'L':
338 ourflags.default_float_format = cln::float_format(cln::the<cln::cl_F>(x));
339 cln::print_real(c.s, ourflags, x);
343 /** This method adds to the output so it blends more consistently together
344 * with the other routines and produces something compatible to ginsh input.
346 * @see print_real_number() */
347 void numeric::print(const print_context & c, unsigned level) const
349 if (is_a<print_tree>(c)) {
351 c.s << std::string(level, ' ') << cln::the<cln::cl_N>(value)
352 << " (" << class_name() << ")"
353 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
356 } else if (is_a<print_csrc>(c)) {
358 std::ios::fmtflags oldflags = c.s.flags();
359 c.s.setf(std::ios::scientific);
360 int oldprec = c.s.precision();
361 if (is_a<print_csrc_double>(c))
365 if (is_a<print_csrc_cl_N>(c) && this->is_integer()) {
366 c.s << "cln::cl_I(\"";
367 const cln::cl_R r = cln::realpart(cln::the<cln::cl_N>(value));
368 print_real_number(c,r);
370 } else if (this->is_rational() && !this->is_integer()) {
371 if (compare(_num0) > 0) {
373 if (is_a<print_csrc_cl_N>(c))
374 c.s << "cln::cl_F(\"" << numer().evalf() << "\")";
376 c.s << numer().to_double();
379 if (is_a<print_csrc_cl_N>(c))
380 c.s << "cln::cl_F(\"" << -numer().evalf() << "\")";
382 c.s << -numer().to_double();
385 if (is_a<print_csrc_cl_N>(c))
386 c.s << "cln::cl_F(\"" << denom().evalf() << "\")";
388 c.s << denom().to_double();
391 if (is_a<print_csrc_cl_N>(c))
392 c.s << "cln::cl_F(\"" << evalf() << "_" << Digits << "\")";
397 c.s.precision(oldprec);
400 const std::string par_open = is_a<print_latex>(c) ? "{(" : "(";
401 const std::string par_close = is_a<print_latex>(c) ? ")}" : ")";
402 const std::string imag_sym = is_a<print_latex>(c) ? "i" : "I";
403 const std::string mul_sym = is_a<print_latex>(c) ? " " : "*";
404 const cln::cl_R r = cln::realpart(cln::the<cln::cl_N>(value));
405 const cln::cl_R i = cln::imagpart(cln::the<cln::cl_N>(value));
406 if (is_a<print_python_repr>(c))
407 c.s << class_name() << "('";
409 // case 1, real: x or -x
410 if ((precedence() <= level) && (!this->is_nonneg_integer())) {
412 print_real_number(c, r);
415 print_real_number(c, r);
419 // case 2, imaginary: y*I or -y*I
423 if (precedence()<=level)
426 c.s << "-" << imag_sym;
428 print_real_number(c, i);
429 c.s << mul_sym+imag_sym;
431 if (precedence()<=level)
435 // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I
436 if (precedence() <= level)
438 print_real_number(c, r);
443 print_real_number(c, i);
444 c.s << mul_sym+imag_sym;
451 print_real_number(c, i);
452 c.s << mul_sym+imag_sym;
455 if (precedence() <= level)
459 if (is_a<print_python_repr>(c))
464 bool numeric::info(unsigned inf) const
467 case info_flags::numeric:
468 case info_flags::polynomial:
469 case info_flags::rational_function:
471 case info_flags::real:
473 case info_flags::rational:
474 case info_flags::rational_polynomial:
475 return is_rational();
476 case info_flags::crational:
477 case info_flags::crational_polynomial:
478 return is_crational();
479 case info_flags::integer:
480 case info_flags::integer_polynomial:
482 case info_flags::cinteger:
483 case info_flags::cinteger_polynomial:
484 return is_cinteger();
485 case info_flags::positive:
486 return is_positive();
487 case info_flags::negative:
488 return is_negative();
489 case info_flags::nonnegative:
490 return !is_negative();
491 case info_flags::posint:
492 return is_pos_integer();
493 case info_flags::negint:
494 return is_integer() && is_negative();
495 case info_flags::nonnegint:
496 return is_nonneg_integer();
497 case info_flags::even:
499 case info_flags::odd:
501 case info_flags::prime:
503 case info_flags::algebraic:
509 int numeric::degree(const ex & s) const
514 int numeric::ldegree(const ex & s) const
519 ex numeric::coeff(const ex & s, int n) const
521 return n==0 ? *this : _ex0;
524 /** Disassemble real part and imaginary part to scan for the occurrence of a
525 * single number. Also handles the imaginary unit. It ignores the sign on
526 * both this and the argument, which may lead to what might appear as funny
527 * results: (2+I).has(-2) -> true. But this is consistent, since we also
528 * would like to have (-2+I).has(2) -> true and we want to think about the
529 * sign as a multiplicative factor. */
530 bool numeric::has(const ex &other) const
532 if (!is_exactly_a<numeric>(other))
534 const numeric &o = ex_to<numeric>(other);
535 if (this->is_equal(o) || this->is_equal(-o))
537 if (o.imag().is_zero()) // e.g. scan for 3 in -3*I
538 return (this->real().is_equal(o) || this->imag().is_equal(o) ||
539 this->real().is_equal(-o) || this->imag().is_equal(-o));
541 if (o.is_equal(I)) // e.g scan for I in 42*I
542 return !this->is_real();
543 if (o.real().is_zero()) // e.g. scan for 2*I in 2*I+1
544 return (this->real().has(o*I) || this->imag().has(o*I) ||
545 this->real().has(-o*I) || this->imag().has(-o*I));
551 /** Evaluation of numbers doesn't do anything at all. */
552 ex numeric::eval(int level) const
554 // Warning: if this is ever gonna do something, the ex ctors from all kinds
555 // of numbers should be checking for status_flags::evaluated.
560 /** Cast numeric into a floating-point object. For example exact numeric(1) is
561 * returned as a 1.0000000000000000000000 and so on according to how Digits is
562 * currently set. In case the object already was a floating point number the
563 * precision is trimmed to match the currently set default.
565 * @param level ignored, only needed for overriding basic::evalf.
566 * @return an ex-handle to a numeric. */
567 ex numeric::evalf(int level) const
569 // level can safely be discarded for numeric objects.
570 return numeric(cln::cl_float(1.0, cln::default_float_format) *
571 (cln::the<cln::cl_N>(value)));
576 int numeric::compare_same_type(const basic &other) const
578 GINAC_ASSERT(is_exactly_a<numeric>(other));
579 const numeric &o = static_cast<const numeric &>(other);
581 return this->compare(o);
585 bool numeric::is_equal_same_type(const basic &other) const
587 GINAC_ASSERT(is_exactly_a<numeric>(other));
588 const numeric &o = static_cast<const numeric &>(other);
590 return this->is_equal(o);
594 unsigned numeric::calchash(void) const
596 // Base computation of hashvalue on CLN's hashcode. Note: That depends
597 // only on the number's value, not its type or precision (i.e. a true
598 // equivalence relation on numbers). As a consequence, 3 and 3.0 share
599 // the same hashvalue. That shouldn't really matter, though.
600 setflag(status_flags::hash_calculated);
601 hashvalue = golden_ratio_hash(cln::equal_hashcode(cln::the<cln::cl_N>(value)));
607 // new virtual functions which can be overridden by derived classes
613 // non-virtual functions in this class
618 /** Numerical addition method. Adds argument to *this and returns result as
619 * a numeric object. */
620 const numeric numeric::add(const numeric &other) const
622 // Efficiency shortcut: trap the neutral element by pointer.
625 else if (&other==_num0_p)
628 return numeric(cln::the<cln::cl_N>(value)+cln::the<cln::cl_N>(other.value));
632 /** Numerical subtraction method. Subtracts argument from *this and returns
633 * result as a numeric object. */
634 const numeric numeric::sub(const numeric &other) const
636 return numeric(cln::the<cln::cl_N>(value)-cln::the<cln::cl_N>(other.value));
640 /** Numerical multiplication method. Multiplies *this and argument and returns
641 * result as a numeric object. */
642 const numeric numeric::mul(const numeric &other) const
644 // Efficiency shortcut: trap the neutral element by pointer.
647 else if (&other==_num1_p)
650 return numeric(cln::the<cln::cl_N>(value)*cln::the<cln::cl_N>(other.value));
654 /** Numerical division method. Divides *this by argument and returns result as
657 * @exception overflow_error (division by zero) */
658 const numeric numeric::div(const numeric &other) const
660 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
661 throw std::overflow_error("numeric::div(): division by zero");
662 return numeric(cln::the<cln::cl_N>(value)/cln::the<cln::cl_N>(other.value));
666 /** Numerical exponentiation. Raises *this to the power given as argument and
667 * returns result as a numeric object. */
668 const numeric numeric::power(const numeric &other) const
670 // Efficiency shortcut: trap the neutral exponent by pointer.
674 if (cln::zerop(cln::the<cln::cl_N>(value))) {
675 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
676 throw std::domain_error("numeric::eval(): pow(0,0) is undefined");
677 else if (cln::zerop(cln::realpart(cln::the<cln::cl_N>(other.value))))
678 throw std::domain_error("numeric::eval(): pow(0,I) is undefined");
679 else if (cln::minusp(cln::realpart(cln::the<cln::cl_N>(other.value))))
680 throw std::overflow_error("numeric::eval(): division by zero");
684 return numeric(cln::expt(cln::the<cln::cl_N>(value),cln::the<cln::cl_N>(other.value)));
689 /** Numerical addition method. Adds argument to *this and returns result as
690 * a numeric object on the heap. Use internally only for direct wrapping into
691 * an ex object, where the result would end up on the heap anyways. */
692 const numeric &numeric::add_dyn(const numeric &other) const
694 // Efficiency shortcut: trap the neutral element by pointer.
697 else if (&other==_num0_p)
700 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)+cln::the<cln::cl_N>(other.value)))->
701 setflag(status_flags::dynallocated));
705 /** Numerical subtraction method. Subtracts argument from *this and returns
706 * result as a numeric object on the heap. Use internally only for direct
707 * wrapping into an ex object, where the result would end up on the heap
709 const numeric &numeric::sub_dyn(const numeric &other) const
711 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)-cln::the<cln::cl_N>(other.value)))->
712 setflag(status_flags::dynallocated));
716 /** Numerical multiplication method. Multiplies *this and argument and returns
717 * result as a numeric object on the heap. Use internally only for direct
718 * wrapping into an ex object, where the result would end up on the heap
720 const numeric &numeric::mul_dyn(const numeric &other) const
722 // Efficiency shortcut: trap the neutral element by pointer.
725 else if (&other==_num1_p)
728 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)*cln::the<cln::cl_N>(other.value)))->
729 setflag(status_flags::dynallocated));
733 /** Numerical division method. Divides *this by argument and returns result as
734 * a numeric object on the heap. Use internally only for direct wrapping
735 * into an ex object, where the result would end up on the heap
738 * @exception overflow_error (division by zero) */
739 const numeric &numeric::div_dyn(const numeric &other) const
741 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
742 throw std::overflow_error("division by zero");
743 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)/cln::the<cln::cl_N>(other.value)))->
744 setflag(status_flags::dynallocated));
748 /** Numerical exponentiation. Raises *this to the power given as argument and
749 * returns result as a numeric object on the heap. Use internally only for
750 * direct wrapping into an ex object, where the result would end up on the
752 const numeric &numeric::power_dyn(const numeric &other) const
754 // Efficiency shortcut: trap the neutral exponent by pointer.
758 if (cln::zerop(cln::the<cln::cl_N>(value))) {
759 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
760 throw std::domain_error("numeric::eval(): pow(0,0) is undefined");
761 else if (cln::zerop(cln::realpart(cln::the<cln::cl_N>(other.value))))
762 throw std::domain_error("numeric::eval(): pow(0,I) is undefined");
763 else if (cln::minusp(cln::realpart(cln::the<cln::cl_N>(other.value))))
764 throw std::overflow_error("numeric::eval(): division by zero");
768 return static_cast<const numeric &>((new numeric(cln::expt(cln::the<cln::cl_N>(value),cln::the<cln::cl_N>(other.value))))->
769 setflag(status_flags::dynallocated));
773 const numeric &numeric::operator=(int i)
775 return operator=(numeric(i));
779 const numeric &numeric::operator=(unsigned int i)
781 return operator=(numeric(i));
785 const numeric &numeric::operator=(long i)
787 return operator=(numeric(i));
791 const numeric &numeric::operator=(unsigned long i)
793 return operator=(numeric(i));
797 const numeric &numeric::operator=(double d)
799 return operator=(numeric(d));
803 const numeric &numeric::operator=(const char * s)
805 return operator=(numeric(s));
809 /** Inverse of a number. */
810 const numeric numeric::inverse(void) const
812 if (cln::zerop(cln::the<cln::cl_N>(value)))
813 throw std::overflow_error("numeric::inverse(): division by zero");
814 return numeric(cln::recip(cln::the<cln::cl_N>(value)));
818 /** Return the complex half-plane (left or right) in which the number lies.
819 * csgn(x)==0 for x==0, csgn(x)==1 for Re(x)>0 or Re(x)=0 and Im(x)>0,
820 * csgn(x)==-1 for Re(x)<0 or Re(x)=0 and Im(x)<0.
822 * @see numeric::compare(const numeric &other) */
823 int numeric::csgn(void) const
825 if (cln::zerop(cln::the<cln::cl_N>(value)))
827 cln::cl_R r = cln::realpart(cln::the<cln::cl_N>(value));
828 if (!cln::zerop(r)) {
834 if (cln::plusp(cln::imagpart(cln::the<cln::cl_N>(value))))
842 /** This method establishes a canonical order on all numbers. For complex
843 * numbers this is not possible in a mathematically consistent way but we need
844 * to establish some order and it ought to be fast. So we simply define it
845 * to be compatible with our method csgn.
847 * @return csgn(*this-other)
848 * @see numeric::csgn(void) */
849 int numeric::compare(const numeric &other) const
851 // Comparing two real numbers?
852 if (cln::instanceof(value, cln::cl_R_ring) &&
853 cln::instanceof(other.value, cln::cl_R_ring))
854 // Yes, so just cln::compare them
855 return cln::compare(cln::the<cln::cl_R>(value), cln::the<cln::cl_R>(other.value));
857 // No, first cln::compare real parts...
858 cl_signean real_cmp = cln::compare(cln::realpart(cln::the<cln::cl_N>(value)), cln::realpart(cln::the<cln::cl_N>(other.value)));
861 // ...and then the imaginary parts.
862 return cln::compare(cln::imagpart(cln::the<cln::cl_N>(value)), cln::imagpart(cln::the<cln::cl_N>(other.value)));
867 bool numeric::is_equal(const numeric &other) const
869 return cln::equal(cln::the<cln::cl_N>(value),cln::the<cln::cl_N>(other.value));
873 /** True if object is zero. */
874 bool numeric::is_zero(void) const
876 return cln::zerop(cln::the<cln::cl_N>(value));
880 /** True if object is not complex and greater than zero. */
881 bool numeric::is_positive(void) const
883 if (cln::instanceof(value, cln::cl_R_ring)) // real?
884 return cln::plusp(cln::the<cln::cl_R>(value));
889 /** True if object is not complex and less than zero. */
890 bool numeric::is_negative(void) const
892 if (cln::instanceof(value, cln::cl_R_ring)) // real?
893 return cln::minusp(cln::the<cln::cl_R>(value));
898 /** True if object is a non-complex integer. */
899 bool numeric::is_integer(void) const
901 return cln::instanceof(value, cln::cl_I_ring);
905 /** True if object is an exact integer greater than zero. */
906 bool numeric::is_pos_integer(void) const
908 return (cln::instanceof(value, cln::cl_I_ring) && cln::plusp(cln::the<cln::cl_I>(value)));
912 /** True if object is an exact integer greater or equal zero. */
913 bool numeric::is_nonneg_integer(void) const
915 return (cln::instanceof(value, cln::cl_I_ring) && !cln::minusp(cln::the<cln::cl_I>(value)));
919 /** True if object is an exact even integer. */
920 bool numeric::is_even(void) const
922 return (cln::instanceof(value, cln::cl_I_ring) && cln::evenp(cln::the<cln::cl_I>(value)));
926 /** True if object is an exact odd integer. */
927 bool numeric::is_odd(void) const
929 return (cln::instanceof(value, cln::cl_I_ring) && cln::oddp(cln::the<cln::cl_I>(value)));
933 /** Probabilistic primality test.
935 * @return true if object is exact integer and prime. */
936 bool numeric::is_prime(void) const
938 return (cln::instanceof(value, cln::cl_I_ring) // integer?
939 && cln::plusp(cln::the<cln::cl_I>(value)) // positive?
940 && cln::isprobprime(cln::the<cln::cl_I>(value)));
944 /** True if object is an exact rational number, may even be complex
945 * (denominator may be unity). */
946 bool numeric::is_rational(void) const
948 return cln::instanceof(value, cln::cl_RA_ring);
952 /** True if object is a real integer, rational or float (but not complex). */
953 bool numeric::is_real(void) const
955 return cln::instanceof(value, cln::cl_R_ring);
959 bool numeric::operator==(const numeric &other) const
961 return cln::equal(cln::the<cln::cl_N>(value), cln::the<cln::cl_N>(other.value));
965 bool numeric::operator!=(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 element of the domain of integers extended by I, i.e. is
972 * of the form a+b*I, where a and b are integers. */
973 bool numeric::is_cinteger(void) const
975 if (cln::instanceof(value, cln::cl_I_ring))
977 else if (!this->is_real()) { // complex case, handle n+m*I
978 if (cln::instanceof(cln::realpart(cln::the<cln::cl_N>(value)), cln::cl_I_ring) &&
979 cln::instanceof(cln::imagpart(cln::the<cln::cl_N>(value)), cln::cl_I_ring))
986 /** True if object is an exact rational number, may even be complex
987 * (denominator may be unity). */
988 bool numeric::is_crational(void) const
990 if (cln::instanceof(value, cln::cl_RA_ring))
992 else if (!this->is_real()) { // complex case, handle Q(i):
993 if (cln::instanceof(cln::realpart(cln::the<cln::cl_N>(value)), cln::cl_RA_ring) &&
994 cln::instanceof(cln::imagpart(cln::the<cln::cl_N>(value)), cln::cl_RA_ring))
1001 /** Numerical comparison: less.
1003 * @exception invalid_argument (complex inequality) */
1004 bool numeric::operator<(const numeric &other) const
1006 if (this->is_real() && other.is_real())
1007 return (cln::the<cln::cl_R>(value) < cln::the<cln::cl_R>(other.value));
1008 throw std::invalid_argument("numeric::operator<(): complex inequality");
1012 /** Numerical comparison: less or equal.
1014 * @exception invalid_argument (complex inequality) */
1015 bool numeric::operator<=(const numeric &other) const
1017 if (this->is_real() && other.is_real())
1018 return (cln::the<cln::cl_R>(value) <= cln::the<cln::cl_R>(other.value));
1019 throw std::invalid_argument("numeric::operator<=(): complex inequality");
1023 /** Numerical comparison: greater.
1025 * @exception invalid_argument (complex inequality) */
1026 bool numeric::operator>(const numeric &other) const
1028 if (this->is_real() && other.is_real())
1029 return (cln::the<cln::cl_R>(value) > cln::the<cln::cl_R>(other.value));
1030 throw std::invalid_argument("numeric::operator>(): complex inequality");
1034 /** Numerical comparison: greater or equal.
1036 * @exception invalid_argument (complex inequality) */
1037 bool numeric::operator>=(const numeric &other) const
1039 if (this->is_real() && other.is_real())
1040 return (cln::the<cln::cl_R>(value) >= cln::the<cln::cl_R>(other.value));
1041 throw std::invalid_argument("numeric::operator>=(): complex inequality");
1045 /** Converts numeric types to machine's int. You should check with
1046 * is_integer() if the number is really an integer before calling this method.
1047 * You may also consider checking the range first. */
1048 int numeric::to_int(void) const
1050 GINAC_ASSERT(this->is_integer());
1051 return cln::cl_I_to_int(cln::the<cln::cl_I>(value));
1055 /** Converts numeric types to machine's long. You should check with
1056 * is_integer() if the number is really an integer before calling this method.
1057 * You may also consider checking the range first. */
1058 long numeric::to_long(void) const
1060 GINAC_ASSERT(this->is_integer());
1061 return cln::cl_I_to_long(cln::the<cln::cl_I>(value));
1065 /** Converts numeric types to machine's double. You should check with is_real()
1066 * if the number is really not complex before calling this method. */
1067 double numeric::to_double(void) const
1069 GINAC_ASSERT(this->is_real());
1070 return cln::double_approx(cln::realpart(cln::the<cln::cl_N>(value)));
1074 /** Returns a new CLN object of type cl_N, representing the value of *this.
1075 * This method may be used when mixing GiNaC and CLN in one project.
1077 cln::cl_N numeric::to_cl_N(void) const
1079 return cln::cl_N(cln::the<cln::cl_N>(value));
1083 /** Real part of a number. */
1084 const numeric numeric::real(void) const
1086 return numeric(cln::realpart(cln::the<cln::cl_N>(value)));
1090 /** Imaginary part of a number. */
1091 const numeric numeric::imag(void) const
1093 return numeric(cln::imagpart(cln::the<cln::cl_N>(value)));
1097 /** Numerator. Computes the numerator of rational numbers, rationalized
1098 * numerator of complex if real and imaginary part are both rational numbers
1099 * (i.e numer(4/3+5/6*I) == 8+5*I), the number carrying the sign in all other
1101 const numeric numeric::numer(void) const
1103 if (cln::instanceof(value, cln::cl_I_ring))
1104 return numeric(*this); // integer case
1106 else if (cln::instanceof(value, cln::cl_RA_ring))
1107 return numeric(cln::numerator(cln::the<cln::cl_RA>(value)));
1109 else if (!this->is_real()) { // complex case, handle Q(i):
1110 const cln::cl_RA r = cln::the<cln::cl_RA>(cln::realpart(cln::the<cln::cl_N>(value)));
1111 const cln::cl_RA i = cln::the<cln::cl_RA>(cln::imagpart(cln::the<cln::cl_N>(value)));
1112 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_I_ring))
1113 return numeric(*this);
1114 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_RA_ring))
1115 return numeric(cln::complex(r*cln::denominator(i), cln::numerator(i)));
1116 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_I_ring))
1117 return numeric(cln::complex(cln::numerator(r), i*cln::denominator(r)));
1118 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_RA_ring)) {
1119 const cln::cl_I s = cln::lcm(cln::denominator(r), cln::denominator(i));
1120 return numeric(cln::complex(cln::numerator(r)*(cln::exquo(s,cln::denominator(r))),
1121 cln::numerator(i)*(cln::exquo(s,cln::denominator(i)))));
1124 // at least one float encountered
1125 return numeric(*this);
1129 /** Denominator. Computes the denominator of rational numbers, common integer
1130 * denominator of complex if real and imaginary part are both rational numbers
1131 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
1132 const numeric numeric::denom(void) const
1134 if (cln::instanceof(value, cln::cl_I_ring))
1135 return _num1; // integer case
1137 if (cln::instanceof(value, cln::cl_RA_ring))
1138 return numeric(cln::denominator(cln::the<cln::cl_RA>(value)));
1140 if (!this->is_real()) { // complex case, handle Q(i):
1141 const cln::cl_RA r = cln::the<cln::cl_RA>(cln::realpart(cln::the<cln::cl_N>(value)));
1142 const cln::cl_RA i = cln::the<cln::cl_RA>(cln::imagpart(cln::the<cln::cl_N>(value)));
1143 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_I_ring))
1145 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_RA_ring))
1146 return numeric(cln::denominator(i));
1147 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_I_ring))
1148 return numeric(cln::denominator(r));
1149 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_RA_ring))
1150 return numeric(cln::lcm(cln::denominator(r), cln::denominator(i)));
1152 // at least one float encountered
1157 /** Size in binary notation. For integers, this is the smallest n >= 0 such
1158 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
1159 * 2^(n-1) <= x < 2^n.
1161 * @return number of bits (excluding sign) needed to represent that number
1162 * in two's complement if it is an integer, 0 otherwise. */
1163 int numeric::int_length(void) const
1165 if (cln::instanceof(value, cln::cl_I_ring))
1166 return cln::integer_length(cln::the<cln::cl_I>(value));
1175 /** Imaginary unit. This is not a constant but a numeric since we are
1176 * natively handing complex numbers anyways, so in each expression containing
1177 * an I it is automatically eval'ed away anyhow. */
1178 const numeric I = numeric(cln::complex(cln::cl_I(0),cln::cl_I(1)));
1181 /** Exponential function.
1183 * @return arbitrary precision numerical exp(x). */
1184 const numeric exp(const numeric &x)
1186 return cln::exp(x.to_cl_N());
1190 /** Natural logarithm.
1192 * @param z complex number
1193 * @return arbitrary precision numerical log(x).
1194 * @exception pole_error("log(): logarithmic pole",0) */
1195 const numeric log(const numeric &z)
1198 throw pole_error("log(): logarithmic pole",0);
1199 return cln::log(z.to_cl_N());
1203 /** Numeric sine (trigonometric function).
1205 * @return arbitrary precision numerical sin(x). */
1206 const numeric sin(const numeric &x)
1208 return cln::sin(x.to_cl_N());
1212 /** Numeric cosine (trigonometric function).
1214 * @return arbitrary precision numerical cos(x). */
1215 const numeric cos(const numeric &x)
1217 return cln::cos(x.to_cl_N());
1221 /** Numeric tangent (trigonometric function).
1223 * @return arbitrary precision numerical tan(x). */
1224 const numeric tan(const numeric &x)
1226 return cln::tan(x.to_cl_N());
1230 /** Numeric inverse sine (trigonometric function).
1232 * @return arbitrary precision numerical asin(x). */
1233 const numeric asin(const numeric &x)
1235 return cln::asin(x.to_cl_N());
1239 /** Numeric inverse cosine (trigonometric function).
1241 * @return arbitrary precision numerical acos(x). */
1242 const numeric acos(const numeric &x)
1244 return cln::acos(x.to_cl_N());
1250 * @param z complex number
1252 * @exception pole_error("atan(): logarithmic pole",0) */
1253 const numeric atan(const numeric &x)
1256 x.real().is_zero() &&
1257 abs(x.imag()).is_equal(_num1))
1258 throw pole_error("atan(): logarithmic pole",0);
1259 return cln::atan(x.to_cl_N());
1265 * @param x real number
1266 * @param y real number
1267 * @return atan(y/x) */
1268 const numeric atan(const numeric &y, const numeric &x)
1270 if (x.is_real() && y.is_real())
1271 return cln::atan(cln::the<cln::cl_R>(x.to_cl_N()),
1272 cln::the<cln::cl_R>(y.to_cl_N()));
1274 throw std::invalid_argument("atan(): complex argument");
1278 /** Numeric hyperbolic sine (trigonometric function).
1280 * @return arbitrary precision numerical sinh(x). */
1281 const numeric sinh(const numeric &x)
1283 return cln::sinh(x.to_cl_N());
1287 /** Numeric hyperbolic cosine (trigonometric function).
1289 * @return arbitrary precision numerical cosh(x). */
1290 const numeric cosh(const numeric &x)
1292 return cln::cosh(x.to_cl_N());
1296 /** Numeric hyperbolic tangent (trigonometric function).
1298 * @return arbitrary precision numerical tanh(x). */
1299 const numeric tanh(const numeric &x)
1301 return cln::tanh(x.to_cl_N());
1305 /** Numeric inverse hyperbolic sine (trigonometric function).
1307 * @return arbitrary precision numerical asinh(x). */
1308 const numeric asinh(const numeric &x)
1310 return cln::asinh(x.to_cl_N());
1314 /** Numeric inverse hyperbolic cosine (trigonometric function).
1316 * @return arbitrary precision numerical acosh(x). */
1317 const numeric acosh(const numeric &x)
1319 return cln::acosh(x.to_cl_N());
1323 /** Numeric inverse hyperbolic tangent (trigonometric function).
1325 * @return arbitrary precision numerical atanh(x). */
1326 const numeric atanh(const numeric &x)
1328 return cln::atanh(x.to_cl_N());
1332 /*static cln::cl_N Li2_series(const ::cl_N &x,
1333 const ::float_format_t &prec)
1335 // Note: argument must be in the unit circle
1336 // This is very inefficient unless we have fast floating point Bernoulli
1337 // numbers implemented!
1338 cln::cl_N c1 = -cln::log(1-x);
1340 // hard-wire the first two Bernoulli numbers
1341 cln::cl_N acc = c1 - cln::square(c1)/4;
1343 cln::cl_F pisq = cln::square(cln::cl_pi(prec)); // pi^2
1344 cln::cl_F piac = cln::cl_float(1, prec); // accumulator: pi^(2*i)
1346 c1 = cln::square(c1);
1350 aug = c2 * (*(bernoulli(numeric(2*i)).clnptr())) / cln::factorial(2*i+1);
1351 // 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));
1354 } while (acc != acc+aug);
1358 /** Numeric evaluation of Dilogarithm within circle of convergence (unit
1359 * circle) using a power series. */
1360 static cln::cl_N Li2_series(const cln::cl_N &x,
1361 const cln::float_format_t &prec)
1363 // Note: argument must be in the unit circle
1365 cln::cl_N num = cln::complex(cln::cl_float(1, prec), 0);
1370 den = den + i; // 1, 4, 9, 16, ...
1374 } while (acc != acc+aug);
1378 /** Folds Li2's argument inside a small rectangle to enhance convergence. */
1379 static cln::cl_N Li2_projection(const cln::cl_N &x,
1380 const cln::float_format_t &prec)
1382 const cln::cl_R re = cln::realpart(x);
1383 const cln::cl_R im = cln::imagpart(x);
1384 if (re > cln::cl_F(".5"))
1385 // zeta(2) - Li2(1-x) - log(x)*log(1-x)
1387 - Li2_series(1-x, prec)
1388 - cln::log(x)*cln::log(1-x));
1389 if ((re <= 0 && cln::abs(im) > cln::cl_F(".75")) || (re < cln::cl_F("-.5")))
1390 // -log(1-x)^2 / 2 - Li2(x/(x-1))
1391 return(- cln::square(cln::log(1-x))/2
1392 - Li2_series(x/(x-1), prec));
1393 if (re > 0 && cln::abs(im) > cln::cl_LF(".75"))
1394 // Li2(x^2)/2 - Li2(-x)
1395 return(Li2_projection(cln::square(x), prec)/2
1396 - Li2_projection(-x, prec));
1397 return Li2_series(x, prec);
1400 /** Numeric evaluation of Dilogarithm. The domain is the entire complex plane,
1401 * the branch cut lies along the positive real axis, starting at 1 and
1402 * continuous with quadrant IV.
1404 * @return arbitrary precision numerical Li2(x). */
1405 const numeric Li2(const numeric &x)
1410 // what is the desired float format?
1411 // first guess: default format
1412 cln::float_format_t prec = cln::default_float_format;
1413 const cln::cl_N value = x.to_cl_N();
1414 // second guess: the argument's format
1415 if (!x.real().is_rational())
1416 prec = cln::float_format(cln::the<cln::cl_F>(cln::realpart(value)));
1417 else if (!x.imag().is_rational())
1418 prec = cln::float_format(cln::the<cln::cl_F>(cln::imagpart(value)));
1420 if (cln::the<cln::cl_N>(value)==1) // may cause trouble with log(1-x)
1421 return cln::zeta(2, prec);
1423 if (cln::abs(value) > 1)
1424 // -log(-x)^2 / 2 - zeta(2) - Li2(1/x)
1425 return(- cln::square(cln::log(-value))/2
1426 - cln::zeta(2, prec)
1427 - Li2_projection(cln::recip(value), prec));
1429 return Li2_projection(x.to_cl_N(), prec);
1433 /** Numeric evaluation of Riemann's Zeta function. Currently works only for
1434 * integer arguments. */
1435 const numeric zeta(const numeric &x)
1437 // A dirty hack to allow for things like zeta(3.0), since CLN currently
1438 // only knows about integer arguments and zeta(3).evalf() automatically
1439 // cascades down to zeta(3.0).evalf(). The trick is to rely on 3.0-3
1440 // being an exact zero for CLN, which can be tested and then we can just
1441 // pass the number casted to an int:
1443 const int aux = (int)(cln::double_approx(cln::the<cln::cl_R>(x.to_cl_N())));
1444 if (cln::zerop(x.to_cl_N()-aux))
1445 return cln::zeta(aux);
1451 /** The Gamma function.
1452 * This is only a stub! */
1453 const numeric lgamma(const numeric &x)
1457 const numeric tgamma(const numeric &x)
1463 /** The psi function (aka polygamma function).
1464 * This is only a stub! */
1465 const numeric psi(const numeric &x)
1471 /** The psi functions (aka polygamma functions).
1472 * This is only a stub! */
1473 const numeric psi(const numeric &n, const numeric &x)
1479 /** Factorial combinatorial function.
1481 * @param n integer argument >= 0
1482 * @exception range_error (argument must be integer >= 0) */
1483 const numeric factorial(const numeric &n)
1485 if (!n.is_nonneg_integer())
1486 throw std::range_error("numeric::factorial(): argument must be integer >= 0");
1487 return numeric(cln::factorial(n.to_int()));
1491 /** The double factorial combinatorial function. (Scarcely used, but still
1492 * useful in cases, like for exact results of tgamma(n+1/2) for instance.)
1494 * @param n integer argument >= -1
1495 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == (-1)!! == 1
1496 * @exception range_error (argument must be integer >= -1) */
1497 const numeric doublefactorial(const numeric &n)
1499 if (n.is_equal(_num_1))
1502 if (!n.is_nonneg_integer())
1503 throw std::range_error("numeric::doublefactorial(): argument must be integer >= -1");
1505 return numeric(cln::doublefactorial(n.to_int()));
1509 /** The Binomial coefficients. It computes the binomial coefficients. For
1510 * integer n and k and positive n this is the number of ways of choosing k
1511 * objects from n distinct objects. If n is negative, the formula
1512 * binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */
1513 const numeric binomial(const numeric &n, const numeric &k)
1515 if (n.is_integer() && k.is_integer()) {
1516 if (n.is_nonneg_integer()) {
1517 if (k.compare(n)!=1 && k.compare(_num0)!=-1)
1518 return numeric(cln::binomial(n.to_int(),k.to_int()));
1522 return _num_1.power(k)*binomial(k-n-_num1,k);
1526 // should really be gamma(n+1)/gamma(r+1)/gamma(n-r+1) or a suitable limit
1527 throw std::range_error("numeric::binomial(): don´t know how to evaluate that.");
1531 /** Bernoulli number. The nth Bernoulli number is the coefficient of x^n/n!
1532 * in the expansion of the function x/(e^x-1).
1534 * @return the nth Bernoulli number (a rational number).
1535 * @exception range_error (argument must be integer >= 0) */
1536 const numeric bernoulli(const numeric &nn)
1538 if (!nn.is_integer() || nn.is_negative())
1539 throw std::range_error("numeric::bernoulli(): argument must be integer >= 0");
1543 // The Bernoulli numbers are rational numbers that may be computed using
1546 // B_n = - 1/(n+1) * sum_{k=0}^{n-1}(binomial(n+1,k)*B_k)
1548 // with B(0) = 1. Since the n'th Bernoulli number depends on all the
1549 // previous ones, the computation is necessarily very expensive. There are
1550 // several other ways of computing them, a particularly good one being
1554 // for (unsigned i=0; i<n; i++) {
1555 // c = exquo(c*(i-n),(i+2));
1556 // Bern = Bern + c*s/(i+2);
1557 // s = s + expt_pos(cl_I(i+2),n);
1561 // But if somebody works with the n'th Bernoulli number she is likely to
1562 // also need all previous Bernoulli numbers. So we need a complete remember
1563 // table and above divide and conquer algorithm is not suited to build one
1564 // up. The formula below accomplishes this. It is a modification of the
1565 // defining formula above but the computation of the binomial coefficients
1566 // is carried along in an inline fashion. It also honors the fact that
1567 // B_n is zero when n is odd and greater than 1.
1569 // (There is an interesting relation with the tangent polynomials described
1570 // in `Concrete Mathematics', which leads to a program a little faster as
1571 // our implementation below, but it requires storing one such polynomial in
1572 // addition to the remember table. This doubles the memory footprint so
1573 // we don't use it.)
1575 const unsigned n = nn.to_int();
1577 // the special cases not covered by the algorithm below
1579 return (n==1) ? _num_1_2 : _num0;
1583 // store nonvanishing Bernoulli numbers here
1584 static std::vector< cln::cl_RA > results;
1585 static unsigned next_r = 0;
1587 // algorithm not applicable to B(2), so just store it
1589 results.push_back(cln::recip(cln::cl_RA(6)));
1593 return results[n/2-1];
1595 results.reserve(n/2);
1596 for (unsigned p=next_r; p<=n; p+=2) {
1597 cln::cl_I c = 1; // seed for binonmial coefficients
1598 cln::cl_RA b = cln::cl_RA(1-p)/2;
1599 const unsigned p3 = p+3;
1600 const unsigned pm = p-2;
1602 // test if intermediate unsigned int can be represented by immediate
1603 // objects by CLN (i.e. < 2^29 for 32 Bit machines, see <cln/object.h>)
1604 if (p < (1UL<<cl_value_len/2)) {
1605 for (i=2, k=1, p_2=p/2; i<=pm; i+=2, ++k, --p_2) {
1606 c = cln::exquo(c * ((p3-i) * p_2), (i-1)*k);
1607 b = b + c*results[k-1];
1610 for (i=2, k=1, p_2=p/2; i<=pm; i+=2, ++k, --p_2) {
1611 c = cln::exquo((c * (p3-i)) * p_2, cln::cl_I(i-1)*k);
1612 b = b + c*results[k-1];
1615 results.push_back(-b/(p+1));
1618 return results[n/2-1];
1622 /** Fibonacci number. The nth Fibonacci number F(n) is defined by the
1623 * recurrence formula F(n)==F(n-1)+F(n-2) with F(0)==0 and F(1)==1.
1625 * @param n an integer
1626 * @return the nth Fibonacci number F(n) (an integer number)
1627 * @exception range_error (argument must be an integer) */
1628 const numeric fibonacci(const numeric &n)
1630 if (!n.is_integer())
1631 throw std::range_error("numeric::fibonacci(): argument must be integer");
1634 // The following addition formula holds:
1636 // F(n+m) = F(m-1)*F(n) + F(m)*F(n+1) for m >= 1, n >= 0.
1638 // (Proof: For fixed m, the LHS and the RHS satisfy the same recurrence
1639 // w.r.t. n, and the initial values (n=0, n=1) agree. Hence all values
1641 // Replace m by m+1:
1642 // F(n+m+1) = F(m)*F(n) + F(m+1)*F(n+1) for m >= 0, n >= 0
1643 // Now put in m = n, to get
1644 // F(2n) = (F(n+1)-F(n))*F(n) + F(n)*F(n+1) = F(n)*(2*F(n+1) - F(n))
1645 // F(2n+1) = F(n)^2 + F(n+1)^2
1647 // F(2n+2) = F(n+1)*(2*F(n) + F(n+1))
1650 if (n.is_negative())
1652 return -fibonacci(-n);
1654 return fibonacci(-n);
1658 cln::cl_I m = cln::the<cln::cl_I>(n.to_cl_N()) >> 1L; // floor(n/2);
1659 for (uintL bit=cln::integer_length(m); bit>0; --bit) {
1660 // Since a squaring is cheaper than a multiplication, better use
1661 // three squarings instead of one multiplication and two squarings.
1662 cln::cl_I u2 = cln::square(u);
1663 cln::cl_I v2 = cln::square(v);
1664 if (cln::logbitp(bit-1, m)) {
1665 v = cln::square(u + v) - u2;
1668 u = v2 - cln::square(v - u);
1673 // Here we don't use the squaring formula because one multiplication
1674 // is cheaper than two squarings.
1675 return u * ((v << 1) - u);
1677 return cln::square(u) + cln::square(v);
1681 /** Absolute value. */
1682 const numeric abs(const numeric& x)
1684 return cln::abs(x.to_cl_N());
1688 /** Modulus (in positive representation).
1689 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1690 * sign of a or is zero. This is different from Maple's modp, where the sign
1691 * of b is ignored. It is in agreement with Mathematica's Mod.
1693 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1694 * integer, 0 otherwise. */
1695 const numeric mod(const numeric &a, const numeric &b)
1697 if (a.is_integer() && b.is_integer())
1698 return cln::mod(cln::the<cln::cl_I>(a.to_cl_N()),
1699 cln::the<cln::cl_I>(b.to_cl_N()));
1705 /** Modulus (in symmetric representation).
1706 * Equivalent to Maple's mods.
1708 * @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1709 const numeric smod(const numeric &a, const numeric &b)
1711 if (a.is_integer() && b.is_integer()) {
1712 const cln::cl_I b2 = cln::ceiling1(cln::the<cln::cl_I>(b.to_cl_N()) >> 1) - 1;
1713 return cln::mod(cln::the<cln::cl_I>(a.to_cl_N()) + b2,
1714 cln::the<cln::cl_I>(b.to_cl_N())) - b2;
1720 /** Numeric integer remainder.
1721 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1722 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1723 * sign of a or is zero.
1725 * @return remainder of a/b if both are integer, 0 otherwise.
1726 * @exception overflow_error (division by zero) if b is zero. */
1727 const numeric irem(const numeric &a, const numeric &b)
1730 throw std::overflow_error("numeric::irem(): division by zero");
1731 if (a.is_integer() && b.is_integer())
1732 return cln::rem(cln::the<cln::cl_I>(a.to_cl_N()),
1733 cln::the<cln::cl_I>(b.to_cl_N()));
1739 /** Numeric integer remainder.
1740 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1741 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1742 * and irem(a,b) has the sign of a or is zero.
1744 * @return remainder of a/b and quotient stored in q if both are integer,
1746 * @exception overflow_error (division by zero) if b is zero. */
1747 const numeric irem(const numeric &a, const numeric &b, numeric &q)
1750 throw std::overflow_error("numeric::irem(): division by zero");
1751 if (a.is_integer() && b.is_integer()) {
1752 const cln::cl_I_div_t rem_quo = cln::truncate2(cln::the<cln::cl_I>(a.to_cl_N()),
1753 cln::the<cln::cl_I>(b.to_cl_N()));
1754 q = rem_quo.quotient;
1755 return rem_quo.remainder;
1763 /** Numeric integer quotient.
1764 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1766 * @return truncated quotient of a/b if both are integer, 0 otherwise.
1767 * @exception overflow_error (division by zero) if b is zero. */
1768 const numeric iquo(const numeric &a, const numeric &b)
1771 throw std::overflow_error("numeric::iquo(): division by zero");
1772 if (a.is_integer() && b.is_integer())
1773 return cln::truncate1(cln::the<cln::cl_I>(a.to_cl_N()),
1774 cln::the<cln::cl_I>(b.to_cl_N()));
1780 /** Numeric integer quotient.
1781 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1782 * r == a - iquo(a,b,r)*b.
1784 * @return truncated quotient of a/b and remainder stored in r if both are
1785 * integer, 0 otherwise.
1786 * @exception overflow_error (division by zero) if b is zero. */
1787 const numeric iquo(const numeric &a, const numeric &b, numeric &r)
1790 throw std::overflow_error("numeric::iquo(): division by zero");
1791 if (a.is_integer() && b.is_integer()) {
1792 const cln::cl_I_div_t rem_quo = cln::truncate2(cln::the<cln::cl_I>(a.to_cl_N()),
1793 cln::the<cln::cl_I>(b.to_cl_N()));
1794 r = rem_quo.remainder;
1795 return rem_quo.quotient;
1803 /** Greatest Common Divisor.
1805 * @return The GCD of two numbers if both are integer, a numerical 1
1806 * if they are not. */
1807 const numeric gcd(const numeric &a, const numeric &b)
1809 if (a.is_integer() && b.is_integer())
1810 return cln::gcd(cln::the<cln::cl_I>(a.to_cl_N()),
1811 cln::the<cln::cl_I>(b.to_cl_N()));
1817 /** Least Common Multiple.
1819 * @return The LCM of two numbers if both are integer, the product of those
1820 * two numbers if they are not. */
1821 const numeric lcm(const numeric &a, const numeric &b)
1823 if (a.is_integer() && b.is_integer())
1824 return cln::lcm(cln::the<cln::cl_I>(a.to_cl_N()),
1825 cln::the<cln::cl_I>(b.to_cl_N()));
1831 /** Numeric square root.
1832 * If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4)
1833 * should return integer 2.
1835 * @param z numeric argument
1836 * @return square root of z. Branch cut along negative real axis, the negative
1837 * real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part
1838 * where imag(z)>0. */
1839 const numeric sqrt(const numeric &z)
1841 return cln::sqrt(z.to_cl_N());
1845 /** Integer numeric square root. */
1846 const numeric isqrt(const numeric &x)
1848 if (x.is_integer()) {
1850 cln::isqrt(cln::the<cln::cl_I>(x.to_cl_N()), &root);
1857 /** Floating point evaluation of Archimedes' constant Pi. */
1860 return numeric(cln::pi(cln::default_float_format));
1864 /** Floating point evaluation of Euler's constant gamma. */
1867 return numeric(cln::eulerconst(cln::default_float_format));
1871 /** Floating point evaluation of Catalan's constant. */
1872 ex CatalanEvalf(void)
1874 return numeric(cln::catalanconst(cln::default_float_format));
1878 /** _numeric_digits default ctor, checking for singleton invariance. */
1879 _numeric_digits::_numeric_digits()
1882 // It initializes to 17 digits, because in CLN float_format(17) turns out
1883 // to be 61 (<64) while float_format(18)=65. The reason is we want to
1884 // have a cl_LF instead of cl_SF, cl_FF or cl_DF.
1886 throw(std::runtime_error("I told you not to do instantiate me!"));
1888 cln::default_float_format = cln::float_format(17);
1892 /** Assign a native long to global Digits object. */
1893 _numeric_digits& _numeric_digits::operator=(long prec)
1896 cln::default_float_format = cln::float_format(prec);
1901 /** Convert global Digits object to native type long. */
1902 _numeric_digits::operator long()
1904 // BTW, this is approx. unsigned(cln::default_float_format*0.301)-1
1905 return (long)digits;
1909 /** Append global Digits object to ostream. */
1910 void _numeric_digits::print(std::ostream &os) const
1916 std::ostream& operator<<(std::ostream &os, const _numeric_digits &e)
1923 // static member variables
1928 bool _numeric_digits::too_late = false;
1931 /** Accuracy in decimal digits. Only object of this type! Can be set using
1932 * assignment from C++ unsigned ints and evaluated like any built-in type. */
1933 _numeric_digits Digits;
1935 } // namespace GiNaC