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-2001 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
33 #if defined(HAVE_SSTREAM)
35 #elif defined(HAVE_STRSTREAM)
38 #error Need either sstream or strstream
48 // CLN should pollute the global namespace as little as possible. Hence, we
49 // include most of it here and include only the part needed for properly
50 // declaring cln::cl_number in numeric.h. This can only be safely done in
51 // namespaced versions of CLN, i.e. version > 1.1.0. Also, we only need a
52 // subset of CLN, so we don't include the complete <cln/cln.h> but only the
54 #include <cln/output.h>
55 #include <cln/integer_io.h>
56 #include <cln/integer_ring.h>
57 #include <cln/rational_io.h>
58 #include <cln/rational_ring.h>
59 #include <cln/lfloat_class.h>
60 #include <cln/lfloat_io.h>
61 #include <cln/real_io.h>
62 #include <cln/real_ring.h>
63 #include <cln/complex_io.h>
64 #include <cln/complex_ring.h>
65 #include <cln/numtheory.h>
69 GINAC_IMPLEMENT_REGISTERED_CLASS(numeric, basic)
72 // default ctor, dtor, copy ctor assignment
73 // operator and helpers
76 /** default ctor. Numerically it initializes to an integer zero. */
77 numeric::numeric() : basic(TINFO_numeric)
79 debugmsg("numeric default ctor", LOGLEVEL_CONSTRUCT);
81 setflag(status_flags::evaluated | status_flags::expanded);
84 void numeric::copy(const numeric &other)
86 inherited::copy(other);
90 DEFAULT_DESTROY(numeric)
98 numeric::numeric(int i) : basic(TINFO_numeric)
100 debugmsg("numeric ctor from int",LOGLEVEL_CONSTRUCT);
101 // Not the whole int-range is available if we don't cast to long
102 // first. This is due to the behaviour of the cl_I-ctor, which
103 // emphasizes efficiency. However, if the integer is small enough,
104 // i.e. satisfies cl_immediate_p(), we save space and dereferences by
105 // using an immediate type:
106 if (cln::cl_immediate_p(i))
107 value = cln::cl_I(i);
109 value = cln::cl_I((long) i);
110 setflag(status_flags::evaluated | status_flags::expanded);
114 numeric::numeric(unsigned int i) : basic(TINFO_numeric)
116 debugmsg("numeric ctor from uint",LOGLEVEL_CONSTRUCT);
117 // Not the whole uint-range is available if we don't cast to ulong
118 // first. This is due to the behaviour of the cl_I-ctor, which
119 // emphasizes efficiency. However, if the integer is small enough,
120 // i.e. satisfies cl_immediate_p(), we save space and dereferences by
121 // using an immediate type:
122 if (cln::cl_immediate_p(i))
123 value = cln::cl_I(i);
125 value = cln::cl_I((unsigned long) i);
126 setflag(status_flags::evaluated | status_flags::expanded);
130 numeric::numeric(long i) : basic(TINFO_numeric)
132 debugmsg("numeric ctor from long",LOGLEVEL_CONSTRUCT);
133 value = cln::cl_I(i);
134 setflag(status_flags::evaluated | status_flags::expanded);
138 numeric::numeric(unsigned long i) : basic(TINFO_numeric)
140 debugmsg("numeric ctor from ulong",LOGLEVEL_CONSTRUCT);
141 value = cln::cl_I(i);
142 setflag(status_flags::evaluated | status_flags::expanded);
145 /** Ctor for rational numerics a/b.
147 * @exception overflow_error (division by zero) */
148 numeric::numeric(long numer, long denom) : basic(TINFO_numeric)
150 debugmsg("numeric ctor from long/long",LOGLEVEL_CONSTRUCT);
152 throw std::overflow_error("division by zero");
153 value = cln::cl_I(numer) / cln::cl_I(denom);
154 setflag(status_flags::evaluated | status_flags::expanded);
158 numeric::numeric(double d) : basic(TINFO_numeric)
160 debugmsg("numeric ctor from double",LOGLEVEL_CONSTRUCT);
161 // We really want to explicitly use the type cl_LF instead of the
162 // more general cl_F, since that would give us a cl_DF only which
163 // will not be promoted to cl_LF if overflow occurs:
164 value = cln::cl_float(d, cln::default_float_format);
165 setflag(status_flags::evaluated | status_flags::expanded);
169 /** ctor from C-style string. It also accepts complex numbers in GiNaC
170 * notation like "2+5*I". */
171 numeric::numeric(const char *s) : basic(TINFO_numeric)
173 debugmsg("numeric ctor from string",LOGLEVEL_CONSTRUCT);
174 cln::cl_N ctorval = 0;
175 // parse complex numbers (functional but not completely safe, unfortunately
176 // std::string does not understand regexpese):
177 // ss should represent a simple sum like 2+5*I
179 // make it safe by adding explicit sign
180 if (ss.at(0) != '+' && ss.at(0) != '-' && ss.at(0) != '#')
182 std::string::size_type delim;
184 // chop ss into terms from left to right
186 bool imaginary = false;
187 delim = ss.find_first_of(std::string("+-"),1);
188 // Do we have an exponent marker like "31.415E-1"? If so, hop on!
189 if ((delim != std::string::npos) && (ss.at(delim-1) == 'E'))
190 delim = ss.find_first_of(std::string("+-"),delim+1);
191 term = ss.substr(0,delim);
192 if (delim != std::string::npos)
193 ss = ss.substr(delim);
194 // is the term imaginary?
195 if (term.find("I") != std::string::npos) {
197 term = term.replace(term.find("I"),1,"");
199 if (term.find("*") != std::string::npos)
200 term = term.replace(term.find("*"),1,"");
201 // correct for trivial +/-I without explicit factor on I:
202 if (term.size() == 1)
206 if (term.find(".") != std::string::npos) {
207 // CLN's short type cl_SF is not very useful within the GiNaC
208 // framework where we are mainly interested in the arbitrary
209 // precision type cl_LF. Hence we go straight to the construction
210 // of generic floats. In order to create them we have to convert
211 // our own floating point notation used for output and construction
212 // from char * to CLN's generic notation:
213 // 3.14 --> 3.14e0_<Digits>
214 // 31.4E-1 --> 31.4e-1_<Digits>
216 // No exponent marker? Let's add a trivial one.
217 if (term.find("E") == std::string::npos)
220 term = term.replace(term.find("E"),1,"e");
221 // append _<Digits> to term
222 #if defined(HAVE_SSTREAM)
223 std::ostringstream buf;
224 buf << unsigned(Digits) << std::ends;
225 term += "_" + buf.str();
228 std::ostrstream(buf,sizeof(buf)) << unsigned(Digits) << std::ends;
229 term += "_" + std::string(buf);
231 // construct float using cln::cl_F(const char *) ctor.
233 ctorval = ctorval + cln::complex(cln::cl_I(0),cln::cl_F(term.c_str()));
235 ctorval = ctorval + cln::cl_F(term.c_str());
237 // not a floating point number...
239 ctorval = ctorval + cln::complex(cln::cl_I(0),cln::cl_R(term.c_str()));
241 ctorval = ctorval + cln::cl_R(term.c_str());
243 } while(delim != std::string::npos);
245 setflag(status_flags::evaluated | status_flags::expanded);
249 /** Ctor from CLN types. This is for the initiated user or internal use
251 numeric::numeric(const cln::cl_N &z) : basic(TINFO_numeric)
253 debugmsg("numeric ctor from cl_N", LOGLEVEL_CONSTRUCT);
255 setflag(status_flags::evaluated | status_flags::expanded);
262 numeric::numeric(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
264 debugmsg("numeric ctor from archive_node", LOGLEVEL_CONSTRUCT);
265 cln::cl_N ctorval = 0;
267 // Read number as string
269 if (n.find_string("number", str)) {
271 std::istringstream s(str);
273 std::istrstream s(str.c_str(), str.size() + 1);
275 cln::cl_idecoded_float re, im;
279 case 'R': // Integer-decoded real number
280 s >> re.sign >> re.mantissa >> re.exponent;
281 ctorval = re.sign * re.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), re.exponent);
283 case 'C': // Integer-decoded complex number
284 s >> re.sign >> re.mantissa >> re.exponent;
285 s >> im.sign >> im.mantissa >> im.exponent;
286 ctorval = cln::complex(re.sign * re.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), re.exponent),
287 im.sign * im.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), im.exponent));
289 default: // Ordinary number
296 setflag(status_flags::evaluated | status_flags::expanded);
299 void numeric::archive(archive_node &n) const
301 inherited::archive(n);
303 // Write number as string
305 std::ostringstream s;
308 std::ostrstream s(buf, 1024);
310 if (this->is_crational())
311 s << cln::the<cln::cl_N>(value);
313 // Non-rational numbers are written in an integer-decoded format
314 // to preserve the precision
315 if (this->is_real()) {
316 cln::cl_idecoded_float re = cln::integer_decode_float(cln::the<cln::cl_F>(value));
318 s << re.sign << " " << re.mantissa << " " << re.exponent;
320 cln::cl_idecoded_float re = cln::integer_decode_float(cln::the<cln::cl_F>(cln::realpart(cln::the<cln::cl_N>(value))));
321 cln::cl_idecoded_float im = cln::integer_decode_float(cln::the<cln::cl_F>(cln::imagpart(cln::the<cln::cl_N>(value))));
323 s << re.sign << " " << re.mantissa << " " << re.exponent << " ";
324 s << im.sign << " " << im.mantissa << " " << im.exponent;
328 n.add_string("number", s.str());
331 std::string str(buf);
332 n.add_string("number", str);
336 DEFAULT_UNARCHIVE(numeric)
339 // functions overriding virtual functions from base classes
342 /** Helper function to print a real number in a nicer way than is CLN's
343 * default. Instead of printing 42.0L0 this just prints 42.0 to ostream os
344 * and instead of 3.99168L7 it prints 3.99168E7. This is fine in GiNaC as
345 * long as it only uses cl_LF and no other floating point types that we might
346 * want to visibly distinguish from cl_LF.
348 * @see numeric::print() */
349 static void print_real_number(std::ostream &os, const cln::cl_R &num)
351 cln::cl_print_flags ourflags;
352 if (cln::instanceof(num, cln::cl_RA_ring)) {
353 // case 1: integer or rational, nothing special to do:
354 cln::print_real(os, ourflags, num);
357 // make CLN believe this number has default_float_format, so it prints
358 // 'E' as exponent marker instead of 'L':
359 ourflags.default_float_format = cln::float_format(cln::the<cln::cl_F>(num));
360 cln::print_real(os, ourflags, num);
364 /** This method adds to the output so it blends more consistently together
365 * with the other routines and produces something compatible to ginsh input.
367 * @see print_real_number() */
368 void numeric::print(const print_context & c, unsigned level) const
370 debugmsg("numeric print", LOGLEVEL_PRINT);
372 if (is_a<print_tree>(c)) {
374 c.s << std::string(level, ' ') << cln::the<cln::cl_N>(value)
375 << " (" << class_name() << ")"
376 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
379 } else if (is_a<print_csrc>(c)) {
381 std::ios::fmtflags oldflags = c.s.flags();
382 c.s.setf(std::ios::scientific);
383 if (this->is_rational() && !this->is_integer()) {
384 if (compare(_num0()) > 0) {
386 if (is_a<print_csrc_cl_N>(c))
387 c.s << "cln::cl_F(\"" << numer().evalf() << "\")";
389 c.s << numer().to_double();
392 if (is_a<print_csrc_cl_N>(c))
393 c.s << "cln::cl_F(\"" << -numer().evalf() << "\")";
395 c.s << -numer().to_double();
398 if (is_a<print_csrc_cl_N>(c))
399 c.s << "cln::cl_F(\"" << denom().evalf() << "\")";
401 c.s << denom().to_double();
404 if (is_a<print_csrc_cl_N>(c))
405 c.s << "cln::cl_F(\"" << evalf() << "\")";
412 const std::string par_open = is_a<print_latex>(c) ? "{(" : "(";
413 const std::string par_close = is_a<print_latex>(c) ? ")}" : ")";
414 const std::string imag_sym = is_a<print_latex>(c) ? "i" : "I";
415 const std::string mul_sym = is_a<print_latex>(c) ? " " : "*";
416 const cln::cl_R r = cln::realpart(cln::the<cln::cl_N>(value));
417 const cln::cl_R i = cln::imagpart(cln::the<cln::cl_N>(value));
419 // case 1, real: x or -x
420 if ((precedence() <= level) && (!this->is_nonneg_integer())) {
422 print_real_number(c.s, r);
425 print_real_number(c.s, r);
429 // case 2, imaginary: y*I or -y*I
430 if ((precedence() <= level) && (i < 0)) {
432 c.s << par_open+imag_sym+par_close;
435 print_real_number(c.s, i);
436 c.s << mul_sym+imag_sym+par_close;
443 c.s << "-" << imag_sym;
445 print_real_number(c.s, i);
446 c.s << mul_sym+imag_sym;
451 // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I
452 if (precedence() <= level)
454 print_real_number(c.s, r);
459 print_real_number(c.s, i);
460 c.s << mul_sym+imag_sym;
467 print_real_number(c.s, i);
468 c.s << mul_sym+imag_sym;
471 if (precedence() <= level)
478 bool numeric::info(unsigned inf) const
481 case info_flags::numeric:
482 case info_flags::polynomial:
483 case info_flags::rational_function:
485 case info_flags::real:
487 case info_flags::rational:
488 case info_flags::rational_polynomial:
489 return is_rational();
490 case info_flags::crational:
491 case info_flags::crational_polynomial:
492 return is_crational();
493 case info_flags::integer:
494 case info_flags::integer_polynomial:
496 case info_flags::cinteger:
497 case info_flags::cinteger_polynomial:
498 return is_cinteger();
499 case info_flags::positive:
500 return is_positive();
501 case info_flags::negative:
502 return is_negative();
503 case info_flags::nonnegative:
504 return !is_negative();
505 case info_flags::posint:
506 return is_pos_integer();
507 case info_flags::negint:
508 return is_integer() && is_negative();
509 case info_flags::nonnegint:
510 return is_nonneg_integer();
511 case info_flags::even:
513 case info_flags::odd:
515 case info_flags::prime:
517 case info_flags::algebraic:
523 /** Disassemble real part and imaginary part to scan for the occurrence of a
524 * single number. Also handles the imaginary unit. It ignores the sign on
525 * both this and the argument, which may lead to what might appear as funny
526 * results: (2+I).has(-2) -> true. But this is consistent, since we also
527 * would like to have (-2+I).has(2) -> true and we want to think about the
528 * sign as a multiplicative factor. */
529 bool numeric::has(const ex &other) const
531 if (!is_exactly_of_type(*other.bp, numeric))
533 const numeric &o = static_cast<const numeric &>(*other.bp);
534 if (this->is_equal(o) || this->is_equal(-o))
536 if (o.imag().is_zero()) // e.g. scan for 3 in -3*I
537 return (this->real().is_equal(o) || this->imag().is_equal(o) ||
538 this->real().is_equal(-o) || this->imag().is_equal(-o));
540 if (o.is_equal(I)) // e.g scan for I in 42*I
541 return !this->is_real();
542 if (o.real().is_zero()) // e.g. scan for 2*I in 2*I+1
543 return (this->real().has(o*I) || this->imag().has(o*I) ||
544 this->real().has(-o*I) || this->imag().has(-o*I));
550 /** Evaluation of numbers doesn't do anything at all. */
551 ex numeric::eval(int level) const
553 // Warning: if this is ever gonna do something, the ex ctors from all kinds
554 // of numbers should be checking for status_flags::evaluated.
559 /** Cast numeric into a floating-point object. For example exact numeric(1) is
560 * returned as a 1.0000000000000000000000 and so on according to how Digits is
561 * currently set. In case the object already was a floating point number the
562 * precision is trimmed to match the currently set default.
564 * @param level ignored, only needed for overriding basic::evalf.
565 * @return an ex-handle to a numeric. */
566 ex numeric::evalf(int level) const
568 // level can safely be discarded for numeric objects.
569 return numeric(cln::cl_float(1.0, cln::default_float_format) *
570 (cln::the<cln::cl_N>(value)));
575 int numeric::compare_same_type(const basic &other) const
577 GINAC_ASSERT(is_exactly_of_type(other, numeric));
578 const numeric &o = static_cast<const numeric &>(other);
580 return this->compare(o);
584 bool numeric::is_equal_same_type(const basic &other) const
586 GINAC_ASSERT(is_exactly_of_type(other,numeric));
587 const numeric &o = static_cast<const numeric &>(other);
589 return this->is_equal(o);
593 unsigned numeric::calchash(void) const
595 // Use CLN's hashcode. Warning: It depends only on the number's value, not
596 // its type or precision (i.e. a true equivalence relation on numbers). As
597 // a consequence, 3 and 3.0 share the same hashvalue.
598 setflag(status_flags::hash_calculated);
599 return (hashvalue = cln::equal_hashcode(cln::the<cln::cl_N>(value)) | 0x80000000U);
604 // new virtual functions which can be overridden by derived classes
610 // non-virtual functions in this class
615 /** Numerical addition method. Adds argument to *this and returns result as
616 * a numeric object. */
617 const numeric numeric::add(const numeric &other) const
619 // Efficiency shortcut: trap the neutral element by pointer.
620 static const numeric * _num0p = &_num0();
623 else if (&other==_num0p)
626 return numeric(cln::the<cln::cl_N>(value)+cln::the<cln::cl_N>(other.value));
630 /** Numerical subtraction method. Subtracts argument from *this and returns
631 * result as a numeric object. */
632 const numeric numeric::sub(const numeric &other) const
634 return numeric(cln::the<cln::cl_N>(value)-cln::the<cln::cl_N>(other.value));
638 /** Numerical multiplication method. Multiplies *this and argument and returns
639 * result as a numeric object. */
640 const numeric numeric::mul(const numeric &other) const
642 // Efficiency shortcut: trap the neutral element by pointer.
643 static const numeric * _num1p = &_num1();
646 else if (&other==_num1p)
649 return numeric(cln::the<cln::cl_N>(value)*cln::the<cln::cl_N>(other.value));
653 /** Numerical division method. Divides *this by argument and returns result as
656 * @exception overflow_error (division by zero) */
657 const numeric numeric::div(const numeric &other) const
659 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
660 throw std::overflow_error("numeric::div(): division by zero");
661 return numeric(cln::the<cln::cl_N>(value)/cln::the<cln::cl_N>(other.value));
665 /** Numerical exponentiation. Raises *this to the power given as argument and
666 * returns result as a numeric object. */
667 const numeric numeric::power(const numeric &other) const
669 // Efficiency shortcut: trap the neutral exponent by pointer.
670 static const numeric * _num1p = &_num1();
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)));
688 const numeric &numeric::add_dyn(const numeric &other) const
690 // Efficiency shortcut: trap the neutral element by pointer.
691 static const numeric * _num0p = &_num0();
694 else if (&other==_num0p)
697 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)+cln::the<cln::cl_N>(other.value)))->
698 setflag(status_flags::dynallocated));
702 const numeric &numeric::sub_dyn(const numeric &other) const
704 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)-cln::the<cln::cl_N>(other.value)))->
705 setflag(status_flags::dynallocated));
709 const numeric &numeric::mul_dyn(const numeric &other) const
711 // Efficiency shortcut: trap the neutral element by pointer.
712 static const numeric * _num1p = &_num1();
715 else if (&other==_num1p)
718 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)*cln::the<cln::cl_N>(other.value)))->
719 setflag(status_flags::dynallocated));
723 const numeric &numeric::div_dyn(const numeric &other) const
725 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
726 throw std::overflow_error("division by zero");
727 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)/cln::the<cln::cl_N>(other.value)))->
728 setflag(status_flags::dynallocated));
732 const numeric &numeric::power_dyn(const numeric &other) const
734 // Efficiency shortcut: trap the neutral exponent by pointer.
735 static const numeric * _num1p=&_num1();
739 if (cln::zerop(cln::the<cln::cl_N>(value))) {
740 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
741 throw std::domain_error("numeric::eval(): pow(0,0) is undefined");
742 else if (cln::zerop(cln::realpart(cln::the<cln::cl_N>(other.value))))
743 throw std::domain_error("numeric::eval(): pow(0,I) is undefined");
744 else if (cln::minusp(cln::realpart(cln::the<cln::cl_N>(other.value))))
745 throw std::overflow_error("numeric::eval(): division by zero");
749 return static_cast<const numeric &>((new numeric(cln::expt(cln::the<cln::cl_N>(value),cln::the<cln::cl_N>(other.value))))->
750 setflag(status_flags::dynallocated));
754 const numeric &numeric::operator=(int i)
756 return operator=(numeric(i));
760 const numeric &numeric::operator=(unsigned int i)
762 return operator=(numeric(i));
766 const numeric &numeric::operator=(long i)
768 return operator=(numeric(i));
772 const numeric &numeric::operator=(unsigned long i)
774 return operator=(numeric(i));
778 const numeric &numeric::operator=(double d)
780 return operator=(numeric(d));
784 const numeric &numeric::operator=(const char * s)
786 return operator=(numeric(s));
790 /** Inverse of a number. */
791 const numeric numeric::inverse(void) const
793 if (cln::zerop(cln::the<cln::cl_N>(value)))
794 throw std::overflow_error("numeric::inverse(): division by zero");
795 return numeric(cln::recip(cln::the<cln::cl_N>(value)));
799 /** Return the complex half-plane (left or right) in which the number lies.
800 * csgn(x)==0 for x==0, csgn(x)==1 for Re(x)>0 or Re(x)=0 and Im(x)>0,
801 * csgn(x)==-1 for Re(x)<0 or Re(x)=0 and Im(x)<0.
803 * @see numeric::compare(const numeric &other) */
804 int numeric::csgn(void) const
806 if (cln::zerop(cln::the<cln::cl_N>(value)))
808 cln::cl_R r = cln::realpart(cln::the<cln::cl_N>(value));
809 if (!cln::zerop(r)) {
815 if (cln::plusp(cln::imagpart(cln::the<cln::cl_N>(value))))
823 /** This method establishes a canonical order on all numbers. For complex
824 * numbers this is not possible in a mathematically consistent way but we need
825 * to establish some order and it ought to be fast. So we simply define it
826 * to be compatible with our method csgn.
828 * @return csgn(*this-other)
829 * @see numeric::csgn(void) */
830 int numeric::compare(const numeric &other) const
832 // Comparing two real numbers?
833 if (cln::instanceof(value, cln::cl_R_ring) &&
834 cln::instanceof(other.value, cln::cl_R_ring))
835 // Yes, so just cln::compare them
836 return cln::compare(cln::the<cln::cl_R>(value), cln::the<cln::cl_R>(other.value));
838 // No, first cln::compare real parts...
839 cl_signean real_cmp = cln::compare(cln::realpart(cln::the<cln::cl_N>(value)), cln::realpart(cln::the<cln::cl_N>(other.value)));
842 // ...and then the imaginary parts.
843 return cln::compare(cln::imagpart(cln::the<cln::cl_N>(value)), cln::imagpart(cln::the<cln::cl_N>(other.value)));
848 bool numeric::is_equal(const numeric &other) const
850 return cln::equal(cln::the<cln::cl_N>(value),cln::the<cln::cl_N>(other.value));
854 /** True if object is zero. */
855 bool numeric::is_zero(void) const
857 return cln::zerop(cln::the<cln::cl_N>(value));
861 /** True if object is not complex and greater than zero. */
862 bool numeric::is_positive(void) const
865 return cln::plusp(cln::the<cln::cl_R>(value));
870 /** True if object is not complex and less than zero. */
871 bool numeric::is_negative(void) const
874 return cln::minusp(cln::the<cln::cl_R>(value));
879 /** True if object is a non-complex integer. */
880 bool numeric::is_integer(void) const
882 return cln::instanceof(value, cln::cl_I_ring);
886 /** True if object is an exact integer greater than zero. */
887 bool numeric::is_pos_integer(void) const
889 return (this->is_integer() && cln::plusp(cln::the<cln::cl_I>(value)));
893 /** True if object is an exact integer greater or equal zero. */
894 bool numeric::is_nonneg_integer(void) const
896 return (this->is_integer() && !cln::minusp(cln::the<cln::cl_I>(value)));
900 /** True if object is an exact even integer. */
901 bool numeric::is_even(void) const
903 return (this->is_integer() && cln::evenp(cln::the<cln::cl_I>(value)));
907 /** True if object is an exact odd integer. */
908 bool numeric::is_odd(void) const
910 return (this->is_integer() && cln::oddp(cln::the<cln::cl_I>(value)));
914 /** Probabilistic primality test.
916 * @return true if object is exact integer and prime. */
917 bool numeric::is_prime(void) const
919 return (this->is_integer() && cln::isprobprime(cln::the<cln::cl_I>(value)));
923 /** True if object is an exact rational number, may even be complex
924 * (denominator may be unity). */
925 bool numeric::is_rational(void) const
927 return cln::instanceof(value, cln::cl_RA_ring);
931 /** True if object is a real integer, rational or float (but not complex). */
932 bool numeric::is_real(void) const
934 return cln::instanceof(value, cln::cl_R_ring);
938 bool numeric::operator==(const numeric &other) const
940 return cln::equal(cln::the<cln::cl_N>(value), cln::the<cln::cl_N>(other.value));
944 bool numeric::operator!=(const numeric &other) const
946 return !cln::equal(cln::the<cln::cl_N>(value), cln::the<cln::cl_N>(other.value));
950 /** True if object is element of the domain of integers extended by I, i.e. is
951 * of the form a+b*I, where a and b are integers. */
952 bool numeric::is_cinteger(void) const
954 if (cln::instanceof(value, cln::cl_I_ring))
956 else if (!this->is_real()) { // complex case, handle n+m*I
957 if (cln::instanceof(cln::realpart(cln::the<cln::cl_N>(value)), cln::cl_I_ring) &&
958 cln::instanceof(cln::imagpart(cln::the<cln::cl_N>(value)), cln::cl_I_ring))
965 /** True if object is an exact rational number, may even be complex
966 * (denominator may be unity). */
967 bool numeric::is_crational(void) const
969 if (cln::instanceof(value, cln::cl_RA_ring))
971 else if (!this->is_real()) { // complex case, handle Q(i):
972 if (cln::instanceof(cln::realpart(cln::the<cln::cl_N>(value)), cln::cl_RA_ring) &&
973 cln::instanceof(cln::imagpart(cln::the<cln::cl_N>(value)), cln::cl_RA_ring))
980 /** Numerical comparison: less.
982 * @exception invalid_argument (complex inequality) */
983 bool numeric::operator<(const numeric &other) const
985 if (this->is_real() && other.is_real())
986 return (cln::the<cln::cl_R>(value) < cln::the<cln::cl_R>(other.value));
987 throw std::invalid_argument("numeric::operator<(): complex inequality");
991 /** Numerical comparison: less or equal.
993 * @exception invalid_argument (complex inequality) */
994 bool numeric::operator<=(const numeric &other) const
996 if (this->is_real() && other.is_real())
997 return (cln::the<cln::cl_R>(value) <= cln::the<cln::cl_R>(other.value));
998 throw std::invalid_argument("numeric::operator<=(): complex inequality");
1002 /** Numerical comparison: greater.
1004 * @exception invalid_argument (complex inequality) */
1005 bool numeric::operator>(const numeric &other) const
1007 if (this->is_real() && other.is_real())
1008 return (cln::the<cln::cl_R>(value) > cln::the<cln::cl_R>(other.value));
1009 throw std::invalid_argument("numeric::operator>(): complex inequality");
1013 /** Numerical comparison: greater or equal.
1015 * @exception invalid_argument (complex inequality) */
1016 bool numeric::operator>=(const numeric &other) const
1018 if (this->is_real() && other.is_real())
1019 return (cln::the<cln::cl_R>(value) >= cln::the<cln::cl_R>(other.value));
1020 throw std::invalid_argument("numeric::operator>=(): complex inequality");
1024 /** Converts numeric types to machine's int. You should check with
1025 * is_integer() if the number is really an integer before calling this method.
1026 * You may also consider checking the range first. */
1027 int numeric::to_int(void) const
1029 GINAC_ASSERT(this->is_integer());
1030 return cln::cl_I_to_int(cln::the<cln::cl_I>(value));
1034 /** Converts numeric types to machine's long. You should check with
1035 * is_integer() if the number is really an integer before calling this method.
1036 * You may also consider checking the range first. */
1037 long numeric::to_long(void) const
1039 GINAC_ASSERT(this->is_integer());
1040 return cln::cl_I_to_long(cln::the<cln::cl_I>(value));
1044 /** Converts numeric types to machine's double. You should check with is_real()
1045 * if the number is really not complex before calling this method. */
1046 double numeric::to_double(void) const
1048 GINAC_ASSERT(this->is_real());
1049 return cln::double_approx(cln::realpart(cln::the<cln::cl_N>(value)));
1053 /** Returns a new CLN object of type cl_N, representing the value of *this.
1054 * This method may be used when mixing GiNaC and CLN in one project.
1056 cln::cl_N numeric::to_cl_N(void) const
1058 return cln::cl_N(cln::the<cln::cl_N>(value));
1062 /** Real part of a number. */
1063 const numeric numeric::real(void) const
1065 return numeric(cln::realpart(cln::the<cln::cl_N>(value)));
1069 /** Imaginary part of a number. */
1070 const numeric numeric::imag(void) const
1072 return numeric(cln::imagpart(cln::the<cln::cl_N>(value)));
1076 /** Numerator. Computes the numerator of rational numbers, rationalized
1077 * numerator of complex if real and imaginary part are both rational numbers
1078 * (i.e numer(4/3+5/6*I) == 8+5*I), the number carrying the sign in all other
1080 const numeric numeric::numer(void) const
1082 if (this->is_integer())
1083 return numeric(*this);
1085 else if (cln::instanceof(value, cln::cl_RA_ring))
1086 return numeric(cln::numerator(cln::the<cln::cl_RA>(value)));
1088 else if (!this->is_real()) { // complex case, handle Q(i):
1089 const cln::cl_RA r = cln::the<cln::cl_RA>(cln::realpart(cln::the<cln::cl_N>(value)));
1090 const cln::cl_RA i = cln::the<cln::cl_RA>(cln::imagpart(cln::the<cln::cl_N>(value)));
1091 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_I_ring))
1092 return numeric(*this);
1093 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_RA_ring))
1094 return numeric(cln::complex(r*cln::denominator(i), cln::numerator(i)));
1095 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_I_ring))
1096 return numeric(cln::complex(cln::numerator(r), i*cln::denominator(r)));
1097 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_RA_ring)) {
1098 const cln::cl_I s = cln::lcm(cln::denominator(r), cln::denominator(i));
1099 return numeric(cln::complex(cln::numerator(r)*(cln::exquo(s,cln::denominator(r))),
1100 cln::numerator(i)*(cln::exquo(s,cln::denominator(i)))));
1103 // at least one float encountered
1104 return numeric(*this);
1108 /** Denominator. Computes the denominator of rational numbers, common integer
1109 * denominator of complex if real and imaginary part are both rational numbers
1110 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
1111 const numeric numeric::denom(void) const
1113 if (this->is_integer())
1116 if (cln::instanceof(value, cln::cl_RA_ring))
1117 return numeric(cln::denominator(cln::the<cln::cl_RA>(value)));
1119 if (!this->is_real()) { // complex case, handle Q(i):
1120 const cln::cl_RA r = cln::the<cln::cl_RA>(cln::realpart(cln::the<cln::cl_N>(value)));
1121 const cln::cl_RA i = cln::the<cln::cl_RA>(cln::imagpart(cln::the<cln::cl_N>(value)));
1122 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_I_ring))
1124 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_RA_ring))
1125 return numeric(cln::denominator(i));
1126 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_I_ring))
1127 return numeric(cln::denominator(r));
1128 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_RA_ring))
1129 return numeric(cln::lcm(cln::denominator(r), cln::denominator(i)));
1131 // at least one float encountered
1136 /** Size in binary notation. For integers, this is the smallest n >= 0 such
1137 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
1138 * 2^(n-1) <= x < 2^n.
1140 * @return number of bits (excluding sign) needed to represent that number
1141 * in two's complement if it is an integer, 0 otherwise. */
1142 int numeric::int_length(void) const
1144 if (this->is_integer())
1145 return cln::integer_length(cln::the<cln::cl_I>(value));
1154 /** Imaginary unit. This is not a constant but a numeric since we are
1155 * natively handing complex numbers anyways, so in each expression containing
1156 * an I it is automatically eval'ed away anyhow. */
1157 const numeric I = numeric(cln::complex(cln::cl_I(0),cln::cl_I(1)));
1160 /** Exponential function.
1162 * @return arbitrary precision numerical exp(x). */
1163 const numeric exp(const numeric &x)
1165 return cln::exp(x.to_cl_N());
1169 /** Natural logarithm.
1171 * @param z complex number
1172 * @return arbitrary precision numerical log(x).
1173 * @exception pole_error("log(): logarithmic pole",0) */
1174 const numeric log(const numeric &z)
1177 throw pole_error("log(): logarithmic pole",0);
1178 return cln::log(z.to_cl_N());
1182 /** Numeric sine (trigonometric function).
1184 * @return arbitrary precision numerical sin(x). */
1185 const numeric sin(const numeric &x)
1187 return cln::sin(x.to_cl_N());
1191 /** Numeric cosine (trigonometric function).
1193 * @return arbitrary precision numerical cos(x). */
1194 const numeric cos(const numeric &x)
1196 return cln::cos(x.to_cl_N());
1200 /** Numeric tangent (trigonometric function).
1202 * @return arbitrary precision numerical tan(x). */
1203 const numeric tan(const numeric &x)
1205 return cln::tan(x.to_cl_N());
1209 /** Numeric inverse sine (trigonometric function).
1211 * @return arbitrary precision numerical asin(x). */
1212 const numeric asin(const numeric &x)
1214 return cln::asin(x.to_cl_N());
1218 /** Numeric inverse cosine (trigonometric function).
1220 * @return arbitrary precision numerical acos(x). */
1221 const numeric acos(const numeric &x)
1223 return cln::acos(x.to_cl_N());
1229 * @param z complex number
1231 * @exception pole_error("atan(): logarithmic pole",0) */
1232 const numeric atan(const numeric &x)
1235 x.real().is_zero() &&
1236 abs(x.imag()).is_equal(_num1()))
1237 throw pole_error("atan(): logarithmic pole",0);
1238 return cln::atan(x.to_cl_N());
1244 * @param x real number
1245 * @param y real number
1246 * @return atan(y/x) */
1247 const numeric atan(const numeric &y, const numeric &x)
1249 if (x.is_real() && y.is_real())
1250 return cln::atan(cln::the<cln::cl_R>(x.to_cl_N()),
1251 cln::the<cln::cl_R>(y.to_cl_N()));
1253 throw std::invalid_argument("atan(): complex argument");
1257 /** Numeric hyperbolic sine (trigonometric function).
1259 * @return arbitrary precision numerical sinh(x). */
1260 const numeric sinh(const numeric &x)
1262 return cln::sinh(x.to_cl_N());
1266 /** Numeric hyperbolic cosine (trigonometric function).
1268 * @return arbitrary precision numerical cosh(x). */
1269 const numeric cosh(const numeric &x)
1271 return cln::cosh(x.to_cl_N());
1275 /** Numeric hyperbolic tangent (trigonometric function).
1277 * @return arbitrary precision numerical tanh(x). */
1278 const numeric tanh(const numeric &x)
1280 return cln::tanh(x.to_cl_N());
1284 /** Numeric inverse hyperbolic sine (trigonometric function).
1286 * @return arbitrary precision numerical asinh(x). */
1287 const numeric asinh(const numeric &x)
1289 return cln::asinh(x.to_cl_N());
1293 /** Numeric inverse hyperbolic cosine (trigonometric function).
1295 * @return arbitrary precision numerical acosh(x). */
1296 const numeric acosh(const numeric &x)
1298 return cln::acosh(x.to_cl_N());
1302 /** Numeric inverse hyperbolic tangent (trigonometric function).
1304 * @return arbitrary precision numerical atanh(x). */
1305 const numeric atanh(const numeric &x)
1307 return cln::atanh(x.to_cl_N());
1311 /*static cln::cl_N Li2_series(const ::cl_N &x,
1312 const ::float_format_t &prec)
1314 // Note: argument must be in the unit circle
1315 // This is very inefficient unless we have fast floating point Bernoulli
1316 // numbers implemented!
1317 cln::cl_N c1 = -cln::log(1-x);
1319 // hard-wire the first two Bernoulli numbers
1320 cln::cl_N acc = c1 - cln::square(c1)/4;
1322 cln::cl_F pisq = cln::square(cln::cl_pi(prec)); // pi^2
1323 cln::cl_F piac = cln::cl_float(1, prec); // accumulator: pi^(2*i)
1325 c1 = cln::square(c1);
1329 aug = c2 * (*(bernoulli(numeric(2*i)).clnptr())) / cln::factorial(2*i+1);
1330 // 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));
1333 } while (acc != acc+aug);
1337 /** Numeric evaluation of Dilogarithm within circle of convergence (unit
1338 * circle) using a power series. */
1339 static cln::cl_N Li2_series(const cln::cl_N &x,
1340 const cln::float_format_t &prec)
1342 // Note: argument must be in the unit circle
1344 cln::cl_N num = cln::complex(cln::cl_float(1, prec), 0);
1349 den = den + i; // 1, 4, 9, 16, ...
1353 } while (acc != acc+aug);
1357 /** Folds Li2's argument inside a small rectangle to enhance convergence. */
1358 static cln::cl_N Li2_projection(const cln::cl_N &x,
1359 const cln::float_format_t &prec)
1361 const cln::cl_R re = cln::realpart(x);
1362 const cln::cl_R im = cln::imagpart(x);
1363 if (re > cln::cl_F(".5"))
1364 // zeta(2) - Li2(1-x) - log(x)*log(1-x)
1366 - Li2_series(1-x, prec)
1367 - cln::log(x)*cln::log(1-x));
1368 if ((re <= 0 && cln::abs(im) > cln::cl_F(".75")) || (re < cln::cl_F("-.5")))
1369 // -log(1-x)^2 / 2 - Li2(x/(x-1))
1370 return(- cln::square(cln::log(1-x))/2
1371 - Li2_series(x/(x-1), prec));
1372 if (re > 0 && cln::abs(im) > cln::cl_LF(".75"))
1373 // Li2(x^2)/2 - Li2(-x)
1374 return(Li2_projection(cln::square(x), prec)/2
1375 - Li2_projection(-x, prec));
1376 return Li2_series(x, prec);
1379 /** Numeric evaluation of Dilogarithm. The domain is the entire complex plane,
1380 * the branch cut lies along the positive real axis, starting at 1 and
1381 * continuous with quadrant IV.
1383 * @return arbitrary precision numerical Li2(x). */
1384 const numeric Li2(const numeric &x)
1389 // what is the desired float format?
1390 // first guess: default format
1391 cln::float_format_t prec = cln::default_float_format;
1392 const cln::cl_N value = x.to_cl_N();
1393 // second guess: the argument's format
1394 if (!x.real().is_rational())
1395 prec = cln::float_format(cln::the<cln::cl_F>(cln::realpart(value)));
1396 else if (!x.imag().is_rational())
1397 prec = cln::float_format(cln::the<cln::cl_F>(cln::imagpart(value)));
1399 if (cln::the<cln::cl_N>(value)==1) // may cause trouble with log(1-x)
1400 return cln::zeta(2, prec);
1402 if (cln::abs(value) > 1)
1403 // -log(-x)^2 / 2 - zeta(2) - Li2(1/x)
1404 return(- cln::square(cln::log(-value))/2
1405 - cln::zeta(2, prec)
1406 - Li2_projection(cln::recip(value), prec));
1408 return Li2_projection(x.to_cl_N(), prec);
1412 /** Numeric evaluation of Riemann's Zeta function. Currently works only for
1413 * integer arguments. */
1414 const numeric zeta(const numeric &x)
1416 // A dirty hack to allow for things like zeta(3.0), since CLN currently
1417 // only knows about integer arguments and zeta(3).evalf() automatically
1418 // cascades down to zeta(3.0).evalf(). The trick is to rely on 3.0-3
1419 // being an exact zero for CLN, which can be tested and then we can just
1420 // pass the number casted to an int:
1422 const int aux = (int)(cln::double_approx(cln::the<cln::cl_R>(x.to_cl_N())));
1423 if (cln::zerop(x.to_cl_N()-aux))
1424 return cln::zeta(aux);
1426 std::clog << "zeta(" << x
1427 << "): Does anybody know a good way to calculate this numerically?"
1433 /** The Gamma function.
1434 * This is only a stub! */
1435 const numeric lgamma(const numeric &x)
1437 std::clog << "lgamma(" << x
1438 << "): Does anybody know a good way to calculate this numerically?"
1442 const numeric tgamma(const numeric &x)
1444 std::clog << "tgamma(" << x
1445 << "): Does anybody know a good way to calculate this numerically?"
1451 /** The psi function (aka polygamma function).
1452 * This is only a stub! */
1453 const numeric psi(const numeric &x)
1455 std::clog << "psi(" << x
1456 << "): Does anybody know a good way to calculate this numerically?"
1462 /** The psi functions (aka polygamma functions).
1463 * This is only a stub! */
1464 const numeric psi(const numeric &n, const numeric &x)
1466 std::clog << "psi(" << n << "," << x
1467 << "): Does anybody know a good way to calculate this numerically?"
1473 /** Factorial combinatorial function.
1475 * @param n integer argument >= 0
1476 * @exception range_error (argument must be integer >= 0) */
1477 const numeric factorial(const numeric &n)
1479 if (!n.is_nonneg_integer())
1480 throw std::range_error("numeric::factorial(): argument must be integer >= 0");
1481 return numeric(cln::factorial(n.to_int()));
1485 /** The double factorial combinatorial function. (Scarcely used, but still
1486 * useful in cases, like for exact results of tgamma(n+1/2) for instance.)
1488 * @param n integer argument >= -1
1489 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == (-1)!! == 1
1490 * @exception range_error (argument must be integer >= -1) */
1491 const numeric doublefactorial(const numeric &n)
1493 if (n.is_equal(_num_1()))
1496 if (!n.is_nonneg_integer())
1497 throw std::range_error("numeric::doublefactorial(): argument must be integer >= -1");
1499 return numeric(cln::doublefactorial(n.to_int()));
1503 /** The Binomial coefficients. It computes the binomial coefficients. For
1504 * integer n and k and positive n this is the number of ways of choosing k
1505 * objects from n distinct objects. If n is negative, the formula
1506 * binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */
1507 const numeric binomial(const numeric &n, const numeric &k)
1509 if (n.is_integer() && k.is_integer()) {
1510 if (n.is_nonneg_integer()) {
1511 if (k.compare(n)!=1 && k.compare(_num0())!=-1)
1512 return numeric(cln::binomial(n.to_int(),k.to_int()));
1516 return _num_1().power(k)*binomial(k-n-_num1(),k);
1520 // should really be gamma(n+1)/gamma(r+1)/gamma(n-r+1) or a suitable limit
1521 throw std::range_error("numeric::binomial(): don´t know how to evaluate that.");
1525 /** Bernoulli number. The nth Bernoulli number is the coefficient of x^n/n!
1526 * in the expansion of the function x/(e^x-1).
1528 * @return the nth Bernoulli number (a rational number).
1529 * @exception range_error (argument must be integer >= 0) */
1530 const numeric bernoulli(const numeric &nn)
1532 if (!nn.is_integer() || nn.is_negative())
1533 throw std::range_error("numeric::bernoulli(): argument must be integer >= 0");
1537 // The Bernoulli numbers are rational numbers that may be computed using
1540 // B_n = - 1/(n+1) * sum_{k=0}^{n-1}(binomial(n+1,k)*B_k)
1542 // with B(0) = 1. Since the n'th Bernoulli number depends on all the
1543 // previous ones, the computation is necessarily very expensive. There are
1544 // several other ways of computing them, a particularly good one being
1548 // for (unsigned i=0; i<n; i++) {
1549 // c = exquo(c*(i-n),(i+2));
1550 // Bern = Bern + c*s/(i+2);
1551 // s = s + expt_pos(cl_I(i+2),n);
1555 // But if somebody works with the n'th Bernoulli number she is likely to
1556 // also need all previous Bernoulli numbers. So we need a complete remember
1557 // table and above divide and conquer algorithm is not suited to build one
1558 // up. The code below is adapted from Pari's function bernvec().
1560 // (There is an interesting relation with the tangent polynomials described
1561 // in `Concrete Mathematics', which leads to a program twice as fast as our
1562 // implementation below, but it requires storing one such polynomial in
1563 // addition to the remember table. This doubles the memory footprint so
1564 // we don't use it.)
1566 // the special cases not covered by the algorithm below
1567 if (nn.is_equal(_num1()))
1572 // store nonvanishing Bernoulli numbers here
1573 static std::vector< cln::cl_RA > results;
1574 static int highest_result = 0;
1575 // algorithm not applicable to B(0), so just store it
1576 if (results.empty())
1577 results.push_back(cln::cl_RA(1));
1579 int n = nn.to_long();
1580 for (int i=highest_result; i<n/2; ++i) {
1586 for (int j=i; j>0; --j) {
1587 B = cln::cl_I(n*m) * (B+results[j]) / (d1*d2);
1593 B = (1 - ((B+1)/(2*i+3))) / (cln::cl_I(1)<<(2*i+2));
1594 results.push_back(B);
1597 return results[n/2];
1601 /** Fibonacci number. The nth Fibonacci number F(n) is defined by the
1602 * recurrence formula F(n)==F(n-1)+F(n-2) with F(0)==0 and F(1)==1.
1604 * @param n an integer
1605 * @return the nth Fibonacci number F(n) (an integer number)
1606 * @exception range_error (argument must be an integer) */
1607 const numeric fibonacci(const numeric &n)
1609 if (!n.is_integer())
1610 throw std::range_error("numeric::fibonacci(): argument must be integer");
1613 // The following addition formula holds:
1615 // F(n+m) = F(m-1)*F(n) + F(m)*F(n+1) for m >= 1, n >= 0.
1617 // (Proof: For fixed m, the LHS and the RHS satisfy the same recurrence
1618 // w.r.t. n, and the initial values (n=0, n=1) agree. Hence all values
1620 // Replace m by m+1:
1621 // F(n+m+1) = F(m)*F(n) + F(m+1)*F(n+1) for m >= 0, n >= 0
1622 // Now put in m = n, to get
1623 // F(2n) = (F(n+1)-F(n))*F(n) + F(n)*F(n+1) = F(n)*(2*F(n+1) - F(n))
1624 // F(2n+1) = F(n)^2 + F(n+1)^2
1626 // F(2n+2) = F(n+1)*(2*F(n) + F(n+1))
1629 if (n.is_negative())
1631 return -fibonacci(-n);
1633 return fibonacci(-n);
1637 cln::cl_I m = cln::the<cln::cl_I>(n.to_cl_N()) >> 1L; // floor(n/2);
1638 for (uintL bit=cln::integer_length(m); bit>0; --bit) {
1639 // Since a squaring is cheaper than a multiplication, better use
1640 // three squarings instead of one multiplication and two squarings.
1641 cln::cl_I u2 = cln::square(u);
1642 cln::cl_I v2 = cln::square(v);
1643 if (cln::logbitp(bit-1, m)) {
1644 v = cln::square(u + v) - u2;
1647 u = v2 - cln::square(v - u);
1652 // Here we don't use the squaring formula because one multiplication
1653 // is cheaper than two squarings.
1654 return u * ((v << 1) - u);
1656 return cln::square(u) + cln::square(v);
1660 /** Absolute value. */
1661 const numeric abs(const numeric& x)
1663 return cln::abs(x.to_cl_N());
1667 /** Modulus (in positive representation).
1668 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1669 * sign of a or is zero. This is different from Maple's modp, where the sign
1670 * of b is ignored. It is in agreement with Mathematica's Mod.
1672 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1673 * integer, 0 otherwise. */
1674 const numeric mod(const numeric &a, const numeric &b)
1676 if (a.is_integer() && b.is_integer())
1677 return cln::mod(cln::the<cln::cl_I>(a.to_cl_N()),
1678 cln::the<cln::cl_I>(b.to_cl_N()));
1684 /** Modulus (in symmetric representation).
1685 * Equivalent to Maple's mods.
1687 * @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1688 const numeric smod(const numeric &a, const numeric &b)
1690 if (a.is_integer() && b.is_integer()) {
1691 const cln::cl_I b2 = cln::ceiling1(cln::the<cln::cl_I>(b.to_cl_N()) >> 1) - 1;
1692 return cln::mod(cln::the<cln::cl_I>(a.to_cl_N()) + b2,
1693 cln::the<cln::cl_I>(b.to_cl_N())) - b2;
1699 /** Numeric integer remainder.
1700 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1701 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1702 * sign of a or is zero.
1704 * @return remainder of a/b if both are integer, 0 otherwise. */
1705 const numeric irem(const numeric &a, const numeric &b)
1707 if (a.is_integer() && b.is_integer())
1708 return cln::rem(cln::the<cln::cl_I>(a.to_cl_N()),
1709 cln::the<cln::cl_I>(b.to_cl_N()));
1715 /** Numeric integer remainder.
1716 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1717 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1718 * and irem(a,b) has the sign of a or is zero.
1720 * @return remainder of a/b and quotient stored in q if both are integer,
1722 const numeric irem(const numeric &a, const numeric &b, numeric &q)
1724 if (a.is_integer() && b.is_integer()) {
1725 const cln::cl_I_div_t rem_quo = cln::truncate2(cln::the<cln::cl_I>(a.to_cl_N()),
1726 cln::the<cln::cl_I>(b.to_cl_N()));
1727 q = rem_quo.quotient;
1728 return rem_quo.remainder;
1736 /** Numeric integer quotient.
1737 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1739 * @return truncated quotient of a/b if both are integer, 0 otherwise. */
1740 const numeric iquo(const numeric &a, const numeric &b)
1742 if (a.is_integer() && b.is_integer())
1743 return cln::truncate1(cln::the<cln::cl_I>(a.to_cl_N()),
1744 cln::the<cln::cl_I>(b.to_cl_N()));
1750 /** Numeric integer quotient.
1751 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1752 * r == a - iquo(a,b,r)*b.
1754 * @return truncated quotient of a/b and remainder stored in r if both are
1755 * integer, 0 otherwise. */
1756 const numeric iquo(const numeric &a, const numeric &b, numeric &r)
1758 if (a.is_integer() && b.is_integer()) {
1759 const cln::cl_I_div_t rem_quo = cln::truncate2(cln::the<cln::cl_I>(a.to_cl_N()),
1760 cln::the<cln::cl_I>(b.to_cl_N()));
1761 r = rem_quo.remainder;
1762 return rem_quo.quotient;
1770 /** Greatest Common Divisor.
1772 * @return The GCD of two numbers if both are integer, a numerical 1
1773 * if they are not. */
1774 const numeric gcd(const numeric &a, const numeric &b)
1776 if (a.is_integer() && b.is_integer())
1777 return cln::gcd(cln::the<cln::cl_I>(a.to_cl_N()),
1778 cln::the<cln::cl_I>(b.to_cl_N()));
1784 /** Least Common Multiple.
1786 * @return The LCM of two numbers if both are integer, the product of those
1787 * two numbers if they are not. */
1788 const numeric lcm(const numeric &a, const numeric &b)
1790 if (a.is_integer() && b.is_integer())
1791 return cln::lcm(cln::the<cln::cl_I>(a.to_cl_N()),
1792 cln::the<cln::cl_I>(b.to_cl_N()));
1798 /** Numeric square root.
1799 * If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4)
1800 * should return integer 2.
1802 * @param z numeric argument
1803 * @return square root of z. Branch cut along negative real axis, the negative
1804 * real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part
1805 * where imag(z)>0. */
1806 const numeric sqrt(const numeric &z)
1808 return cln::sqrt(z.to_cl_N());
1812 /** Integer numeric square root. */
1813 const numeric isqrt(const numeric &x)
1815 if (x.is_integer()) {
1817 cln::isqrt(cln::the<cln::cl_I>(x.to_cl_N()), &root);
1824 /** Floating point evaluation of Archimedes' constant Pi. */
1827 return numeric(cln::pi(cln::default_float_format));
1831 /** Floating point evaluation of Euler's constant gamma. */
1834 return numeric(cln::eulerconst(cln::default_float_format));
1838 /** Floating point evaluation of Catalan's constant. */
1839 ex CatalanEvalf(void)
1841 return numeric(cln::catalanconst(cln::default_float_format));
1845 /** _numeric_digits default ctor, checking for singleton invariance. */
1846 _numeric_digits::_numeric_digits()
1849 // It initializes to 17 digits, because in CLN float_format(17) turns out
1850 // to be 61 (<64) while float_format(18)=65. The reason is we want to
1851 // have a cl_LF instead of cl_SF, cl_FF or cl_DF.
1853 throw(std::runtime_error("I told you not to do instantiate me!"));
1855 cln::default_float_format = cln::float_format(17);
1859 /** Assign a native long to global Digits object. */
1860 _numeric_digits& _numeric_digits::operator=(long prec)
1863 cln::default_float_format = cln::float_format(prec);
1868 /** Convert global Digits object to native type long. */
1869 _numeric_digits::operator long()
1871 // BTW, this is approx. unsigned(cln::default_float_format*0.301)-1
1872 return (long)digits;
1876 /** Append global Digits object to ostream. */
1877 void _numeric_digits::print(std::ostream &os) const
1879 debugmsg("_numeric_digits print", LOGLEVEL_PRINT);
1884 std::ostream& operator<<(std::ostream &os, const _numeric_digits &e)
1891 // static member variables
1896 bool _numeric_digits::too_late = false;
1899 /** Accuracy in decimal digits. Only object of this type! Can be set using
1900 * assignment from C++ unsigned ints and evaluated like any built-in type. */
1901 _numeric_digits Digits;
1903 } // namespace GiNaC