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-2000 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
47 // CLN should not pollute the global namespace, hence we include it here
48 // instead of in some header file where it would propagate to other parts.
49 // Also, we only need a subset of CLN, so we don't include the complete cln.h:
51 #include <cln/cl_output.h>
52 #include <cln/cl_integer_io.h>
53 #include <cln/cl_integer_ring.h>
54 #include <cln/cl_univpoly_integer.h>
55 #include <cln/cl_rational_io.h>
56 #include <cln/cl_rational_ring.h>
57 #include <cln/cl_lfloat_class.h>
58 #include <cln/cl_lfloat_io.h>
59 #include <cln/cl_real_io.h>
60 #include <cln/cl_real_ring.h>
61 #include <cln/cl_complex_io.h>
62 #include <cln/cl_complex_ring.h>
63 #include <cln/cl_numtheory.h>
64 #else // def HAVE_CLN_CLN_H
65 #include <cl_output.h>
66 #include <cl_integer_io.h>
67 #include <cl_integer_ring.h>
68 #include <cl_univpoly_integer.h>
69 #include <cl_rational_io.h>
70 #include <cl_rational_ring.h>
71 #include <cl_lfloat_class.h>
72 #include <cl_lfloat_io.h>
73 #include <cl_real_io.h>
74 #include <cl_real_ring.h>
75 #include <cl_complex_io.h>
76 #include <cl_complex_ring.h>
77 #include <cl_numtheory.h>
78 #endif // def HAVE_CLN_CLN_H
80 #ifndef NO_NAMESPACE_GINAC
82 #endif // ndef NO_NAMESPACE_GINAC
84 // linker has no problems finding text symbols for numerator or denominator
87 GINAC_IMPLEMENT_REGISTERED_CLASS(numeric, basic)
90 // default constructor, destructor, copy constructor assignment
91 // operator and helpers
96 /** default ctor. Numerically it initializes to an integer zero. */
97 numeric::numeric() : basic(TINFO_numeric)
99 debugmsg("numeric default constructor", LOGLEVEL_CONSTRUCT);
103 setflag(status_flags::evaluated |
104 status_flags::expanded |
105 status_flags::hash_calculated);
110 debugmsg("numeric destructor" ,LOGLEVEL_DESTRUCT);
114 numeric::numeric(const numeric & other)
116 debugmsg("numeric copy constructor", LOGLEVEL_CONSTRUCT);
120 const numeric & numeric::operator=(const numeric & other)
122 debugmsg("numeric operator=", LOGLEVEL_ASSIGNMENT);
123 if (this != &other) {
132 void numeric::copy(const numeric & other)
135 value = new ::cl_N(*other.value);
138 void numeric::destroy(bool call_parent)
141 if (call_parent) basic::destroy(call_parent);
145 // other constructors
150 numeric::numeric(int i) : basic(TINFO_numeric)
152 debugmsg("numeric constructor from int",LOGLEVEL_CONSTRUCT);
153 // Not the whole int-range is available if we don't cast to long
154 // first. This is due to the behaviour of the cl_I-ctor, which
155 // emphasizes efficiency:
156 value = new ::cl_I((long) i);
158 setflag(status_flags::evaluated|
159 status_flags::hash_calculated);
163 numeric::numeric(unsigned int i) : basic(TINFO_numeric)
165 debugmsg("numeric constructor from uint",LOGLEVEL_CONSTRUCT);
166 // Not the whole uint-range is available if we don't cast to ulong
167 // first. This is due to the behaviour of the cl_I-ctor, which
168 // emphasizes efficiency:
169 value = new ::cl_I((unsigned long)i);
171 setflag(status_flags::evaluated|
172 status_flags::hash_calculated);
176 numeric::numeric(long i) : basic(TINFO_numeric)
178 debugmsg("numeric constructor from long",LOGLEVEL_CONSTRUCT);
179 value = new ::cl_I(i);
181 setflag(status_flags::evaluated|
182 status_flags::hash_calculated);
186 numeric::numeric(unsigned long i) : basic(TINFO_numeric)
188 debugmsg("numeric constructor from ulong",LOGLEVEL_CONSTRUCT);
189 value = new ::cl_I(i);
191 setflag(status_flags::evaluated|
192 status_flags::hash_calculated);
195 /** Ctor for rational numerics a/b.
197 * @exception overflow_error (division by zero) */
198 numeric::numeric(long numer, long denom) : basic(TINFO_numeric)
200 debugmsg("numeric constructor from long/long",LOGLEVEL_CONSTRUCT);
202 throw (std::overflow_error("division by zero"));
203 value = new ::cl_I(numer);
204 *value = *value / ::cl_I(denom);
206 setflag(status_flags::evaluated|
207 status_flags::hash_calculated);
211 numeric::numeric(double d) : basic(TINFO_numeric)
213 debugmsg("numeric constructor from double",LOGLEVEL_CONSTRUCT);
214 // We really want to explicitly use the type cl_LF instead of the
215 // more general cl_F, since that would give us a cl_DF only which
216 // will not be promoted to cl_LF if overflow occurs:
218 *value = cl_float(d, cl_default_float_format);
220 setflag(status_flags::evaluated|
221 status_flags::hash_calculated);
225 /** ctor from C-style string. It also accepts complex numbers in GiNaC
226 * notation like "2+5*I". */
227 numeric::numeric(const char *s) : basic(TINFO_numeric)
229 debugmsg("numeric constructor from string",LOGLEVEL_CONSTRUCT);
230 value = new ::cl_N(0);
231 // parse complex numbers (functional but not completely safe, unfortunately
232 // std::string does not understand regexpese):
233 // ss should represent a simple sum like 2+5*I
235 // make it safe by adding explicit sign
236 if (ss.at(0) != '+' && ss.at(0) != '-')
238 std::string::size_type delim;
240 // chop ss into terms from left to right
242 bool imaginary = false;
243 delim = ss.find_first_of(std::string("+-"),1);
244 // Do we have an exponent marker like "31.415E-1"? If so, hop on!
245 if (delim != std::string::npos &&
246 ss.at(delim-1) == 'E')
247 delim = ss.find_first_of(std::string("+-"),delim+1);
248 term = ss.substr(0,delim);
249 if (delim != std::string::npos)
250 ss = ss.substr(delim);
251 // is the term imaginary?
252 if (term.find("I") != std::string::npos) {
254 term = term.replace(term.find("I"),1,"");
256 if (term.find("*") != std::string::npos)
257 term = term.replace(term.find("*"),1,"");
258 // correct for trivial +/-I without explicit factor on I:
259 if (term.size() == 1)
263 const char *cs = term.c_str();
264 // CLN's short types are not useful within the GiNaC framework, hence
265 // we go straight to the construction of a long float. Simply using
266 // cl_N(s) would require us to use add a CLN exponent mark, otherwise
267 // we would not be save from over-/underflows.
270 *value = *value + ::complex(cl_I(0),::cl_LF(cs));
272 *value = *value + ::cl_LF(cs);
275 *value = *value + ::complex(cl_I(0),::cl_R(cs));
277 *value = *value + ::cl_R(cs);
278 } while(delim != std::string::npos);
280 setflag(status_flags::evaluated|
281 status_flags::hash_calculated);
284 /** Ctor from CLN types. This is for the initiated user or internal use
286 numeric::numeric(const cl_N & z) : basic(TINFO_numeric)
288 debugmsg("numeric constructor from cl_N", LOGLEVEL_CONSTRUCT);
289 value = new ::cl_N(z);
291 setflag(status_flags::evaluated|
292 status_flags::hash_calculated);
299 /** Construct object from archive_node. */
300 numeric::numeric(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
302 debugmsg("numeric constructor from archive_node", LOGLEVEL_CONSTRUCT);
305 // Read number as string
307 if (n.find_string("number", str)) {
309 std::istringstream s(str);
311 std::istrstream s(str.c_str(), str.size() + 1);
313 ::cl_idecoded_float re, im;
317 case 'R': // Integer-decoded real number
318 s >> re.sign >> re.mantissa >> re.exponent;
319 *value = re.sign * re.mantissa * ::expt(cl_float(2.0, cl_default_float_format), re.exponent);
321 case 'C': // Integer-decoded complex number
322 s >> re.sign >> re.mantissa >> re.exponent;
323 s >> im.sign >> im.mantissa >> im.exponent;
324 *value = ::complex(re.sign * re.mantissa * ::expt(cl_float(2.0, cl_default_float_format), re.exponent),
325 im.sign * im.mantissa * ::expt(cl_float(2.0, cl_default_float_format), im.exponent));
327 default: // Ordinary number
334 setflag(status_flags::evaluated|
335 status_flags::hash_calculated);
338 /** Unarchive the object. */
339 ex numeric::unarchive(const archive_node &n, const lst &sym_lst)
341 return (new numeric(n, sym_lst))->setflag(status_flags::dynallocated);
344 /** Archive the object. */
345 void numeric::archive(archive_node &n) const
347 inherited::archive(n);
349 // Write number as string
351 std::ostringstream s;
354 std::ostrstream s(buf, 1024);
356 if (this->is_crational())
359 // Non-rational numbers are written in an integer-decoded format
360 // to preserve the precision
361 if (this->is_real()) {
362 cl_idecoded_float re = integer_decode_float(The(::cl_F)(*value));
364 s << re.sign << " " << re.mantissa << " " << re.exponent;
366 cl_idecoded_float re = integer_decode_float(The(::cl_F)(::realpart(*value)));
367 cl_idecoded_float im = integer_decode_float(The(::cl_F)(::imagpart(*value)));
369 s << re.sign << " " << re.mantissa << " " << re.exponent << " ";
370 s << im.sign << " " << im.mantissa << " " << im.exponent;
374 n.add_string("number", s.str());
377 std::string str(buf);
378 n.add_string("number", str);
383 // functions overriding virtual functions from bases classes
388 basic * numeric::duplicate() const
390 debugmsg("numeric duplicate", LOGLEVEL_DUPLICATE);
391 return new numeric(*this);
395 /** Helper function to print a real number in a nicer way than is CLN's
396 * default. Instead of printing 42.0L0 this just prints 42.0 to ostream os
397 * and instead of 3.99168L7 it prints 3.99168E7. This is fine in GiNaC as
398 * long as it only uses cl_LF and no other floating point types.
400 * @see numeric::print() */
401 static void print_real_number(ostream & os, const cl_R & num)
403 cl_print_flags ourflags;
404 if (::instanceof(num, ::cl_RA_ring)) {
405 // case 1: integer or rational, nothing special to do:
406 ::print_real(os, ourflags, num);
409 // make CLN believe this number has default_float_format, so it prints
410 // 'E' as exponent marker instead of 'L':
411 ourflags.default_float_format = ::cl_float_format(The(::cl_F)(num));
412 ::print_real(os, ourflags, num);
417 /** This method adds to the output so it blends more consistently together
418 * with the other routines and produces something compatible to ginsh input.
420 * @see print_real_number() */
421 void numeric::print(ostream & os, unsigned upper_precedence) const
423 debugmsg("numeric print", LOGLEVEL_PRINT);
424 if (this->is_real()) {
425 // case 1, real: x or -x
426 if ((precedence<=upper_precedence) && (!this->is_nonneg_integer())) {
428 print_real_number(os, The(::cl_R)(*value));
431 print_real_number(os, The(::cl_R)(*value));
434 // case 2, imaginary: y*I or -y*I
435 if (::realpart(*value) == 0) {
436 if ((precedence<=upper_precedence) && (::imagpart(*value) < 0)) {
437 if (::imagpart(*value) == -1) {
441 print_real_number(os, The(::cl_R)(::imagpart(*value)));
445 if (::imagpart(*value) == 1) {
448 if (::imagpart (*value) == -1) {
451 print_real_number(os, The(::cl_R)(::imagpart(*value)));
457 // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I
458 if (precedence <= upper_precedence)
460 print_real_number(os, The(::cl_R)(::realpart(*value)));
461 if (::imagpart(*value) < 0) {
462 if (::imagpart(*value) == -1) {
465 print_real_number(os, The(::cl_R)(::imagpart(*value)));
469 if (::imagpart(*value) == 1) {
473 print_real_number(os, The(::cl_R)(::imagpart(*value)));
477 if (precedence <= upper_precedence)
484 void numeric::printraw(ostream & os) const
486 // The method printraw doesn't do much, it simply uses CLN's operator<<()
487 // for output, which is ugly but reliable. e.g: 2+2i
488 debugmsg("numeric printraw", LOGLEVEL_PRINT);
489 os << "numeric(" << *value << ")";
493 void numeric::printtree(ostream & os, unsigned indent) const
495 debugmsg("numeric printtree", LOGLEVEL_PRINT);
496 os << std::string(indent,' ') << *value
498 << "hash=" << hashvalue << " (0x" << hex << hashvalue << dec << ")"
499 << ", flags=" << flags << endl;
503 void numeric::printcsrc(ostream & os, unsigned type, unsigned upper_precedence) const
505 debugmsg("numeric print csrc", LOGLEVEL_PRINT);
506 ios::fmtflags oldflags = os.flags();
507 os.setf(ios::scientific);
508 if (this->is_rational() && !this->is_integer()) {
509 if (compare(_num0()) > 0) {
511 if (type == csrc_types::ctype_cl_N)
512 os << "cl_F(\"" << numer().evalf() << "\")";
514 os << numer().to_double();
517 if (type == csrc_types::ctype_cl_N)
518 os << "cl_F(\"" << -numer().evalf() << "\")";
520 os << -numer().to_double();
523 if (type == csrc_types::ctype_cl_N)
524 os << "cl_F(\"" << denom().evalf() << "\")";
526 os << denom().to_double();
529 if (type == csrc_types::ctype_cl_N)
530 os << "cl_F(\"" << evalf() << "\")";
538 bool numeric::info(unsigned inf) const
541 case info_flags::numeric:
542 case info_flags::polynomial:
543 case info_flags::rational_function:
545 case info_flags::real:
547 case info_flags::rational:
548 case info_flags::rational_polynomial:
549 return is_rational();
550 case info_flags::crational:
551 case info_flags::crational_polynomial:
552 return is_crational();
553 case info_flags::integer:
554 case info_flags::integer_polynomial:
556 case info_flags::cinteger:
557 case info_flags::cinteger_polynomial:
558 return is_cinteger();
559 case info_flags::positive:
560 return is_positive();
561 case info_flags::negative:
562 return is_negative();
563 case info_flags::nonnegative:
564 return !is_negative();
565 case info_flags::posint:
566 return is_pos_integer();
567 case info_flags::negint:
568 return is_integer() && is_negative();
569 case info_flags::nonnegint:
570 return is_nonneg_integer();
571 case info_flags::even:
573 case info_flags::odd:
575 case info_flags::prime:
577 case info_flags::algebraic:
583 /** Disassemble real part and imaginary part to scan for the occurrence of a
584 * single number. Also handles the imaginary unit. It ignores the sign on
585 * both this and the argument, which may lead to what might appear as funny
586 * results: (2+I).has(-2) -> true. But this is consistent, since we also
587 * would like to have (-2+I).has(2) -> true and we want to think about the
588 * sign as a multiplicative factor. */
589 bool numeric::has(const ex & other) const
591 if (!is_exactly_of_type(*other.bp, numeric))
593 const numeric & o = static_cast<numeric &>(const_cast<basic &>(*other.bp));
594 if (this->is_equal(o) || this->is_equal(-o))
596 if (o.imag().is_zero()) // e.g. scan for 3 in -3*I
597 return (this->real().is_equal(o) || this->imag().is_equal(o) ||
598 this->real().is_equal(-o) || this->imag().is_equal(-o));
600 if (o.is_equal(I)) // e.g scan for I in 42*I
601 return !this->is_real();
602 if (o.real().is_zero()) // e.g. scan for 2*I in 2*I+1
603 return (this->real().has(o*I) || this->imag().has(o*I) ||
604 this->real().has(-o*I) || this->imag().has(-o*I));
610 /** Evaluation of numbers doesn't do anything at all. */
611 ex numeric::eval(int level) const
613 // Warning: if this is ever gonna do something, the ex ctors from all kinds
614 // of numbers should be checking for status_flags::evaluated.
619 /** Cast numeric into a floating-point object. For example exact numeric(1) is
620 * returned as a 1.0000000000000000000000 and so on according to how Digits is
623 * @param level ignored, but needed for overriding basic::evalf.
624 * @return an ex-handle to a numeric. */
625 ex numeric::evalf(int level) const
627 // level can safely be discarded for numeric objects.
628 return numeric(::cl_float(1.0, ::cl_default_float_format) * (*value)); // -> CLN
633 /** Implementation of ex::diff() for a numeric. It always returns 0.
636 ex numeric::derivative(const symbol & s) const
642 int numeric::compare_same_type(const basic & other) const
644 GINAC_ASSERT(is_exactly_of_type(other, numeric));
645 const numeric & o = static_cast<numeric &>(const_cast<basic &>(other));
647 if (*value == *o.value) {
655 bool numeric::is_equal_same_type(const basic & other) const
657 GINAC_ASSERT(is_exactly_of_type(other,numeric));
658 const numeric *o = static_cast<const numeric *>(&other);
660 return this->is_equal(*o);
664 unsigned numeric::calchash(void) const
666 // Use CLN's hashcode. Warning: It depends only on the number's value, not
667 // its type or precision (i.e. a true equivalence relation on numbers). As
668 // a consequence, 3 and 3.0 share the same hashvalue.
669 return (hashvalue = cl_equal_hashcode(*value) | 0x80000000U);
674 // new virtual functions which can be overridden by derived classes
680 // non-virtual functions in this class
685 /** Numerical addition method. Adds argument to *this and returns result as
686 * a new numeric object. */
687 numeric numeric::add(const numeric & other) const
689 return numeric((*value)+(*other.value));
692 /** Numerical subtraction method. Subtracts argument from *this and returns
693 * result as a new numeric object. */
694 numeric numeric::sub(const numeric & other) const
696 return numeric((*value)-(*other.value));
699 /** Numerical multiplication method. Multiplies *this and argument and returns
700 * result as a new numeric object. */
701 numeric numeric::mul(const numeric & other) const
703 static const numeric * _num1p=&_num1();
706 } else if (&other==_num1p) {
709 return numeric((*value)*(*other.value));
712 /** Numerical division method. Divides *this by argument and returns result as
713 * a new numeric object.
715 * @exception overflow_error (division by zero) */
716 numeric numeric::div(const numeric & other) const
718 if (::zerop(*other.value))
719 throw (std::overflow_error("division by zero"));
720 return numeric((*value)/(*other.value));
723 numeric numeric::power(const numeric & other) const
725 static const numeric * _num1p = &_num1();
728 if (::zerop(*value)) {
729 if (::zerop(*other.value))
730 throw (std::domain_error("numeric::eval(): pow(0,0) is undefined"));
731 else if (::zerop(::realpart(*other.value)))
732 throw (std::domain_error("numeric::eval(): pow(0,I) is undefined"));
733 else if (::minusp(::realpart(*other.value)))
734 throw (std::overflow_error("numeric::eval(): division by zero"));
738 return numeric(::expt(*value,*other.value));
741 /** Inverse of a number. */
742 numeric numeric::inverse(void) const
744 return numeric(::recip(*value)); // -> CLN
747 const numeric & numeric::add_dyn(const numeric & other) const
749 return static_cast<const numeric &>((new numeric((*value)+(*other.value)))->
750 setflag(status_flags::dynallocated));
753 const numeric & numeric::sub_dyn(const numeric & other) const
755 return static_cast<const numeric &>((new numeric((*value)-(*other.value)))->
756 setflag(status_flags::dynallocated));
759 const numeric & numeric::mul_dyn(const numeric & other) const
761 static const numeric * _num1p=&_num1();
764 } else if (&other==_num1p) {
767 return static_cast<const numeric &>((new numeric((*value)*(*other.value)))->
768 setflag(status_flags::dynallocated));
771 const numeric & numeric::div_dyn(const numeric & other) const
773 if (::zerop(*other.value))
774 throw (std::overflow_error("division by zero"));
775 return static_cast<const numeric &>((new numeric((*value)/(*other.value)))->
776 setflag(status_flags::dynallocated));
779 const numeric & numeric::power_dyn(const numeric & other) const
781 static const numeric * _num1p=&_num1();
784 if (::zerop(*value)) {
785 if (::zerop(*other.value))
786 throw (std::domain_error("numeric::eval(): pow(0,0) is undefined"));
787 else if (::zerop(::realpart(*other.value)))
788 throw (std::domain_error("numeric::eval(): pow(0,I) is undefined"));
789 else if (::minusp(::realpart(*other.value)))
790 throw (std::overflow_error("numeric::eval(): division by zero"));
794 return static_cast<const numeric &>((new numeric(::expt(*value,*other.value)))->
795 setflag(status_flags::dynallocated));
798 const numeric & numeric::operator=(int i)
800 return operator=(numeric(i));
803 const numeric & numeric::operator=(unsigned int i)
805 return operator=(numeric(i));
808 const numeric & numeric::operator=(long i)
810 return operator=(numeric(i));
813 const numeric & numeric::operator=(unsigned long i)
815 return operator=(numeric(i));
818 const numeric & numeric::operator=(double d)
820 return operator=(numeric(d));
823 const numeric & numeric::operator=(const char * s)
825 return operator=(numeric(s));
828 /** Return the complex half-plane (left or right) in which the number lies.
829 * csgn(x)==0 for x==0, csgn(x)==1 for Re(x)>0 or Re(x)=0 and Im(x)>0,
830 * csgn(x)==-1 for Re(x)<0 or Re(x)=0 and Im(x)<0.
832 * @see numeric::compare(const numeric & other) */
833 int numeric::csgn(void) const
837 if (!::zerop(::realpart(*value))) {
838 if (::plusp(::realpart(*value)))
843 if (::plusp(::imagpart(*value)))
850 /** This method establishes a canonical order on all numbers. For complex
851 * numbers this is not possible in a mathematically consistent way but we need
852 * to establish some order and it ought to be fast. So we simply define it
853 * to be compatible with our method csgn.
855 * @return csgn(*this-other)
856 * @see numeric::csgn(void) */
857 int numeric::compare(const numeric & other) const
859 // Comparing two real numbers?
860 if (this->is_real() && other.is_real())
861 // Yes, just compare them
862 return ::cl_compare(The(::cl_R)(*value), The(::cl_R)(*other.value));
864 // No, first compare real parts
865 cl_signean real_cmp = ::cl_compare(::realpart(*value), ::realpart(*other.value));
869 return ::cl_compare(::imagpart(*value), ::imagpart(*other.value));
873 bool numeric::is_equal(const numeric & other) const
875 return (*value == *other.value);
878 /** True if object is zero. */
879 bool numeric::is_zero(void) const
881 return ::zerop(*value); // -> CLN
884 /** True if object is not complex and greater than zero. */
885 bool numeric::is_positive(void) const
888 return ::plusp(The(::cl_R)(*value)); // -> CLN
892 /** True if object is not complex and less than zero. */
893 bool numeric::is_negative(void) const
896 return ::minusp(The(::cl_R)(*value)); // -> CLN
900 /** True if object is a non-complex integer. */
901 bool numeric::is_integer(void) const
903 return ::instanceof(*value, ::cl_I_ring); // -> CLN
906 /** True if object is an exact integer greater than zero. */
907 bool numeric::is_pos_integer(void) const
909 return (this->is_integer() && ::plusp(The(::cl_I)(*value))); // -> CLN
912 /** True if object is an exact integer greater or equal zero. */
913 bool numeric::is_nonneg_integer(void) const
915 return (this->is_integer() && !::minusp(The(::cl_I)(*value))); // -> CLN
918 /** True if object is an exact even integer. */
919 bool numeric::is_even(void) const
921 return (this->is_integer() && ::evenp(The(::cl_I)(*value))); // -> CLN
924 /** True if object is an exact odd integer. */
925 bool numeric::is_odd(void) const
927 return (this->is_integer() && ::oddp(The(::cl_I)(*value))); // -> CLN
930 /** Probabilistic primality test.
932 * @return true if object is exact integer and prime. */
933 bool numeric::is_prime(void) const
935 return (this->is_integer() && ::isprobprime(The(::cl_I)(*value))); // -> CLN
938 /** True if object is an exact rational number, may even be complex
939 * (denominator may be unity). */
940 bool numeric::is_rational(void) const
942 return ::instanceof(*value, ::cl_RA_ring); // -> CLN
945 /** True if object is a real integer, rational or float (but not complex). */
946 bool numeric::is_real(void) const
948 return ::instanceof(*value, ::cl_R_ring); // -> CLN
951 bool numeric::operator==(const numeric & other) const
953 return (*value == *other.value); // -> CLN
956 bool numeric::operator!=(const numeric & other) const
958 return (*value != *other.value); // -> CLN
961 /** True if object is element of the domain of integers extended by I, i.e. is
962 * of the form a+b*I, where a and b are integers. */
963 bool numeric::is_cinteger(void) const
965 if (::instanceof(*value, ::cl_I_ring))
967 else if (!this->is_real()) { // complex case, handle n+m*I
968 if (::instanceof(::realpart(*value), ::cl_I_ring) &&
969 ::instanceof(::imagpart(*value), ::cl_I_ring))
975 /** True if object is an exact rational number, may even be complex
976 * (denominator may be unity). */
977 bool numeric::is_crational(void) const
979 if (::instanceof(*value, ::cl_RA_ring))
981 else if (!this->is_real()) { // complex case, handle Q(i):
982 if (::instanceof(::realpart(*value), ::cl_RA_ring) &&
983 ::instanceof(::imagpart(*value), ::cl_RA_ring))
989 /** Numerical comparison: less.
991 * @exception invalid_argument (complex inequality) */
992 bool numeric::operator<(const numeric & other) const
994 if (this->is_real() && other.is_real())
995 return (The(::cl_R)(*value) < The(::cl_R)(*other.value)); // -> CLN
996 throw (std::invalid_argument("numeric::operator<(): complex inequality"));
997 return false; // make compiler shut up
1000 /** Numerical comparison: less or equal.
1002 * @exception invalid_argument (complex inequality) */
1003 bool numeric::operator<=(const numeric & other) const
1005 if (this->is_real() && other.is_real())
1006 return (The(::cl_R)(*value) <= The(::cl_R)(*other.value)); // -> CLN
1007 throw (std::invalid_argument("numeric::operator<=(): complex inequality"));
1008 return false; // make compiler shut up
1011 /** Numerical comparison: greater.
1013 * @exception invalid_argument (complex inequality) */
1014 bool numeric::operator>(const numeric & other) const
1016 if (this->is_real() && other.is_real())
1017 return (The(::cl_R)(*value) > The(::cl_R)(*other.value)); // -> CLN
1018 throw (std::invalid_argument("numeric::operator>(): complex inequality"));
1019 return false; // make compiler shut up
1022 /** Numerical comparison: greater or equal.
1024 * @exception invalid_argument (complex inequality) */
1025 bool numeric::operator>=(const numeric & other) const
1027 if (this->is_real() && other.is_real())
1028 return (The(::cl_R)(*value) >= The(::cl_R)(*other.value)); // -> CLN
1029 throw (std::invalid_argument("numeric::operator>=(): complex inequality"));
1030 return false; // make compiler shut up
1033 /** Converts numeric types to machine's int. You should check with
1034 * is_integer() if the number is really an integer before calling this method.
1035 * You may also consider checking the range first. */
1036 int numeric::to_int(void) const
1038 GINAC_ASSERT(this->is_integer());
1039 return ::cl_I_to_int(The(::cl_I)(*value)); // -> CLN
1042 /** Converts numeric types to machine's long. You should check with
1043 * is_integer() if the number is really an integer before calling this method.
1044 * You may also consider checking the range first. */
1045 long numeric::to_long(void) const
1047 GINAC_ASSERT(this->is_integer());
1048 return ::cl_I_to_long(The(::cl_I)(*value)); // -> CLN
1051 /** Converts numeric types to machine's double. You should check with is_real()
1052 * if the number is really not complex before calling this method. */
1053 double numeric::to_double(void) const
1055 GINAC_ASSERT(this->is_real());
1056 return ::cl_double_approx(::realpart(*value)); // -> CLN
1059 /** Real part of a number. */
1060 const numeric numeric::real(void) const
1062 return numeric(::realpart(*value)); // -> CLN
1065 /** Imaginary part of a number. */
1066 const numeric numeric::imag(void) const
1068 return numeric(::imagpart(*value)); // -> CLN
1072 // Unfortunately, CLN did not provide an official way to access the numerator
1073 // or denominator of a rational number (cl_RA). Doing some excavations in CLN
1074 // one finds how it works internally in src/rational/cl_RA.h:
1075 struct cl_heap_ratio : cl_heap {
1080 inline cl_heap_ratio* TheRatio (const cl_N& obj)
1081 { return (cl_heap_ratio*)(obj.pointer); }
1082 #endif // ndef SANE_LINKER
1084 /** Numerator. Computes the numerator of rational numbers, rationalized
1085 * numerator of complex if real and imaginary part are both rational numbers
1086 * (i.e numer(4/3+5/6*I) == 8+5*I), the number carrying the sign in all other
1088 const numeric numeric::numer(void) const
1090 if (this->is_integer()) {
1091 return numeric(*this);
1094 else if (::instanceof(*value, ::cl_RA_ring)) {
1095 return numeric(::numerator(The(::cl_RA)(*value)));
1097 else if (!this->is_real()) { // complex case, handle Q(i):
1098 cl_R r = ::realpart(*value);
1099 cl_R i = ::imagpart(*value);
1100 if (::instanceof(r, ::cl_I_ring) && ::instanceof(i, ::cl_I_ring))
1101 return numeric(*this);
1102 if (::instanceof(r, ::cl_I_ring) && ::instanceof(i, ::cl_RA_ring))
1103 return numeric(::complex(r*::denominator(The(::cl_RA)(i)), ::numerator(The(::cl_RA)(i))));
1104 if (::instanceof(r, ::cl_RA_ring) && ::instanceof(i, ::cl_I_ring))
1105 return numeric(::complex(::numerator(The(::cl_RA)(r)), i*::denominator(The(::cl_RA)(r))));
1106 if (::instanceof(r, ::cl_RA_ring) && ::instanceof(i, ::cl_RA_ring)) {
1107 cl_I s = ::lcm(::denominator(The(::cl_RA)(r)), ::denominator(The(::cl_RA)(i)));
1108 return numeric(::complex(::numerator(The(::cl_RA)(r))*(exquo(s,::denominator(The(::cl_RA)(r)))),
1109 ::numerator(The(::cl_RA)(i))*(exquo(s,::denominator(The(::cl_RA)(i))))));
1113 else if (instanceof(*value, ::cl_RA_ring)) {
1114 return numeric(TheRatio(*value)->numerator);
1116 else if (!this->is_real()) { // complex case, handle Q(i):
1117 cl_R r = ::realpart(*value);
1118 cl_R i = ::imagpart(*value);
1119 if (instanceof(r, ::cl_I_ring) && instanceof(i, ::cl_I_ring))
1120 return numeric(*this);
1121 if (instanceof(r, ::cl_I_ring) && instanceof(i, ::cl_RA_ring))
1122 return numeric(::complex(r*TheRatio(i)->denominator, TheRatio(i)->numerator));
1123 if (instanceof(r, ::cl_RA_ring) && instanceof(i, ::cl_I_ring))
1124 return numeric(::complex(TheRatio(r)->numerator, i*TheRatio(r)->denominator));
1125 if (instanceof(r, ::cl_RA_ring) && instanceof(i, ::cl_RA_ring)) {
1126 cl_I s = ::lcm(TheRatio(r)->denominator, TheRatio(i)->denominator);
1127 return numeric(::complex(TheRatio(r)->numerator*(exquo(s,TheRatio(r)->denominator)),
1128 TheRatio(i)->numerator*(exquo(s,TheRatio(i)->denominator))));
1131 #endif // def SANE_LINKER
1132 // at least one float encountered
1133 return numeric(*this);
1136 /** Denominator. Computes the denominator of rational numbers, common integer
1137 * denominator of complex if real and imaginary part are both rational numbers
1138 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
1139 const numeric numeric::denom(void) const
1141 if (this->is_integer()) {
1145 if (instanceof(*value, ::cl_RA_ring)) {
1146 return numeric(::denominator(The(::cl_RA)(*value)));
1148 if (!this->is_real()) { // complex case, handle Q(i):
1149 cl_R r = ::realpart(*value);
1150 cl_R i = ::imagpart(*value);
1151 if (::instanceof(r, ::cl_I_ring) && ::instanceof(i, ::cl_I_ring))
1153 if (::instanceof(r, ::cl_I_ring) && ::instanceof(i, ::cl_RA_ring))
1154 return numeric(::denominator(The(::cl_RA)(i)));
1155 if (::instanceof(r, ::cl_RA_ring) && ::instanceof(i, ::cl_I_ring))
1156 return numeric(::denominator(The(::cl_RA)(r)));
1157 if (::instanceof(r, ::cl_RA_ring) && ::instanceof(i, ::cl_RA_ring))
1158 return numeric(::lcm(::denominator(The(::cl_RA)(r)), ::denominator(The(::cl_RA)(i))));
1161 if (instanceof(*value, ::cl_RA_ring)) {
1162 return numeric(TheRatio(*value)->denominator);
1164 if (!this->is_real()) { // complex case, handle Q(i):
1165 cl_R r = ::realpart(*value);
1166 cl_R i = ::imagpart(*value);
1167 if (instanceof(r, ::cl_I_ring) && instanceof(i, ::cl_I_ring))
1169 if (instanceof(r, ::cl_I_ring) && instanceof(i, ::cl_RA_ring))
1170 return numeric(TheRatio(i)->denominator);
1171 if (instanceof(r, ::cl_RA_ring) && instanceof(i, ::cl_I_ring))
1172 return numeric(TheRatio(r)->denominator);
1173 if (instanceof(r, ::cl_RA_ring) && instanceof(i, ::cl_RA_ring))
1174 return numeric(::lcm(TheRatio(r)->denominator, TheRatio(i)->denominator));
1176 #endif // def SANE_LINKER
1177 // at least one float encountered
1181 /** Size in binary notation. For integers, this is the smallest n >= 0 such
1182 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
1183 * 2^(n-1) <= x < 2^n.
1185 * @return number of bits (excluding sign) needed to represent that number
1186 * in two's complement if it is an integer, 0 otherwise. */
1187 int numeric::int_length(void) const
1189 if (this->is_integer())
1190 return ::integer_length(The(::cl_I)(*value)); // -> CLN
1197 // static member variables
1202 unsigned numeric::precedence = 30;
1208 const numeric some_numeric;
1209 const type_info & typeid_numeric=typeid(some_numeric);
1210 /** Imaginary unit. This is not a constant but a numeric since we are
1211 * natively handing complex numbers anyways. */
1212 const numeric I = numeric(::complex(cl_I(0),cl_I(1)));
1215 /** Exponential function.
1217 * @return arbitrary precision numerical exp(x). */
1218 const numeric exp(const numeric & x)
1220 return ::exp(*x.value); // -> CLN
1224 /** Natural logarithm.
1226 * @param z complex number
1227 * @return arbitrary precision numerical log(x).
1228 * @exception overflow_error (logarithmic singularity) */
1229 const numeric log(const numeric & z)
1232 throw (std::overflow_error("log(): logarithmic singularity"));
1233 return ::log(*z.value); // -> CLN
1237 /** Numeric sine (trigonometric function).
1239 * @return arbitrary precision numerical sin(x). */
1240 const numeric sin(const numeric & x)
1242 return ::sin(*x.value); // -> CLN
1246 /** Numeric cosine (trigonometric function).
1248 * @return arbitrary precision numerical cos(x). */
1249 const numeric cos(const numeric & x)
1251 return ::cos(*x.value); // -> CLN
1255 /** Numeric tangent (trigonometric function).
1257 * @return arbitrary precision numerical tan(x). */
1258 const numeric tan(const numeric & x)
1260 return ::tan(*x.value); // -> CLN
1264 /** Numeric inverse sine (trigonometric function).
1266 * @return arbitrary precision numerical asin(x). */
1267 const numeric asin(const numeric & x)
1269 return ::asin(*x.value); // -> CLN
1273 /** Numeric inverse cosine (trigonometric function).
1275 * @return arbitrary precision numerical acos(x). */
1276 const numeric acos(const numeric & x)
1278 return ::acos(*x.value); // -> CLN
1284 * @param z complex number
1286 * @exception overflow_error (logarithmic singularity) */
1287 const numeric atan(const numeric & x)
1290 x.real().is_zero() &&
1291 !abs(x.imag()).is_equal(_num1()))
1292 throw (std::overflow_error("atan(): logarithmic singularity"));
1293 return ::atan(*x.value); // -> CLN
1299 * @param x real number
1300 * @param y real number
1301 * @return atan(y/x) */
1302 const numeric atan(const numeric & y, const numeric & x)
1304 if (x.is_real() && y.is_real())
1305 return ::atan(::realpart(*x.value), ::realpart(*y.value)); // -> CLN
1307 throw (std::invalid_argument("numeric::atan(): complex argument"));
1311 /** Numeric hyperbolic sine (trigonometric function).
1313 * @return arbitrary precision numerical sinh(x). */
1314 const numeric sinh(const numeric & x)
1316 return ::sinh(*x.value); // -> CLN
1320 /** Numeric hyperbolic cosine (trigonometric function).
1322 * @return arbitrary precision numerical cosh(x). */
1323 const numeric cosh(const numeric & x)
1325 return ::cosh(*x.value); // -> CLN
1329 /** Numeric hyperbolic tangent (trigonometric function).
1331 * @return arbitrary precision numerical tanh(x). */
1332 const numeric tanh(const numeric & x)
1334 return ::tanh(*x.value); // -> CLN
1338 /** Numeric inverse hyperbolic sine (trigonometric function).
1340 * @return arbitrary precision numerical asinh(x). */
1341 const numeric asinh(const numeric & x)
1343 return ::asinh(*x.value); // -> CLN
1347 /** Numeric inverse hyperbolic cosine (trigonometric function).
1349 * @return arbitrary precision numerical acosh(x). */
1350 const numeric acosh(const numeric & x)
1352 return ::acosh(*x.value); // -> CLN
1356 /** Numeric inverse hyperbolic tangent (trigonometric function).
1358 * @return arbitrary precision numerical atanh(x). */
1359 const numeric atanh(const numeric & x)
1361 return ::atanh(*x.value); // -> CLN
1365 /** Numeric evaluation of Riemann's Zeta function. Currently works only for
1366 * integer arguments. */
1367 const numeric zeta(const numeric & x)
1369 // A dirty hack to allow for things like zeta(3.0), since CLN currently
1370 // only knows about integer arguments and zeta(3).evalf() automatically
1371 // cascades down to zeta(3.0).evalf(). The trick is to rely on 3.0-3
1372 // being an exact zero for CLN, which can be tested and then we can just
1373 // pass the number casted to an int:
1375 int aux = (int)(::cl_double_approx(::realpart(*x.value)));
1376 if (zerop(*x.value-aux))
1377 return ::cl_zeta(aux); // -> CLN
1379 clog << "zeta(" << x
1380 << "): Does anybody know good way to calculate this numerically?"
1386 /** The Gamma function.
1387 * This is only a stub! */
1388 const numeric lgamma(const numeric & x)
1390 clog << "lgamma(" << x
1391 << "): Does anybody know good way to calculate this numerically?"
1395 const numeric tgamma(const numeric & x)
1397 clog << "tgamma(" << x
1398 << "): Does anybody know good way to calculate this numerically?"
1404 /** The psi function (aka polygamma function).
1405 * This is only a stub! */
1406 const numeric psi(const numeric & x)
1409 << "): Does anybody know good way to calculate this numerically?"
1415 /** The psi functions (aka polygamma functions).
1416 * This is only a stub! */
1417 const numeric psi(const numeric & n, const numeric & x)
1419 clog << "psi(" << n << "," << x
1420 << "): Does anybody know good way to calculate this numerically?"
1426 /** Factorial combinatorial function.
1428 * @param n integer argument >= 0
1429 * @exception range_error (argument must be integer >= 0) */
1430 const numeric factorial(const numeric & n)
1432 if (!n.is_nonneg_integer())
1433 throw (std::range_error("numeric::factorial(): argument must be integer >= 0"));
1434 return numeric(::factorial(n.to_int())); // -> CLN
1438 /** The double factorial combinatorial function. (Scarcely used, but still
1439 * useful in cases, like for exact results of tgamma(n+1/2) for instance.)
1441 * @param n integer argument >= -1
1442 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == (-1)!! == 1
1443 * @exception range_error (argument must be integer >= -1) */
1444 const numeric doublefactorial(const numeric & n)
1446 if (n == numeric(-1)) {
1449 if (!n.is_nonneg_integer()) {
1450 throw (std::range_error("numeric::doublefactorial(): argument must be integer >= -1"));
1452 return numeric(::doublefactorial(n.to_int())); // -> CLN
1456 /** The Binomial coefficients. It computes the binomial coefficients. For
1457 * integer n and k and positive n this is the number of ways of choosing k
1458 * objects from n distinct objects. If n is negative, the formula
1459 * binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */
1460 const numeric binomial(const numeric & n, const numeric & k)
1462 if (n.is_integer() && k.is_integer()) {
1463 if (n.is_nonneg_integer()) {
1464 if (k.compare(n)!=1 && k.compare(_num0())!=-1)
1465 return numeric(::binomial(n.to_int(),k.to_int())); // -> CLN
1469 return _num_1().power(k)*binomial(k-n-_num1(),k);
1473 // should really be gamma(n+1)/gamma(r+1)/gamma(n-r+1) or a suitable limit
1474 throw (std::range_error("numeric::binomial(): don´t know how to evaluate that."));
1478 /** Bernoulli number. The nth Bernoulli number is the coefficient of x^n/n!
1479 * in the expansion of the function x/(e^x-1).
1481 * @return the nth Bernoulli number (a rational number).
1482 * @exception range_error (argument must be integer >= 0) */
1483 const numeric bernoulli(const numeric & nn)
1485 if (!nn.is_integer() || nn.is_negative())
1486 throw (std::range_error("numeric::bernoulli(): argument must be integer >= 0"));
1490 // The Bernoulli numbers are rational numbers that may be computed using
1493 // B_n = - 1/(n+1) * sum_{k=0}^{n-1}(binomial(n+1,k)*B_k) (1)
1495 // with B(0) = 1. Since the n'th Bernoulli number depends on all the
1496 // previous ones, the computation is necessarily very expensive.
1497 // We can do better by computing the tangent numbers, sometimes called
1498 // zag numbers. They are integers which speeds up computation
1499 // considerably. Their relation to the Bernoulli numbers is given by
1501 // B_n == T_{n-1} * (-)^(n/2-1) * n / (4^n-2^n) (2)
1503 // for even n>=2. We can calculate the tangent numbers as the tangent
1504 // polynomials T_n(x) evaluated at x == 0. The T_n(x) satisfy the
1505 // recurrence relation
1507 // T_{n+1}(x) == (1+x^2)*T_n(x)'
1509 // with starting value T_0(x) = x, by which they will be computed. The
1510 // n'th tangent polynomial has degree n+1.
1512 // Method (2) is about 2-10 times faster than method (1) when it is
1513 // implemented in CLN's efficient univariate polynomials and not much more
1514 // memory consuming. Since any application that needs B_n is likely to
1515 // need B_k, for k<n as well, we store all results computed so far, which
1516 // gives us the same convenient runtime behaviour as method (1).
1518 // the special cases not covered by the algorithm below
1521 if (!nn.compare(_num1()))
1522 return numeric(-1,2);
1523 if (!nn.compare(_num2()))
1524 return numeric(::cl_I(1)/::cl_I(6));
1528 // let CLN set up the integer ring we are working in
1529 ::cl_univpoly_integer_ring myring = ::cl_find_univpoly_ring(::cl_I_ring);
1531 // store nonvanishing Bernoulli numbers and the last tangent poly here
1532 static vector< ::cl_RA > results;
1533 static int highest_result = 0;
1534 static ::cl_UP_I T_n = myring->create(1);
1536 // index of results vector
1537 int m = (nn.to_int()-4)/2;
1538 // look if the result is precomputed
1539 if (m < highest_result)
1540 return numeric(results[m]);
1541 // reserve the whole chunk we'll need
1542 if (results.capacity() < (unsigned)(m+1))
1543 results.reserve(m+1);
1545 // create the generating polynomial T_gen = 1+x^2
1546 ::cl_UP_I T_gen = myring->create(2);
1547 ::set_coeff(T_gen, 0, cl_I(1));
1548 ::set_coeff(T_gen, 2, cl_I(1));
1550 // T_n will be iterated, start with T_1(x) == 1+x^2 == T_gen
1551 if (highest_result==0)
1553 // iterate to the n'th tangent polynomial
1554 for (int n=highest_result; n<=m; ++n) {
1555 // recur tangent polynomial twice
1556 for (int i=0; i<2; ++i)
1557 T_n = ::deriv(T_n)*T_gen;
1559 ::cl_I T = ::coeff(T_n,0);
1560 // compute B_n from the T_{n-1}:
1561 ::cl_RA B = T * (n%2 ? ::cl_I(1) : ::cl_I(-1));
1562 B = B * 2*(n+2) / ((::cl_I(1)<<4*(n+2))-(::cl_I(1)<<2*(n+2)));
1563 results.push_back(B);
1566 return numeric(results[m]);
1570 /** Fibonacci number. The nth Fibonacci number F(n) is defined by the
1571 * recurrence formula F(n)==F(n-1)+F(n-2) with F(0)==0 and F(1)==1.
1573 * @param n an integer
1574 * @return the nth Fibonacci number F(n) (an integer number)
1575 * @exception range_error (argument must be an integer) */
1576 const numeric fibonacci(const numeric & n)
1578 if (!n.is_integer())
1579 throw (std::range_error("numeric::fibonacci(): argument must be integer"));
1582 // This is based on an implementation that can be found in CLN's example
1583 // directory. There, it is done recursively, which may be more elegant
1584 // than our non-recursive implementation that has to resort to some bit-
1585 // fiddling. This is, however, a matter of taste.
1586 // The following addition formula holds:
1588 // F(n+m) = F(m-1)*F(n) + F(m)*F(n+1) for m >= 1, n >= 0.
1590 // (Proof: For fixed m, the LHS and the RHS satisfy the same recurrence
1591 // w.r.t. n, and the initial values (n=0, n=1) agree. Hence all values
1593 // Replace m by m+1:
1594 // F(n+m+1) = F(m)*F(n) + F(m+1)*F(n+1) for m >= 0, n >= 0
1595 // Now put in m = n, to get
1596 // F(2n) = (F(n+1)-F(n))*F(n) + F(n)*F(n+1) = F(n)*(2*F(n+1) - F(n))
1597 // F(2n+1) = F(n)^2 + F(n+1)^2
1599 // F(2n+2) = F(n+1)*(2*F(n) + F(n+1))
1602 if (n.is_negative())
1604 return -fibonacci(-n);
1606 return fibonacci(-n);
1610 ::cl_I m = The(::cl_I)(*n.value) >> 1L; // floor(n/2);
1611 for (uintL bit=::integer_length(m); bit>0; --bit) {
1612 // Since a squaring is cheaper than a multiplication, better use
1613 // three squarings instead of one multiplication and two squarings.
1614 ::cl_I u2 = ::square(u);
1615 ::cl_I v2 = ::square(v);
1616 if (::logbitp(bit-1, m)) {
1617 v = ::square(u + v) - u2;
1620 u = v2 - ::square(v - u);
1625 // Here we don't use the squaring formula because one multiplication
1626 // is cheaper than two squarings.
1627 return u * ((v << 1) - u);
1629 return ::square(u) + ::square(v);
1633 /** Absolute value. */
1634 numeric abs(const numeric & x)
1636 return ::abs(*x.value); // -> CLN
1640 /** Modulus (in positive representation).
1641 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1642 * sign of a or is zero. This is different from Maple's modp, where the sign
1643 * of b is ignored. It is in agreement with Mathematica's Mod.
1645 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1646 * integer, 0 otherwise. */
1647 numeric mod(const numeric & a, const numeric & b)
1649 if (a.is_integer() && b.is_integer())
1650 return ::mod(The(::cl_I)(*a.value), The(::cl_I)(*b.value)); // -> CLN
1652 return _num0(); // Throw?
1656 /** Modulus (in symmetric representation).
1657 * Equivalent to Maple's mods.
1659 * @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1660 numeric smod(const numeric & a, const numeric & b)
1662 if (a.is_integer() && b.is_integer()) {
1663 cl_I b2 = The(::cl_I)(ceiling1(The(::cl_I)(*b.value) / 2)) - 1;
1664 return ::mod(The(::cl_I)(*a.value) + b2, The(::cl_I)(*b.value)) - b2;
1666 return _num0(); // Throw?
1670 /** Numeric integer remainder.
1671 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1672 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1673 * sign of a or is zero.
1675 * @return remainder of a/b if both are integer, 0 otherwise. */
1676 numeric irem(const numeric & a, const numeric & b)
1678 if (a.is_integer() && b.is_integer())
1679 return ::rem(The(::cl_I)(*a.value), The(::cl_I)(*b.value)); // -> CLN
1681 return _num0(); // Throw?
1685 /** Numeric integer remainder.
1686 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1687 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1688 * and irem(a,b) has the sign of a or is zero.
1690 * @return remainder of a/b and quotient stored in q if both are integer,
1692 numeric irem(const numeric & a, const numeric & b, numeric & q)
1694 if (a.is_integer() && b.is_integer()) { // -> CLN
1695 cl_I_div_t rem_quo = truncate2(The(::cl_I)(*a.value), The(::cl_I)(*b.value));
1696 q = rem_quo.quotient;
1697 return rem_quo.remainder;
1701 return _num0(); // Throw?
1706 /** Numeric integer quotient.
1707 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1709 * @return truncated quotient of a/b if both are integer, 0 otherwise. */
1710 numeric iquo(const numeric & a, const numeric & b)
1712 if (a.is_integer() && b.is_integer())
1713 return truncate1(The(::cl_I)(*a.value), The(::cl_I)(*b.value)); // -> CLN
1715 return _num0(); // Throw?
1719 /** Numeric integer quotient.
1720 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1721 * r == a - iquo(a,b,r)*b.
1723 * @return truncated quotient of a/b and remainder stored in r if both are
1724 * integer, 0 otherwise. */
1725 numeric iquo(const numeric & a, const numeric & b, numeric & r)
1727 if (a.is_integer() && b.is_integer()) { // -> CLN
1728 cl_I_div_t rem_quo = truncate2(The(::cl_I)(*a.value), The(::cl_I)(*b.value));
1729 r = rem_quo.remainder;
1730 return rem_quo.quotient;
1733 return _num0(); // Throw?
1738 /** Numeric square root.
1739 * If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4)
1740 * should return integer 2.
1742 * @param z numeric argument
1743 * @return square root of z. Branch cut along negative real axis, the negative
1744 * real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part
1745 * where imag(z)>0. */
1746 numeric sqrt(const numeric & z)
1748 return ::sqrt(*z.value); // -> CLN
1752 /** Integer numeric square root. */
1753 numeric isqrt(const numeric & x)
1755 if (x.is_integer()) {
1757 ::isqrt(The(::cl_I)(*x.value), &root); // -> CLN
1760 return _num0(); // Throw?
1764 /** Greatest Common Divisor.
1766 * @return The GCD of two numbers if both are integer, a numerical 1
1767 * if they are not. */
1768 numeric gcd(const numeric & a, const numeric & b)
1770 if (a.is_integer() && b.is_integer())
1771 return ::gcd(The(::cl_I)(*a.value), The(::cl_I)(*b.value)); // -> CLN
1777 /** Least Common Multiple.
1779 * @return The LCM of two numbers if both are integer, the product of those
1780 * two numbers if they are not. */
1781 numeric lcm(const numeric & a, const numeric & b)
1783 if (a.is_integer() && b.is_integer())
1784 return ::lcm(The(::cl_I)(*a.value), The(::cl_I)(*b.value)); // -> CLN
1786 return *a.value * *b.value;
1790 /** Floating point evaluation of Archimedes' constant Pi. */
1793 return numeric(::cl_pi(cl_default_float_format)); // -> CLN
1797 /** Floating point evaluation of Euler's constant gamma. */
1800 return numeric(::cl_eulerconst(cl_default_float_format)); // -> CLN
1804 /** Floating point evaluation of Catalan's constant. */
1805 ex CatalanEvalf(void)
1807 return numeric(::cl_catalanconst(cl_default_float_format)); // -> CLN
1811 // It initializes to 17 digits, because in CLN cl_float_format(17) turns out to
1812 // be 61 (<64) while cl_float_format(18)=65. We want to have a cl_LF instead
1813 // of cl_SF, cl_FF or cl_DF but everything else is basically arbitrary.
1814 _numeric_digits::_numeric_digits()
1819 cl_default_float_format = ::cl_float_format(17);
1823 _numeric_digits& _numeric_digits::operator=(long prec)
1826 cl_default_float_format = ::cl_float_format(prec);
1831 _numeric_digits::operator long()
1833 return (long)digits;
1837 void _numeric_digits::print(ostream & os) const
1839 debugmsg("_numeric_digits print", LOGLEVEL_PRINT);
1844 ostream& operator<<(ostream& os, const _numeric_digits & e)
1851 // static member variables
1856 bool _numeric_digits::too_late = false;
1859 /** Accuracy in decimal digits. Only object of this type! Can be set using
1860 * assignment from C++ unsigned ints and evaluated like any built-in type. */
1861 _numeric_digits Digits;
1863 #ifndef NO_NAMESPACE_GINAC
1864 } // namespace GiNaC
1865 #endif // ndef NO_NAMESPACE_GINAC