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_integer_io.h>
52 #include <cln/cl_integer_ring.h>
53 #include <cln/cl_rational_io.h>
54 #include <cln/cl_rational_ring.h>
55 #include <cln/cl_lfloat_class.h>
56 #include <cln/cl_lfloat_io.h>
57 #include <cln/cl_real_io.h>
58 #include <cln/cl_real_ring.h>
59 #include <cln/cl_complex_io.h>
60 #include <cln/cl_complex_ring.h>
61 #include <cln/cl_numtheory.h>
63 #include <cl_integer_io.h>
64 #include <cl_integer_ring.h>
65 #include <cl_rational_io.h>
66 #include <cl_rational_ring.h>
67 #include <cl_lfloat_class.h>
68 #include <cl_lfloat_io.h>
69 #include <cl_real_io.h>
70 #include <cl_real_ring.h>
71 #include <cl_complex_io.h>
72 #include <cl_complex_ring.h>
73 #include <cl_numtheory.h>
76 #ifndef NO_GINAC_NAMESPACE
78 #endif // ndef NO_GINAC_NAMESPACE
80 // linker has no problems finding text symbols for numerator or denominator
83 GINAC_IMPLEMENT_REGISTERED_CLASS(numeric, basic)
86 // default constructor, destructor, copy constructor assignment
87 // operator and helpers
92 /** default ctor. Numerically it initializes to an integer zero. */
93 numeric::numeric() : basic(TINFO_numeric)
95 debugmsg("numeric default constructor", LOGLEVEL_CONSTRUCT);
99 setflag(status_flags::evaluated|
100 status_flags::hash_calculated);
105 debugmsg("numeric destructor" ,LOGLEVEL_DESTRUCT);
109 numeric::numeric(const numeric & other)
111 debugmsg("numeric copy constructor", LOGLEVEL_CONSTRUCT);
115 const numeric & numeric::operator=(const numeric & other)
117 debugmsg("numeric operator=", LOGLEVEL_ASSIGNMENT);
118 if (this != &other) {
127 void numeric::copy(const numeric & other)
130 value = new cl_N(*other.value);
133 void numeric::destroy(bool call_parent)
136 if (call_parent) basic::destroy(call_parent);
140 // other constructors
145 numeric::numeric(int i) : basic(TINFO_numeric)
147 debugmsg("numeric constructor from int",LOGLEVEL_CONSTRUCT);
148 // Not the whole int-range is available if we don't cast to long
149 // first. This is due to the behaviour of the cl_I-ctor, which
150 // emphasizes efficiency:
151 value = new cl_I((long) i);
153 setflag(status_flags::evaluated|
154 status_flags::hash_calculated);
157 numeric::numeric(unsigned int i) : basic(TINFO_numeric)
159 debugmsg("numeric constructor from uint",LOGLEVEL_CONSTRUCT);
160 // Not the whole uint-range is available if we don't cast to ulong
161 // first. This is due to the behaviour of the cl_I-ctor, which
162 // emphasizes efficiency:
163 value = new cl_I((unsigned long)i);
165 setflag(status_flags::evaluated|
166 status_flags::hash_calculated);
169 numeric::numeric(long i) : basic(TINFO_numeric)
171 debugmsg("numeric constructor from long",LOGLEVEL_CONSTRUCT);
174 setflag(status_flags::evaluated|
175 status_flags::hash_calculated);
178 numeric::numeric(unsigned long i) : basic(TINFO_numeric)
180 debugmsg("numeric constructor from ulong",LOGLEVEL_CONSTRUCT);
183 setflag(status_flags::evaluated|
184 status_flags::hash_calculated);
187 /** Ctor for rational numerics a/b.
189 * @exception overflow_error (division by zero) */
190 numeric::numeric(long numer, long denom) : basic(TINFO_numeric)
192 debugmsg("numeric constructor from long/long",LOGLEVEL_CONSTRUCT);
194 throw (std::overflow_error("division by zero"));
195 value = new cl_I(numer);
196 *value = *value / cl_I(denom);
198 setflag(status_flags::evaluated|
199 status_flags::hash_calculated);
202 numeric::numeric(double d) : basic(TINFO_numeric)
204 debugmsg("numeric constructor from double",LOGLEVEL_CONSTRUCT);
205 // We really want to explicitly use the type cl_LF instead of the
206 // more general cl_F, since that would give us a cl_DF only which
207 // will not be promoted to cl_LF if overflow occurs:
209 *value = cl_float(d, cl_default_float_format);
211 setflag(status_flags::evaluated|
212 status_flags::hash_calculated);
215 numeric::numeric(const char *s) : basic(TINFO_numeric)
216 { // MISSING: treatment of complex and ints and rationals.
217 debugmsg("numeric constructor from string",LOGLEVEL_CONSTRUCT);
219 value = new cl_LF(s);
223 setflag(status_flags::evaluated|
224 status_flags::hash_calculated);
227 /** Ctor from CLN types. This is for the initiated user or internal use
229 numeric::numeric(cl_N const & z) : basic(TINFO_numeric)
231 debugmsg("numeric constructor from cl_N", LOGLEVEL_CONSTRUCT);
234 setflag(status_flags::evaluated|
235 status_flags::hash_calculated);
242 /** Construct object from archive_node. */
243 numeric::numeric(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
245 debugmsg("numeric constructor from archive_node", LOGLEVEL_CONSTRUCT);
248 // Read number as string
250 if (n.find_string("number", str)) {
251 istringstream s(str);
252 cl_idecoded_float re, im;
256 case 'N': // Ordinary number
257 case 'R': // Integer-decoded real number
258 s >> re.sign >> re.mantissa >> re.exponent;
259 *value = re.sign * re.mantissa * expt(cl_float(2.0, cl_default_float_format), re.exponent);
261 case 'C': // Integer-decoded complex number
262 s >> re.sign >> re.mantissa >> re.exponent;
263 s >> im.sign >> im.mantissa >> im.exponent;
264 *value = complex(re.sign * re.mantissa * expt(cl_float(2.0, cl_default_float_format), re.exponent),
265 im.sign * im.mantissa * expt(cl_float(2.0, cl_default_float_format), im.exponent));
267 default: // Ordinary number
274 // Read number as string
276 if (n.find_string("number", str)) {
277 istrstream f(str.c_str(), str.size() + 1);
278 cl_idecoded_float re, im;
282 case 'R': // Integer-decoded real number
283 f >> re.sign >> re.mantissa >> re.exponent;
284 *value = re.sign * re.mantissa * expt(cl_float(2.0, cl_default_float_format), re.exponent);
286 case 'C': // Integer-decoded complex number
287 f >> re.sign >> re.mantissa >> re.exponent;
288 f >> im.sign >> im.mantissa >> im.exponent;
289 *value = complex(re.sign * re.mantissa * expt(cl_float(2.0, cl_default_float_format), re.exponent),
290 im.sign * im.mantissa * expt(cl_float(2.0, cl_default_float_format), im.exponent));
292 default: // Ordinary number
300 setflag(status_flags::evaluated|
301 status_flags::hash_calculated);
304 /** Unarchive the object. */
305 ex numeric::unarchive(const archive_node &n, const lst &sym_lst)
307 return (new numeric(n, sym_lst))->setflag(status_flags::dynallocated);
310 /** Archive the object. */
311 void numeric::archive(archive_node &n) const
313 inherited::archive(n);
315 // Write number as string
320 // Non-rational numbers are written in an integer-decoded format
321 // to preserve the precision
323 cl_idecoded_float re = integer_decode_float(The(cl_F)(*value));
325 s << re.sign << " " << re.mantissa << " " << re.exponent;
327 cl_idecoded_float re = integer_decode_float(The(cl_F)(realpart(*value)));
328 cl_idecoded_float im = integer_decode_float(The(cl_F)(imagpart(*value)));
330 s << re.sign << " " << re.mantissa << " " << re.exponent << " ";
331 s << im.sign << " " << im.mantissa << " " << im.exponent;
334 n.add_string("number", s.str());
336 // Write number as string
338 ostrstream f(buf, 1024);
342 // Non-rational numbers are written in an integer-decoded format
343 // to preserve the precision
345 cl_idecoded_float re = integer_decode_float(The(cl_F)(*value));
347 f << re.sign << " " << re.mantissa << " " << re.exponent << ends;
349 cl_idecoded_float re = integer_decode_float(The(cl_F)(realpart(*value)));
350 cl_idecoded_float im = integer_decode_float(The(cl_F)(imagpart(*value)));
352 f << re.sign << " " << re.mantissa << " " << re.exponent << " ";
353 f << im.sign << " " << im.mantissa << " " << im.exponent << ends;
357 n.add_string("number", str);
362 // functions overriding virtual functions from bases classes
367 basic * numeric::duplicate() const
369 debugmsg("numeric duplicate", LOGLEVEL_DUPLICATE);
370 return new numeric(*this);
373 void numeric::print(ostream & os, unsigned upper_precedence) const
375 // The method print adds to the output so it blends more consistently
376 // together with the other routines and produces something compatible to
378 debugmsg("numeric print", LOGLEVEL_PRINT);
380 // case 1, real: x or -x
381 if ((precedence<=upper_precedence) && (!is_pos_integer())) {
382 os << "(" << *value << ")";
387 // case 2, imaginary: y*I or -y*I
388 if (realpart(*value) == 0) {
389 if ((precedence<=upper_precedence) && (imagpart(*value) < 0)) {
390 if (imagpart(*value) == -1) {
393 os << "(" << imagpart(*value) << "*I)";
396 if (imagpart(*value) == 1) {
399 if (imagpart (*value) == -1) {
402 os << imagpart(*value) << "*I";
407 // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I
408 if (precedence <= upper_precedence) os << "(";
409 os << realpart(*value);
410 if (imagpart(*value) < 0) {
411 if (imagpart(*value) == -1) {
414 os << imagpart(*value) << "*I";
417 if (imagpart(*value) == 1) {
420 os << "+" << imagpart(*value) << "*I";
423 if (precedence <= upper_precedence) os << ")";
429 void numeric::printraw(ostream & os) const
431 // The method printraw doesn't do much, it simply uses CLN's operator<<()
432 // for output, which is ugly but reliable. e.g: 2+2i
433 debugmsg("numeric printraw", LOGLEVEL_PRINT);
434 os << "numeric(" << *value << ")";
436 void numeric::printtree(ostream & os, unsigned indent) const
438 debugmsg("numeric printtree", LOGLEVEL_PRINT);
439 os << string(indent,' ') << *value
441 << "hash=" << hashvalue << " (0x" << hex << hashvalue << dec << ")"
442 << ", flags=" << flags << endl;
445 void numeric::printcsrc(ostream & os, unsigned type, unsigned upper_precedence) const
447 debugmsg("numeric print csrc", LOGLEVEL_PRINT);
448 ios::fmtflags oldflags = os.flags();
449 os.setf(ios::scientific);
450 if (is_rational() && !is_integer()) {
451 if (compare(_num0()) > 0) {
453 if (type == csrc_types::ctype_cl_N)
454 os << "cl_F(\"" << numer().evalf() << "\")";
456 os << numer().to_double();
459 if (type == csrc_types::ctype_cl_N)
460 os << "cl_F(\"" << -numer().evalf() << "\")";
462 os << -numer().to_double();
465 if (type == csrc_types::ctype_cl_N)
466 os << "cl_F(\"" << denom().evalf() << "\")";
468 os << denom().to_double();
471 if (type == csrc_types::ctype_cl_N)
472 os << "cl_F(\"" << evalf() << "\")";
479 bool numeric::info(unsigned inf) const
482 case info_flags::numeric:
483 case info_flags::polynomial:
484 case info_flags::rational_function:
486 case info_flags::real:
488 case info_flags::rational:
489 case info_flags::rational_polynomial:
490 return is_rational();
491 case info_flags::crational:
492 case info_flags::crational_polynomial:
493 return is_crational();
494 case info_flags::integer:
495 case info_flags::integer_polynomial:
497 case info_flags::cinteger:
498 case info_flags::cinteger_polynomial:
499 return is_cinteger();
500 case info_flags::positive:
501 return is_positive();
502 case info_flags::negative:
503 return is_negative();
504 case info_flags::nonnegative:
505 return compare(_num0())>=0;
506 case info_flags::posint:
507 return is_pos_integer();
508 case info_flags::negint:
509 return is_integer() && (compare(_num0())<0);
510 case info_flags::nonnegint:
511 return is_nonneg_integer();
512 case info_flags::even:
514 case info_flags::odd:
516 case info_flags::prime:
522 /** Cast numeric into a floating-point object. For example exact numeric(1) is
523 * returned as a 1.0000000000000000000000 and so on according to how Digits is
526 * @param level ignored, but needed for overriding basic::evalf.
527 * @return an ex-handle to a numeric. */
528 ex numeric::evalf(int level) const
530 // level can safely be discarded for numeric objects.
531 return numeric(cl_float(1.0, cl_default_float_format) * (*value)); // -> CLN
536 int numeric::compare_same_type(const basic & other) const
538 GINAC_ASSERT(is_exactly_of_type(other, numeric));
539 const numeric & o = static_cast<numeric &>(const_cast<basic &>(other));
541 if (*value == *o.value) {
548 bool numeric::is_equal_same_type(const basic & other) const
550 GINAC_ASSERT(is_exactly_of_type(other,numeric));
551 const numeric *o = static_cast<const numeric *>(&other);
557 unsigned numeric::calchash(void) const
559 double d=to_double();
565 return 0x88000000U+s*unsigned(d/0x07FF0000);
571 // new virtual functions which can be overridden by derived classes
577 // non-virtual functions in this class
582 /** Numerical addition method. Adds argument to *this and returns result as
583 * a new numeric object. */
584 numeric numeric::add(const numeric & other) const
586 return numeric((*value)+(*other.value));
589 /** Numerical subtraction method. Subtracts argument from *this and returns
590 * result as a new numeric object. */
591 numeric numeric::sub(const numeric & other) const
593 return numeric((*value)-(*other.value));
596 /** Numerical multiplication method. Multiplies *this and argument and returns
597 * result as a new numeric object. */
598 numeric numeric::mul(const numeric & other) const
600 static const numeric * _num1p=&_num1();
603 } else if (&other==_num1p) {
606 return numeric((*value)*(*other.value));
609 /** Numerical division method. Divides *this by argument and returns result as
610 * a new numeric object.
612 * @exception overflow_error (division by zero) */
613 numeric numeric::div(const numeric & other) const
615 if (::zerop(*other.value))
616 throw (std::overflow_error("division by zero"));
617 return numeric((*value)/(*other.value));
620 numeric numeric::power(const numeric & other) const
622 static const numeric * _num1p=&_num1();
625 if (::zerop(*value) && other.is_real() && ::minusp(realpart(*other.value)))
626 throw (std::overflow_error("division by zero"));
627 return numeric(::expt(*value,*other.value));
630 /** Inverse of a number. */
631 numeric numeric::inverse(void) const
633 return numeric(::recip(*value)); // -> CLN
636 const numeric & numeric::add_dyn(const numeric & other) const
638 return static_cast<const numeric &>((new numeric((*value)+(*other.value)))->
639 setflag(status_flags::dynallocated));
642 const numeric & numeric::sub_dyn(const numeric & other) const
644 return static_cast<const numeric &>((new numeric((*value)-(*other.value)))->
645 setflag(status_flags::dynallocated));
648 const numeric & numeric::mul_dyn(const numeric & other) const
650 static const numeric * _num1p=&_num1();
653 } else if (&other==_num1p) {
656 return static_cast<const numeric &>((new numeric((*value)*(*other.value)))->
657 setflag(status_flags::dynallocated));
660 const numeric & numeric::div_dyn(const numeric & other) const
662 if (::zerop(*other.value))
663 throw (std::overflow_error("division by zero"));
664 return static_cast<const numeric &>((new numeric((*value)/(*other.value)))->
665 setflag(status_flags::dynallocated));
668 const numeric & numeric::power_dyn(const numeric & other) const
670 static const numeric * _num1p=&_num1();
673 if (::zerop(*value) && other.is_real() && ::minusp(realpart(*other.value)))
674 throw (std::overflow_error("division by zero"));
675 return static_cast<const numeric &>((new numeric(::expt(*value,*other.value)))->
676 setflag(status_flags::dynallocated));
679 const numeric & numeric::operator=(int i)
681 return operator=(numeric(i));
684 const numeric & numeric::operator=(unsigned int i)
686 return operator=(numeric(i));
689 const numeric & numeric::operator=(long i)
691 return operator=(numeric(i));
694 const numeric & numeric::operator=(unsigned long i)
696 return operator=(numeric(i));
699 const numeric & numeric::operator=(double d)
701 return operator=(numeric(d));
704 const numeric & numeric::operator=(const char * s)
706 return operator=(numeric(s));
709 /** Return the complex half-plane (left or right) in which the number lies.
710 * csgn(x)==0 for x==0, csgn(x)==1 for Re(x)>0 or Re(x)=0 and Im(x)>0,
711 * csgn(x)==-1 for Re(x)<0 or Re(x)=0 and Im(x)<0.
713 * @see numeric::compare(const numeric & other) */
714 int numeric::csgn(void) const
718 if (!::zerop(realpart(*value))) {
719 if (::plusp(realpart(*value)))
724 if (::plusp(imagpart(*value)))
731 /** This method establishes a canonical order on all numbers. For complex
732 * numbers this is not possible in a mathematically consistent way but we need
733 * to establish some order and it ought to be fast. So we simply define it
734 * to be compatible with our method csgn.
736 * @return csgn(*this-other)
737 * @see numeric::csgn(void) */
738 int numeric::compare(const numeric & other) const
740 // Comparing two real numbers?
741 if (is_real() && other.is_real())
742 // Yes, just compare them
743 return ::cl_compare(The(cl_R)(*value), The(cl_R)(*other.value));
745 // No, first compare real parts
746 cl_signean real_cmp = ::cl_compare(realpart(*value), realpart(*other.value));
750 return ::cl_compare(imagpart(*value), imagpart(*other.value));
754 bool numeric::is_equal(const numeric & other) const
756 return (*value == *other.value);
759 /** True if object is zero. */
760 bool numeric::is_zero(void) const
762 return ::zerop(*value); // -> CLN
765 /** True if object is not complex and greater than zero. */
766 bool numeric::is_positive(void) const
769 return ::plusp(The(cl_R)(*value)); // -> CLN
773 /** True if object is not complex and less than zero. */
774 bool numeric::is_negative(void) const
777 return ::minusp(The(cl_R)(*value)); // -> CLN
781 /** True if object is a non-complex integer. */
782 bool numeric::is_integer(void) const
784 return ::instanceof(*value, cl_I_ring); // -> CLN
787 /** True if object is an exact integer greater than zero. */
788 bool numeric::is_pos_integer(void) const
790 return (is_integer() && ::plusp(The(cl_I)(*value))); // -> CLN
793 /** True if object is an exact integer greater or equal zero. */
794 bool numeric::is_nonneg_integer(void) const
796 return (is_integer() && !::minusp(The(cl_I)(*value))); // -> CLN
799 /** True if object is an exact even integer. */
800 bool numeric::is_even(void) const
802 return (is_integer() && ::evenp(The(cl_I)(*value))); // -> CLN
805 /** True if object is an exact odd integer. */
806 bool numeric::is_odd(void) const
808 return (is_integer() && ::oddp(The(cl_I)(*value))); // -> CLN
811 /** Probabilistic primality test.
813 * @return true if object is exact integer and prime. */
814 bool numeric::is_prime(void) const
816 return (is_integer() && ::isprobprime(The(cl_I)(*value))); // -> CLN
819 /** True if object is an exact rational number, may even be complex
820 * (denominator may be unity). */
821 bool numeric::is_rational(void) const
823 return ::instanceof(*value, cl_RA_ring); // -> CLN
826 /** True if object is a real integer, rational or float (but not complex). */
827 bool numeric::is_real(void) const
829 return ::instanceof(*value, cl_R_ring); // -> CLN
832 bool numeric::operator==(const numeric & other) const
834 return (*value == *other.value); // -> CLN
837 bool numeric::operator!=(const numeric & other) const
839 return (*value != *other.value); // -> CLN
842 /** True if object is element of the domain of integers extended by I, i.e. is
843 * of the form a+b*I, where a and b are integers. */
844 bool numeric::is_cinteger(void) const
846 if (::instanceof(*value, cl_I_ring))
848 else if (!is_real()) { // complex case, handle n+m*I
849 if (::instanceof(realpart(*value), cl_I_ring) &&
850 ::instanceof(imagpart(*value), cl_I_ring))
856 /** True if object is an exact rational number, may even be complex
857 * (denominator may be unity). */
858 bool numeric::is_crational(void) const
860 if (::instanceof(*value, cl_RA_ring))
862 else if (!is_real()) { // complex case, handle Q(i):
863 if (::instanceof(realpart(*value), cl_RA_ring) &&
864 ::instanceof(imagpart(*value), cl_RA_ring))
870 /** Numerical comparison: less.
872 * @exception invalid_argument (complex inequality) */
873 bool numeric::operator<(const numeric & other) const
875 if (is_real() && other.is_real())
876 return (bool)(The(cl_R)(*value) < The(cl_R)(*other.value)); // -> CLN
877 throw (std::invalid_argument("numeric::operator<(): complex inequality"));
878 return false; // make compiler shut up
881 /** Numerical comparison: less or equal.
883 * @exception invalid_argument (complex inequality) */
884 bool numeric::operator<=(const numeric & other) const
886 if (is_real() && other.is_real())
887 return (bool)(The(cl_R)(*value) <= The(cl_R)(*other.value)); // -> CLN
888 throw (std::invalid_argument("numeric::operator<=(): complex inequality"));
889 return false; // make compiler shut up
892 /** Numerical comparison: greater.
894 * @exception invalid_argument (complex inequality) */
895 bool numeric::operator>(const numeric & other) const
897 if (is_real() && other.is_real())
898 return (bool)(The(cl_R)(*value) > The(cl_R)(*other.value)); // -> CLN
899 throw (std::invalid_argument("numeric::operator>(): complex inequality"));
900 return false; // make compiler shut up
903 /** Numerical comparison: greater or equal.
905 * @exception invalid_argument (complex inequality) */
906 bool numeric::operator>=(const numeric & other) const
908 if (is_real() && other.is_real())
909 return (bool)(The(cl_R)(*value) >= The(cl_R)(*other.value)); // -> CLN
910 throw (std::invalid_argument("numeric::operator>=(): complex inequality"));
911 return false; // make compiler shut up
914 /** Converts numeric types to machine's int. You should check with is_integer()
915 * if the number is really an integer before calling this method. */
916 int numeric::to_int(void) const
918 GINAC_ASSERT(is_integer());
919 return ::cl_I_to_int(The(cl_I)(*value)); // -> CLN
922 /** Converts numeric types to machine's double. You should check with is_real()
923 * if the number is really not complex before calling this method. */
924 double numeric::to_double(void) const
926 GINAC_ASSERT(is_real());
927 return ::cl_double_approx(realpart(*value)); // -> CLN
930 /** Real part of a number. */
931 numeric numeric::real(void) const
933 return numeric(::realpart(*value)); // -> CLN
936 /** Imaginary part of a number. */
937 numeric numeric::imag(void) const
939 return numeric(::imagpart(*value)); // -> CLN
943 // Unfortunately, CLN did not provide an official way to access the numerator
944 // or denominator of a rational number (cl_RA). Doing some excavations in CLN
945 // one finds how it works internally in src/rational/cl_RA.h:
946 struct cl_heap_ratio : cl_heap {
951 inline cl_heap_ratio* TheRatio (const cl_N& obj)
952 { return (cl_heap_ratio*)(obj.pointer); }
953 #endif // ndef SANE_LINKER
955 /** Numerator. Computes the numerator of rational numbers, rationalized
956 * numerator of complex if real and imaginary part are both rational numbers
957 * (i.e numer(4/3+5/6*I) == 8+5*I), the number carrying the sign in all other
959 numeric numeric::numer(void) const
962 return numeric(*this);
965 else if (::instanceof(*value, cl_RA_ring)) {
966 return numeric(::numerator(The(cl_RA)(*value)));
968 else if (!is_real()) { // complex case, handle Q(i):
969 cl_R r = ::realpart(*value);
970 cl_R i = ::imagpart(*value);
971 if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_I_ring))
972 return numeric(*this);
973 if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_RA_ring))
974 return numeric(complex(r*::denominator(The(cl_RA)(i)), ::numerator(The(cl_RA)(i))));
975 if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_I_ring))
976 return numeric(complex(::numerator(The(cl_RA)(r)), i*::denominator(The(cl_RA)(r))));
977 if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_RA_ring)) {
978 cl_I s = lcm(::denominator(The(cl_RA)(r)), ::denominator(The(cl_RA)(i)));
979 return numeric(complex(::numerator(The(cl_RA)(r))*(exquo(s,::denominator(The(cl_RA)(r)))),
980 ::numerator(The(cl_RA)(i))*(exquo(s,::denominator(The(cl_RA)(i))))));
984 else if (instanceof(*value, cl_RA_ring)) {
985 return numeric(TheRatio(*value)->numerator);
987 else if (!is_real()) { // complex case, handle Q(i):
988 cl_R r = realpart(*value);
989 cl_R i = imagpart(*value);
990 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
991 return numeric(*this);
992 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
993 return numeric(complex(r*TheRatio(i)->denominator, TheRatio(i)->numerator));
994 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
995 return numeric(complex(TheRatio(r)->numerator, i*TheRatio(r)->denominator));
996 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) {
997 cl_I s = lcm(TheRatio(r)->denominator, TheRatio(i)->denominator);
998 return numeric(complex(TheRatio(r)->numerator*(exquo(s,TheRatio(r)->denominator)),
999 TheRatio(i)->numerator*(exquo(s,TheRatio(i)->denominator))));
1002 #endif // def SANE_LINKER
1003 // at least one float encountered
1004 return numeric(*this);
1007 /** Denominator. Computes the denominator of rational numbers, common integer
1008 * denominator of complex if real and imaginary part are both rational numbers
1009 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
1010 numeric numeric::denom(void) const
1016 if (instanceof(*value, cl_RA_ring)) {
1017 return numeric(::denominator(The(cl_RA)(*value)));
1019 if (!is_real()) { // complex case, handle Q(i):
1020 cl_R r = realpart(*value);
1021 cl_R i = imagpart(*value);
1022 if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_I_ring))
1024 if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_RA_ring))
1025 return numeric(::denominator(The(cl_RA)(i)));
1026 if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_I_ring))
1027 return numeric(::denominator(The(cl_RA)(r)));
1028 if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_RA_ring))
1029 return numeric(lcm(::denominator(The(cl_RA)(r)), ::denominator(The(cl_RA)(i))));
1032 if (instanceof(*value, cl_RA_ring)) {
1033 return numeric(TheRatio(*value)->denominator);
1035 if (!is_real()) { // complex case, handle Q(i):
1036 cl_R r = realpart(*value);
1037 cl_R i = imagpart(*value);
1038 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
1040 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
1041 return numeric(TheRatio(i)->denominator);
1042 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
1043 return numeric(TheRatio(r)->denominator);
1044 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring))
1045 return numeric(lcm(TheRatio(r)->denominator, TheRatio(i)->denominator));
1047 #endif // def SANE_LINKER
1048 // at least one float encountered
1052 /** Size in binary notation. For integers, this is the smallest n >= 0 such
1053 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
1054 * 2^(n-1) <= x < 2^n.
1056 * @return number of bits (excluding sign) needed to represent that number
1057 * in two's complement if it is an integer, 0 otherwise. */
1058 int numeric::int_length(void) const
1061 return ::integer_length(The(cl_I)(*value)); // -> CLN
1068 // static member variables
1073 unsigned numeric::precedence = 30;
1079 const numeric some_numeric;
1080 const type_info & typeid_numeric=typeid(some_numeric);
1081 /** Imaginary unit. This is not a constant but a numeric since we are
1082 * natively handing complex numbers anyways. */
1083 const numeric I = numeric(complex(cl_I(0),cl_I(1)));
1085 /** Exponential function.
1087 * @return arbitrary precision numerical exp(x). */
1088 numeric exp(const numeric & x)
1090 return ::exp(*x.value); // -> CLN
1093 /** Natural logarithm.
1095 * @param z complex number
1096 * @return arbitrary precision numerical log(x).
1097 * @exception overflow_error (logarithmic singularity) */
1098 numeric log(const numeric & z)
1101 throw (std::overflow_error("log(): logarithmic singularity"));
1102 return ::log(*z.value); // -> CLN
1105 /** Numeric sine (trigonometric function).
1107 * @return arbitrary precision numerical sin(x). */
1108 numeric sin(const numeric & x)
1110 return ::sin(*x.value); // -> CLN
1113 /** Numeric cosine (trigonometric function).
1115 * @return arbitrary precision numerical cos(x). */
1116 numeric cos(const numeric & x)
1118 return ::cos(*x.value); // -> CLN
1121 /** Numeric tangent (trigonometric function).
1123 * @return arbitrary precision numerical tan(x). */
1124 numeric tan(const numeric & x)
1126 return ::tan(*x.value); // -> CLN
1129 /** Numeric inverse sine (trigonometric function).
1131 * @return arbitrary precision numerical asin(x). */
1132 numeric asin(const numeric & x)
1134 return ::asin(*x.value); // -> CLN
1137 /** Numeric inverse cosine (trigonometric function).
1139 * @return arbitrary precision numerical acos(x). */
1140 numeric acos(const numeric & x)
1142 return ::acos(*x.value); // -> CLN
1147 * @param z complex number
1149 * @exception overflow_error (logarithmic singularity) */
1150 numeric atan(const numeric & x)
1153 x.real().is_zero() &&
1154 !abs(x.imag()).is_equal(_num1()))
1155 throw (std::overflow_error("atan(): logarithmic singularity"));
1156 return ::atan(*x.value); // -> CLN
1161 * @param x real number
1162 * @param y real number
1163 * @return atan(y/x) */
1164 numeric atan(const numeric & y, const numeric & x)
1166 if (x.is_real() && y.is_real())
1167 return ::atan(realpart(*x.value), realpart(*y.value)); // -> CLN
1169 throw (std::invalid_argument("numeric::atan(): complex argument"));
1172 /** Numeric hyperbolic sine (trigonometric function).
1174 * @return arbitrary precision numerical sinh(x). */
1175 numeric sinh(const numeric & x)
1177 return ::sinh(*x.value); // -> CLN
1180 /** Numeric hyperbolic cosine (trigonometric function).
1182 * @return arbitrary precision numerical cosh(x). */
1183 numeric cosh(const numeric & x)
1185 return ::cosh(*x.value); // -> CLN
1188 /** Numeric hyperbolic tangent (trigonometric function).
1190 * @return arbitrary precision numerical tanh(x). */
1191 numeric tanh(const numeric & x)
1193 return ::tanh(*x.value); // -> CLN
1196 /** Numeric inverse hyperbolic sine (trigonometric function).
1198 * @return arbitrary precision numerical asinh(x). */
1199 numeric asinh(const numeric & x)
1201 return ::asinh(*x.value); // -> CLN
1204 /** Numeric inverse hyperbolic cosine (trigonometric function).
1206 * @return arbitrary precision numerical acosh(x). */
1207 numeric acosh(const numeric & x)
1209 return ::acosh(*x.value); // -> CLN
1212 /** Numeric inverse hyperbolic tangent (trigonometric function).
1214 * @return arbitrary precision numerical atanh(x). */
1215 numeric atanh(const numeric & x)
1217 return ::atanh(*x.value); // -> CLN
1220 /** Numeric evaluation of Riemann's Zeta function. Currently works only for
1221 * integer arguments. */
1222 numeric zeta(const numeric & x)
1224 // A dirty hack to allow for things like zeta(3.0), since CLN currently
1225 // only knows about integer arguments and zeta(3).evalf() automatically
1226 // cascades down to zeta(3.0).evalf(). The trick is to rely on 3.0-3
1227 // being an exact zero for CLN, which can be tested and then we can just
1228 // pass the number casted to an int:
1230 int aux = (int)(::cl_double_approx(realpart(*x.value)));
1231 if (zerop(*x.value-aux))
1232 return ::cl_zeta(aux); // -> CLN
1234 clog << "zeta(" << x
1235 << "): Does anybody know good way to calculate this numerically?"
1240 /** The gamma function.
1241 * This is only a stub! */
1242 numeric gamma(const numeric & x)
1244 clog << "gamma(" << x
1245 << "): Does anybody know good way to calculate this numerically?"
1250 /** The psi function (aka polygamma function).
1251 * This is only a stub! */
1252 numeric psi(const numeric & x)
1255 << "): Does anybody know good way to calculate this numerically?"
1260 /** The psi functions (aka polygamma functions).
1261 * This is only a stub! */
1262 numeric psi(const numeric & n, const numeric & x)
1264 clog << "psi(" << n << "," << x
1265 << "): Does anybody know good way to calculate this numerically?"
1270 /** Factorial combinatorial function.
1272 * @exception range_error (argument must be integer >= 0) */
1273 numeric factorial(const numeric & nn)
1275 if (!nn.is_nonneg_integer())
1276 throw (std::range_error("numeric::factorial(): argument must be integer >= 0"));
1277 return numeric(::factorial(nn.to_int())); // -> CLN
1280 /** The double factorial combinatorial function. (Scarcely used, but still
1281 * useful in cases, like for exact results of Gamma(n+1/2) for instance.)
1283 * @param n integer argument >= -1
1284 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == (-1)!! == 1
1285 * @exception range_error (argument must be integer >= -1) */
1286 numeric doublefactorial(const numeric & nn)
1288 if (nn == numeric(-1)) {
1291 if (!nn.is_nonneg_integer()) {
1292 throw (std::range_error("numeric::doublefactorial(): argument must be integer >= -1"));
1294 return numeric(::doublefactorial(nn.to_int())); // -> CLN
1297 /** The Binomial coefficients. It computes the binomial coefficients. For
1298 * integer n and k and positive n this is the number of ways of choosing k
1299 * objects from n distinct objects. If n is negative, the formula
1300 * binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */
1301 numeric binomial(const numeric & n, const numeric & k)
1303 if (n.is_integer() && k.is_integer()) {
1304 if (n.is_nonneg_integer()) {
1305 if (k.compare(n)!=1 && k.compare(_num0())!=-1)
1306 return numeric(::binomial(n.to_int(),k.to_int())); // -> CLN
1310 return _num_1().power(k)*binomial(k-n-_num1(),k);
1314 // should really be gamma(n+1)/(gamma(r+1)/gamma(n-r+1) or a suitable limit
1315 throw (std::range_error("numeric::binomial(): donĀ“t know how to evaluate that."));
1318 /** Bernoulli number. The nth Bernoulli number is the coefficient of x^n/n!
1319 * in the expansion of the function x/(e^x-1).
1321 * @return the nth Bernoulli number (a rational number).
1322 * @exception range_error (argument must be integer >= 0) */
1323 numeric bernoulli(const numeric & nn)
1325 if (!nn.is_integer() || nn.is_negative())
1326 throw (std::range_error("numeric::bernoulli(): argument must be integer >= 0"));
1329 if (!nn.compare(_num1()))
1330 return numeric(-1,2);
1333 // Until somebody has the Blues and comes up with a much better idea and
1334 // codes it (preferably in CLN) we make this a remembering function which
1335 // computes its results using the formula
1336 // B(nn) == - 1/(nn+1) * sum_{k=0}^{nn-1}(binomial(nn+1,k)*B(k))
1338 static vector<numeric> results;
1339 static int highest_result = -1;
1340 int n = nn.sub(_num2()).div(_num2()).to_int();
1341 if (n <= highest_result)
1343 if (results.capacity() < (unsigned)(n+1))
1344 results.reserve(n+1);
1346 numeric tmp; // used to store the sum
1347 for (int i=highest_result+1; i<=n; ++i) {
1348 // the first two elements:
1349 tmp = numeric(-2*i-1,2);
1350 // accumulate the remaining elements:
1351 for (int j=0; j<i; ++j)
1352 tmp += binomial(numeric(2*i+3),numeric(j*2+2))*results[j];
1353 // divide by -(nn+1) and store result:
1354 results.push_back(-tmp/numeric(2*i+3));
1360 /** Absolute value. */
1361 numeric abs(const numeric & x)
1363 return ::abs(*x.value); // -> CLN
1366 /** Modulus (in positive representation).
1367 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1368 * sign of a or is zero. This is different from Maple's modp, where the sign
1369 * of b is ignored. It is in agreement with Mathematica's Mod.
1371 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1372 * integer, 0 otherwise. */
1373 numeric mod(const numeric & a, const numeric & b)
1375 if (a.is_integer() && b.is_integer())
1376 return ::mod(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1378 return _num0(); // Throw?
1381 /** Modulus (in symmetric representation).
1382 * Equivalent to Maple's mods.
1384 * @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1385 numeric smod(const numeric & a, const numeric & b)
1387 // FIXME: Should this become a member function?
1388 if (a.is_integer() && b.is_integer()) {
1389 cl_I b2 = The(cl_I)(ceiling1(The(cl_I)(*b.value) / 2)) - 1;
1390 return ::mod(The(cl_I)(*a.value) + b2, The(cl_I)(*b.value)) - b2;
1392 return _num0(); // Throw?
1395 /** Numeric integer remainder.
1396 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1397 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1398 * sign of a or is zero.
1400 * @return remainder of a/b if both are integer, 0 otherwise. */
1401 numeric irem(const numeric & a, const numeric & b)
1403 if (a.is_integer() && b.is_integer())
1404 return ::rem(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1406 return _num0(); // Throw?
1409 /** Numeric integer remainder.
1410 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1411 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1412 * and irem(a,b) has the sign of a or is zero.
1414 * @return remainder of a/b and quotient stored in q if both are integer,
1416 numeric irem(const numeric & a, const numeric & b, numeric & q)
1418 if (a.is_integer() && b.is_integer()) { // -> CLN
1419 cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1420 q = rem_quo.quotient;
1421 return rem_quo.remainder;
1425 return _num0(); // Throw?
1429 /** Numeric integer quotient.
1430 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1432 * @return truncated quotient of a/b if both are integer, 0 otherwise. */
1433 numeric iquo(const numeric & a, const numeric & b)
1435 if (a.is_integer() && b.is_integer())
1436 return truncate1(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1438 return _num0(); // Throw?
1441 /** Numeric integer quotient.
1442 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1443 * r == a - iquo(a,b,r)*b.
1445 * @return truncated quotient of a/b and remainder stored in r if both are
1446 * integer, 0 otherwise. */
1447 numeric iquo(const numeric & a, const numeric & b, numeric & r)
1449 if (a.is_integer() && b.is_integer()) { // -> CLN
1450 cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1451 r = rem_quo.remainder;
1452 return rem_quo.quotient;
1455 return _num0(); // Throw?
1459 /** Numeric square root.
1460 * If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4)
1461 * should return integer 2.
1463 * @param z numeric argument
1464 * @return square root of z. Branch cut along negative real axis, the negative
1465 * real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part
1466 * where imag(z)>0. */
1467 numeric sqrt(const numeric & z)
1469 return ::sqrt(*z.value); // -> CLN
1472 /** Integer numeric square root. */
1473 numeric isqrt(const numeric & x)
1475 if (x.is_integer()) {
1477 ::isqrt(The(cl_I)(*x.value), &root); // -> CLN
1480 return _num0(); // Throw?
1483 /** Greatest Common Divisor.
1485 * @return The GCD of two numbers if both are integer, a numerical 1
1486 * if they are not. */
1487 numeric gcd(const numeric & a, const numeric & b)
1489 if (a.is_integer() && b.is_integer())
1490 return ::gcd(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1495 /** Least Common Multiple.
1497 * @return The LCM of two numbers if both are integer, the product of those
1498 * two numbers if they are not. */
1499 numeric lcm(const numeric & a, const numeric & b)
1501 if (a.is_integer() && b.is_integer())
1502 return ::lcm(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1504 return *a.value * *b.value;
1509 return numeric(cl_pi(cl_default_float_format)); // -> CLN
1512 ex EulerGammaEvalf(void)
1514 return numeric(cl_eulerconst(cl_default_float_format)); // -> CLN
1517 ex CatalanEvalf(void)
1519 return numeric(cl_catalanconst(cl_default_float_format)); // -> CLN
1522 // It initializes to 17 digits, because in CLN cl_float_format(17) turns out to
1523 // be 61 (<64) while cl_float_format(18)=65. We want to have a cl_LF instead
1524 // of cl_SF, cl_FF or cl_DF but everything else is basically arbitrary.
1525 _numeric_digits::_numeric_digits()
1530 cl_default_float_format = cl_float_format(17);
1533 _numeric_digits& _numeric_digits::operator=(long prec)
1536 cl_default_float_format = cl_float_format(prec);
1540 _numeric_digits::operator long()
1542 return (long)digits;
1545 void _numeric_digits::print(ostream & os) const
1547 debugmsg("_numeric_digits print", LOGLEVEL_PRINT);
1551 ostream& operator<<(ostream& os, const _numeric_digits & e)
1558 // static member variables
1563 bool _numeric_digits::too_late = false;
1565 /** Accuracy in decimal digits. Only object of this type! Can be set using
1566 * assignment from C++ unsigned ints and evaluated like any built-in type. */
1567 _numeric_digits Digits;
1569 #ifndef NO_GINAC_NAMESPACE
1570 } // namespace GiNaC
1571 #endif // ndef NO_GINAC_NAMESPACE