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
36 // CLN should not pollute the global namespace, hence we include it here
37 // instead of in some header file where it would propagate to other parts:
44 #ifndef NO_GINAC_NAMESPACE
46 #endif // ndef NO_GINAC_NAMESPACE
48 // linker has no problems finding text symbols for numerator or denominator
52 // default constructor, destructor, copy constructor assignment
53 // operator and helpers
58 /** default ctor. Numerically it initializes to an integer zero. */
59 numeric::numeric() : basic(TINFO_numeric)
61 debugmsg("numeric default constructor", LOGLEVEL_CONSTRUCT);
65 setflag(status_flags::evaluated|
66 status_flags::hash_calculated);
71 debugmsg("numeric destructor" ,LOGLEVEL_DESTRUCT);
75 numeric::numeric(const numeric & other)
77 debugmsg("numeric copy constructor", LOGLEVEL_CONSTRUCT);
81 const numeric & numeric::operator=(const numeric & other)
83 debugmsg("numeric operator=", LOGLEVEL_ASSIGNMENT);
93 void numeric::copy(const numeric & other)
96 value = new cl_N(*other.value);
99 void numeric::destroy(bool call_parent)
102 if (call_parent) basic::destroy(call_parent);
106 // other constructors
111 numeric::numeric(int i) : basic(TINFO_numeric)
113 debugmsg("const numericructor from int",LOGLEVEL_CONSTRUCT);
114 // Not the whole int-range is available if we don't cast to long
115 // first. This is due to the behaviour of the cl_I-ctor, which
116 // emphasizes efficiency:
117 value = new cl_I((long) i);
119 setflag(status_flags::evaluated|
120 status_flags::hash_calculated);
123 numeric::numeric(unsigned int i) : basic(TINFO_numeric)
125 debugmsg("const numericructor from uint",LOGLEVEL_CONSTRUCT);
126 // Not the whole uint-range is available if we don't cast to ulong
127 // first. This is due to the behaviour of the cl_I-ctor, which
128 // emphasizes efficiency:
129 value = new cl_I((unsigned long)i);
131 setflag(status_flags::evaluated|
132 status_flags::hash_calculated);
135 numeric::numeric(long i) : basic(TINFO_numeric)
137 debugmsg("const numericructor from long",LOGLEVEL_CONSTRUCT);
140 setflag(status_flags::evaluated|
141 status_flags::hash_calculated);
144 numeric::numeric(unsigned long i) : basic(TINFO_numeric)
146 debugmsg("const numericructor from ulong",LOGLEVEL_CONSTRUCT);
149 setflag(status_flags::evaluated|
150 status_flags::hash_calculated);
153 /** Ctor for rational numerics a/b.
155 * @exception overflow_error (division by zero) */
156 numeric::numeric(long numer, long denom) : basic(TINFO_numeric)
158 debugmsg("const numericructor from long/long",LOGLEVEL_CONSTRUCT);
160 throw (std::overflow_error("division by zero"));
161 value = new cl_I(numer);
162 *value = *value / cl_I(denom);
164 setflag(status_flags::evaluated|
165 status_flags::hash_calculated);
168 numeric::numeric(double d) : basic(TINFO_numeric)
170 debugmsg("const numericructor from double",LOGLEVEL_CONSTRUCT);
171 // We really want to explicitly use the type cl_LF instead of the
172 // more general cl_F, since that would give us a cl_DF only which
173 // will not be promoted to cl_LF if overflow occurs:
175 *value = cl_float(d, cl_default_float_format);
177 setflag(status_flags::evaluated|
178 status_flags::hash_calculated);
181 numeric::numeric(char const *s) : basic(TINFO_numeric)
182 { // MISSING: treatment of complex and ints and rationals.
183 debugmsg("const numericructor from string",LOGLEVEL_CONSTRUCT);
185 value = new cl_LF(s);
189 setflag(status_flags::evaluated|
190 status_flags::hash_calculated);
193 /** Ctor from CLN types. This is for the initiated user or internal use
195 numeric::numeric(cl_N const & z) : basic(TINFO_numeric)
197 debugmsg("const numericructor from cl_N", LOGLEVEL_CONSTRUCT);
200 setflag(status_flags::evaluated|
201 status_flags::hash_calculated);
205 // functions overriding virtual functions from bases classes
210 basic * numeric::duplicate() const
212 debugmsg("numeric duplicate", LOGLEVEL_DUPLICATE);
213 return new numeric(*this);
216 void numeric::print(ostream & os, unsigned upper_precedence) const
218 // The method print adds to the output so it blends more consistently
219 // together with the other routines and produces something compatible to
221 debugmsg("numeric print", LOGLEVEL_PRINT);
223 // case 1, real: x or -x
224 if ((precedence<=upper_precedence) && (!is_pos_integer())) {
225 os << "(" << *value << ")";
230 // case 2, imaginary: y*I or -y*I
231 if (realpart(*value) == 0) {
232 if ((precedence<=upper_precedence) && (imagpart(*value) < 0)) {
233 if (imagpart(*value) == -1) {
236 os << "(" << imagpart(*value) << "*I)";
239 if (imagpart(*value) == 1) {
242 if (imagpart (*value) == -1) {
245 os << imagpart(*value) << "*I";
250 // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I
251 if (precedence <= upper_precedence) os << "(";
252 os << realpart(*value);
253 if (imagpart(*value) < 0) {
254 if (imagpart(*value) == -1) {
257 os << imagpart(*value) << "*I";
260 if (imagpart(*value) == 1) {
263 os << "+" << imagpart(*value) << "*I";
266 if (precedence <= upper_precedence) os << ")";
272 void numeric::printraw(ostream & os) const
274 // The method printraw doesn't do much, it simply uses CLN's operator<<()
275 // for output, which is ugly but reliable. e.g: 2+2i
276 debugmsg("numeric printraw", LOGLEVEL_PRINT);
277 os << "numeric(" << *value << ")";
279 void numeric::printtree(ostream & os, unsigned indent) const
281 debugmsg("numeric printtree", LOGLEVEL_PRINT);
282 os << string(indent,' ') << *value
284 << "hash=" << hashvalue << " (0x" << hex << hashvalue << dec << ")"
285 << ", flags=" << flags << endl;
288 void numeric::printcsrc(ostream & os, unsigned type, unsigned upper_precedence) const
290 debugmsg("numeric print csrc", LOGLEVEL_PRINT);
291 ios::fmtflags oldflags = os.flags();
292 os.setf(ios::scientific);
293 if (is_rational() && !is_integer()) {
294 if (compare(_num0()) > 0) {
296 if (type == csrc_types::ctype_cl_N)
297 os << "cl_F(\"" << numer().evalf() << "\")";
299 os << numer().to_double();
302 if (type == csrc_types::ctype_cl_N)
303 os << "cl_F(\"" << -numer().evalf() << "\")";
305 os << -numer().to_double();
308 if (type == csrc_types::ctype_cl_N)
309 os << "cl_F(\"" << denom().evalf() << "\")";
311 os << denom().to_double();
314 if (type == csrc_types::ctype_cl_N)
315 os << "cl_F(\"" << evalf() << "\")";
322 bool numeric::info(unsigned inf) const
325 case info_flags::numeric:
326 case info_flags::polynomial:
327 case info_flags::rational_function:
329 case info_flags::real:
331 case info_flags::rational:
332 case info_flags::rational_polynomial:
333 return is_rational();
334 case info_flags::crational:
335 case info_flags::crational_polynomial:
336 return is_crational();
337 case info_flags::integer:
338 case info_flags::integer_polynomial:
340 case info_flags::cinteger:
341 case info_flags::cinteger_polynomial:
342 return is_cinteger();
343 case info_flags::positive:
344 return is_positive();
345 case info_flags::negative:
346 return is_negative();
347 case info_flags::nonnegative:
348 return compare(_num0())>=0;
349 case info_flags::posint:
350 return is_pos_integer();
351 case info_flags::negint:
352 return is_integer() && (compare(_num0())<0);
353 case info_flags::nonnegint:
354 return is_nonneg_integer();
355 case info_flags::even:
357 case info_flags::odd:
359 case info_flags::prime:
365 /** Cast numeric into a floating-point object. For example exact numeric(1) is
366 * returned as a 1.0000000000000000000000 and so on according to how Digits is
369 * @param level ignored, but needed for overriding basic::evalf.
370 * @return an ex-handle to a numeric. */
371 ex numeric::evalf(int level) const
373 // level can safely be discarded for numeric objects.
374 return numeric(cl_float(1.0, cl_default_float_format) * (*value)); // -> CLN
379 int numeric::compare_same_type(basic const & other) const
381 GINAC_ASSERT(is_exactly_of_type(other, numeric));
382 const numeric & o = static_cast<numeric &>(const_cast<basic &>(other));
384 if (*value == *o.value) {
391 bool numeric::is_equal_same_type(basic const & other) const
393 GINAC_ASSERT(is_exactly_of_type(other,numeric));
394 const numeric *o = static_cast<const numeric *>(&other);
400 unsigned numeric::calchash(void) const
402 double d=to_double();
408 return 0x88000000U+s*unsigned(d/0x07FF0000);
414 // new virtual functions which can be overridden by derived classes
420 // non-virtual functions in this class
425 /** Numerical addition method. Adds argument to *this and returns result as
426 * a new numeric object. */
427 numeric numeric::add(const numeric & other) const
429 return numeric((*value)+(*other.value));
432 /** Numerical subtraction method. Subtracts argument from *this and returns
433 * result as a new numeric object. */
434 numeric numeric::sub(const numeric & other) const
436 return numeric((*value)-(*other.value));
439 /** Numerical multiplication method. Multiplies *this and argument and returns
440 * result as a new numeric object. */
441 numeric numeric::mul(const numeric & other) const
443 static const numeric * _num1p=&_num1();
446 } else if (&other==_num1p) {
449 return numeric((*value)*(*other.value));
452 /** Numerical division method. Divides *this by argument and returns result as
453 * a new numeric object.
455 * @exception overflow_error (division by zero) */
456 numeric numeric::div(const numeric & other) const
458 if (::zerop(*other.value))
459 throw (std::overflow_error("division by zero"));
460 return numeric((*value)/(*other.value));
463 numeric numeric::power(const numeric & other) const
465 static const numeric * _num1p=&_num1();
468 if (::zerop(*value) && other.is_real() && ::minusp(realpart(*other.value)))
469 throw (std::overflow_error("division by zero"));
470 return numeric(::expt(*value,*other.value));
473 /** Inverse of a number. */
474 numeric numeric::inverse(void) const
476 return numeric(::recip(*value)); // -> CLN
479 const numeric & numeric::add_dyn(const numeric & other) const
481 return static_cast<const numeric &>((new numeric((*value)+(*other.value)))->
482 setflag(status_flags::dynallocated));
485 const numeric & numeric::sub_dyn(const numeric & other) const
487 return static_cast<const numeric &>((new numeric((*value)-(*other.value)))->
488 setflag(status_flags::dynallocated));
491 const numeric & numeric::mul_dyn(const numeric & other) const
493 static const numeric * _num1p=&_num1();
496 } else if (&other==_num1p) {
499 return static_cast<const numeric &>((new numeric((*value)*(*other.value)))->
500 setflag(status_flags::dynallocated));
503 const numeric & numeric::div_dyn(const numeric & other) const
505 if (::zerop(*other.value))
506 throw (std::overflow_error("division by zero"));
507 return static_cast<const numeric &>((new numeric((*value)/(*other.value)))->
508 setflag(status_flags::dynallocated));
511 const numeric & numeric::power_dyn(const numeric & other) const
513 static const numeric * _num1p=&_num1();
516 if (::zerop(*value) && other.is_real() && ::minusp(realpart(*other.value)))
517 throw (std::overflow_error("division by zero"));
518 return static_cast<const numeric &>((new numeric(::expt(*value,*other.value)))->
519 setflag(status_flags::dynallocated));
522 const numeric & numeric::operator=(int i)
524 return operator=(numeric(i));
527 const numeric & numeric::operator=(unsigned int i)
529 return operator=(numeric(i));
532 const numeric & numeric::operator=(long i)
534 return operator=(numeric(i));
537 const numeric & numeric::operator=(unsigned long i)
539 return operator=(numeric(i));
542 const numeric & numeric::operator=(double d)
544 return operator=(numeric(d));
547 const numeric & numeric::operator=(char const * s)
549 return operator=(numeric(s));
552 /** Return the complex half-plane (left or right) in which the number lies.
553 * csgn(x)==0 for x==0, csgn(x)==1 for Re(x)>0 or Re(x)=0 and Im(x)>0,
554 * csgn(x)==-1 for Re(x)<0 or Re(x)=0 and Im(x)<0.
556 * @see numeric::compare(const numeric & other) */
557 int numeric::csgn(void) const
561 if (!::zerop(realpart(*value))) {
562 if (::plusp(realpart(*value)))
567 if (::plusp(imagpart(*value)))
574 /** This method establishes a canonical order on all numbers. For complex
575 * numbers this is not possible in a mathematically consistent way but we need
576 * to establish some order and it ought to be fast. So we simply define it
577 * to be compatible with our method csgn.
579 * @return csgn(*this-other)
580 * @see numeric::csgn(void) */
581 int numeric::compare(const numeric & other) const
583 // Comparing two real numbers?
584 if (is_real() && other.is_real())
585 // Yes, just compare them
586 return ::cl_compare(The(cl_R)(*value), The(cl_R)(*other.value));
588 // No, first compare real parts
589 cl_signean real_cmp = ::cl_compare(realpart(*value), realpart(*other.value));
593 return ::cl_compare(imagpart(*value), imagpart(*other.value));
597 bool numeric::is_equal(const numeric & other) const
599 return (*value == *other.value);
602 /** True if object is zero. */
603 bool numeric::is_zero(void) const
605 return ::zerop(*value); // -> CLN
608 /** True if object is not complex and greater than zero. */
609 bool numeric::is_positive(void) const
612 return ::plusp(The(cl_R)(*value)); // -> CLN
616 /** True if object is not complex and less than zero. */
617 bool numeric::is_negative(void) const
620 return ::minusp(The(cl_R)(*value)); // -> CLN
624 /** True if object is a non-complex integer. */
625 bool numeric::is_integer(void) const
627 return ::instanceof(*value, cl_I_ring); // -> CLN
630 /** True if object is an exact integer greater than zero. */
631 bool numeric::is_pos_integer(void) const
633 return (is_integer() && ::plusp(The(cl_I)(*value))); // -> CLN
636 /** True if object is an exact integer greater or equal zero. */
637 bool numeric::is_nonneg_integer(void) const
639 return (is_integer() && !::minusp(The(cl_I)(*value))); // -> CLN
642 /** True if object is an exact even integer. */
643 bool numeric::is_even(void) const
645 return (is_integer() && ::evenp(The(cl_I)(*value))); // -> CLN
648 /** True if object is an exact odd integer. */
649 bool numeric::is_odd(void) const
651 return (is_integer() && ::oddp(The(cl_I)(*value))); // -> CLN
654 /** Probabilistic primality test.
656 * @return true if object is exact integer and prime. */
657 bool numeric::is_prime(void) const
659 return (is_integer() && ::isprobprime(The(cl_I)(*value))); // -> CLN
662 /** True if object is an exact rational number, may even be complex
663 * (denominator may be unity). */
664 bool numeric::is_rational(void) const
666 return ::instanceof(*value, cl_RA_ring); // -> CLN
669 /** True if object is a real integer, rational or float (but not complex). */
670 bool numeric::is_real(void) const
672 return ::instanceof(*value, cl_R_ring); // -> CLN
675 bool numeric::operator==(const numeric & other) const
677 return (*value == *other.value); // -> CLN
680 bool numeric::operator!=(const numeric & other) const
682 return (*value != *other.value); // -> CLN
685 /** True if object is element of the domain of integers extended by I, i.e. is
686 * of the form a+b*I, where a and b are integers. */
687 bool numeric::is_cinteger(void) const
689 if (::instanceof(*value, cl_I_ring))
691 else if (!is_real()) { // complex case, handle n+m*I
692 if (::instanceof(realpart(*value), cl_I_ring) &&
693 ::instanceof(imagpart(*value), cl_I_ring))
699 /** True if object is an exact rational number, may even be complex
700 * (denominator may be unity). */
701 bool numeric::is_crational(void) const
703 if (::instanceof(*value, cl_RA_ring))
705 else if (!is_real()) { // complex case, handle Q(i):
706 if (::instanceof(realpart(*value), cl_RA_ring) &&
707 ::instanceof(imagpart(*value), cl_RA_ring))
713 /** Numerical comparison: less.
715 * @exception invalid_argument (complex inequality) */
716 bool numeric::operator<(const numeric & other) const
718 if (is_real() && other.is_real())
719 return (bool)(The(cl_R)(*value) < The(cl_R)(*other.value)); // -> CLN
720 throw (std::invalid_argument("numeric::operator<(): complex inequality"));
721 return false; // make compiler shut up
724 /** Numerical comparison: less or equal.
726 * @exception invalid_argument (complex inequality) */
727 bool numeric::operator<=(const numeric & other) const
729 if (is_real() && other.is_real())
730 return (bool)(The(cl_R)(*value) <= The(cl_R)(*other.value)); // -> CLN
731 throw (std::invalid_argument("numeric::operator<=(): complex inequality"));
732 return false; // make compiler shut up
735 /** Numerical comparison: greater.
737 * @exception invalid_argument (complex inequality) */
738 bool numeric::operator>(const numeric & other) const
740 if (is_real() && other.is_real())
741 return (bool)(The(cl_R)(*value) > The(cl_R)(*other.value)); // -> CLN
742 throw (std::invalid_argument("numeric::operator>(): complex inequality"));
743 return false; // make compiler shut up
746 /** Numerical comparison: greater or equal.
748 * @exception invalid_argument (complex inequality) */
749 bool numeric::operator>=(const numeric & other) const
751 if (is_real() && other.is_real())
752 return (bool)(The(cl_R)(*value) >= The(cl_R)(*other.value)); // -> CLN
753 throw (std::invalid_argument("numeric::operator>=(): complex inequality"));
754 return false; // make compiler shut up
757 /** Converts numeric types to machine's int. You should check with is_integer()
758 * if the number is really an integer before calling this method. */
759 int numeric::to_int(void) const
761 GINAC_ASSERT(is_integer());
762 return ::cl_I_to_int(The(cl_I)(*value)); // -> CLN
765 /** Converts numeric types to machine's double. You should check with is_real()
766 * if the number is really not complex before calling this method. */
767 double numeric::to_double(void) const
769 GINAC_ASSERT(is_real());
770 return ::cl_double_approx(realpart(*value)); // -> CLN
773 /** Real part of a number. */
774 numeric numeric::real(void) const
776 return numeric(::realpart(*value)); // -> CLN
779 /** Imaginary part of a number. */
780 numeric numeric::imag(void) const
782 return numeric(::imagpart(*value)); // -> CLN
786 // Unfortunately, CLN did not provide an official way to access the numerator
787 // or denominator of a rational number (cl_RA). Doing some excavations in CLN
788 // one finds how it works internally in src/rational/cl_RA.h:
789 struct cl_heap_ratio : cl_heap {
794 inline cl_heap_ratio* TheRatio (const cl_N& obj)
795 { return (cl_heap_ratio*)(obj.pointer); }
796 #endif // ndef SANE_LINKER
798 /** Numerator. Computes the numerator of rational numbers, rationalized
799 * numerator of complex if real and imaginary part are both rational numbers
800 * (i.e numer(4/3+5/6*I) == 8+5*I), the number carrying the sign in all other
802 numeric numeric::numer(void) const
805 return numeric(*this);
808 else if (::instanceof(*value, cl_RA_ring)) {
809 return numeric(::numerator(The(cl_RA)(*value)));
811 else if (!is_real()) { // complex case, handle Q(i):
812 cl_R r = ::realpart(*value);
813 cl_R i = ::imagpart(*value);
814 if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_I_ring))
815 return numeric(*this);
816 if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_RA_ring))
817 return numeric(complex(r*::denominator(The(cl_RA)(i)), ::numerator(The(cl_RA)(i))));
818 if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_I_ring))
819 return numeric(complex(::numerator(The(cl_RA)(r)), i*::denominator(The(cl_RA)(r))));
820 if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_RA_ring)) {
821 cl_I s = lcm(::denominator(The(cl_RA)(r)), ::denominator(The(cl_RA)(i)));
822 return numeric(complex(::numerator(The(cl_RA)(r))*(exquo(s,::denominator(The(cl_RA)(r)))),
823 ::numerator(The(cl_RA)(i))*(exquo(s,::denominator(The(cl_RA)(i))))));
827 else if (instanceof(*value, cl_RA_ring)) {
828 return numeric(TheRatio(*value)->numerator);
830 else if (!is_real()) { // complex case, handle Q(i):
831 cl_R r = realpart(*value);
832 cl_R i = imagpart(*value);
833 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
834 return numeric(*this);
835 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
836 return numeric(complex(r*TheRatio(i)->denominator, TheRatio(i)->numerator));
837 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
838 return numeric(complex(TheRatio(r)->numerator, i*TheRatio(r)->denominator));
839 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) {
840 cl_I s = lcm(TheRatio(r)->denominator, TheRatio(i)->denominator);
841 return numeric(complex(TheRatio(r)->numerator*(exquo(s,TheRatio(r)->denominator)),
842 TheRatio(i)->numerator*(exquo(s,TheRatio(i)->denominator))));
845 #endif // def SANE_LINKER
846 // at least one float encountered
847 return numeric(*this);
850 /** Denominator. Computes the denominator of rational numbers, common integer
851 * denominator of complex if real and imaginary part are both rational numbers
852 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
853 numeric numeric::denom(void) const
859 if (instanceof(*value, cl_RA_ring)) {
860 return numeric(::denominator(The(cl_RA)(*value)));
862 if (!is_real()) { // complex case, handle Q(i):
863 cl_R r = realpart(*value);
864 cl_R i = imagpart(*value);
865 if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_I_ring))
867 if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_RA_ring))
868 return numeric(::denominator(The(cl_RA)(i)));
869 if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_I_ring))
870 return numeric(::denominator(The(cl_RA)(r)));
871 if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_RA_ring))
872 return numeric(lcm(::denominator(The(cl_RA)(r)), ::denominator(The(cl_RA)(i))));
875 if (instanceof(*value, cl_RA_ring)) {
876 return numeric(TheRatio(*value)->denominator);
878 if (!is_real()) { // complex case, handle Q(i):
879 cl_R r = realpart(*value);
880 cl_R i = imagpart(*value);
881 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
883 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
884 return numeric(TheRatio(i)->denominator);
885 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
886 return numeric(TheRatio(r)->denominator);
887 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring))
888 return numeric(lcm(TheRatio(r)->denominator, TheRatio(i)->denominator));
890 #endif // def SANE_LINKER
891 // at least one float encountered
895 /** Size in binary notation. For integers, this is the smallest n >= 0 such
896 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
897 * 2^(n-1) <= x < 2^n.
899 * @return number of bits (excluding sign) needed to represent that number
900 * in two's complement if it is an integer, 0 otherwise. */
901 int numeric::int_length(void) const
904 return ::integer_length(The(cl_I)(*value)); // -> CLN
911 // static member variables
916 unsigned numeric::precedence = 30;
922 const numeric some_numeric;
923 type_info const & typeid_numeric=typeid(some_numeric);
924 /** Imaginary unit. This is not a constant but a numeric since we are
925 * natively handing complex numbers anyways. */
926 const numeric I = numeric(complex(cl_I(0),cl_I(1)));
928 /** Exponential function.
930 * @return arbitrary precision numerical exp(x). */
931 numeric exp(const numeric & x)
933 return ::exp(*x.value); // -> CLN
936 /** Natural logarithm.
938 * @param z complex number
939 * @return arbitrary precision numerical log(x).
940 * @exception overflow_error (logarithmic singularity) */
941 numeric log(const numeric & z)
944 throw (std::overflow_error("log(): logarithmic singularity"));
945 return ::log(*z.value); // -> CLN
948 /** Numeric sine (trigonometric function).
950 * @return arbitrary precision numerical sin(x). */
951 numeric sin(const numeric & x)
953 return ::sin(*x.value); // -> CLN
956 /** Numeric cosine (trigonometric function).
958 * @return arbitrary precision numerical cos(x). */
959 numeric cos(const numeric & x)
961 return ::cos(*x.value); // -> CLN
964 /** Numeric tangent (trigonometric function).
966 * @return arbitrary precision numerical tan(x). */
967 numeric tan(const numeric & x)
969 return ::tan(*x.value); // -> CLN
972 /** Numeric inverse sine (trigonometric function).
974 * @return arbitrary precision numerical asin(x). */
975 numeric asin(const numeric & x)
977 return ::asin(*x.value); // -> CLN
980 /** Numeric inverse cosine (trigonometric function).
982 * @return arbitrary precision numerical acos(x). */
983 numeric acos(const numeric & x)
985 return ::acos(*x.value); // -> CLN
990 * @param z complex number
992 * @exception overflow_error (logarithmic singularity) */
993 numeric atan(const numeric & x)
996 x.real().is_zero() &&
997 !abs(x.imag()).is_equal(_num1()))
998 throw (std::overflow_error("atan(): logarithmic singularity"));
999 return ::atan(*x.value); // -> CLN
1004 * @param x real number
1005 * @param y real number
1006 * @return atan(y/x) */
1007 numeric atan(const numeric & y, const numeric & x)
1009 if (x.is_real() && y.is_real())
1010 return ::atan(realpart(*x.value), realpart(*y.value)); // -> CLN
1012 throw (std::invalid_argument("numeric::atan(): complex argument"));
1015 /** Numeric hyperbolic sine (trigonometric function).
1017 * @return arbitrary precision numerical sinh(x). */
1018 numeric sinh(const numeric & x)
1020 return ::sinh(*x.value); // -> CLN
1023 /** Numeric hyperbolic cosine (trigonometric function).
1025 * @return arbitrary precision numerical cosh(x). */
1026 numeric cosh(const numeric & x)
1028 return ::cosh(*x.value); // -> CLN
1031 /** Numeric hyperbolic tangent (trigonometric function).
1033 * @return arbitrary precision numerical tanh(x). */
1034 numeric tanh(const numeric & x)
1036 return ::tanh(*x.value); // -> CLN
1039 /** Numeric inverse hyperbolic sine (trigonometric function).
1041 * @return arbitrary precision numerical asinh(x). */
1042 numeric asinh(const numeric & x)
1044 return ::asinh(*x.value); // -> CLN
1047 /** Numeric inverse hyperbolic cosine (trigonometric function).
1049 * @return arbitrary precision numerical acosh(x). */
1050 numeric acosh(const numeric & x)
1052 return ::acosh(*x.value); // -> CLN
1055 /** Numeric inverse hyperbolic tangent (trigonometric function).
1057 * @return arbitrary precision numerical atanh(x). */
1058 numeric atanh(const numeric & x)
1060 return ::atanh(*x.value); // -> CLN
1063 /** Numeric evaluation of Riemann's Zeta function. Currently works only for
1064 * integer arguments. */
1065 numeric zeta(const numeric & x)
1067 // A dirty hack to allow for things like zeta(3.0), since CLN currently
1068 // only knows about integer arguments and zeta(3).evalf() automatically
1069 // cascades down to zeta(3.0).evalf(). The trick is to rely on 3.0-3
1070 // being an exact zero for CLN, which can be tested and then we can just
1071 // pass the number casted to an int:
1073 int aux = (int)(::cl_double_approx(realpart(*x.value)));
1074 if (zerop(*x.value-aux))
1075 return ::cl_zeta(aux); // -> CLN
1077 clog << "zeta(" << x
1078 << "): Does anybody know good way to calculate this numerically?"
1083 /** The gamma function.
1084 * This is only a stub! */
1085 numeric gamma(const numeric & x)
1087 clog << "gamma(" << x
1088 << "): Does anybody know good way to calculate this numerically?"
1093 /** The psi function (aka polygamma function).
1094 * This is only a stub! */
1095 numeric psi(const numeric & x)
1098 << "): Does anybody know good way to calculate this numerically?"
1103 /** The psi functions (aka polygamma functions).
1104 * This is only a stub! */
1105 numeric psi(const numeric & n, const numeric & x)
1107 clog << "psi(" << n << "," << x
1108 << "): Does anybody know good way to calculate this numerically?"
1113 /** Factorial combinatorial function.
1115 * @exception range_error (argument must be integer >= 0) */
1116 numeric factorial(const numeric & nn)
1118 if (!nn.is_nonneg_integer())
1119 throw (std::range_error("numeric::factorial(): argument must be integer >= 0"));
1120 return numeric(::factorial(nn.to_int())); // -> CLN
1123 /** The double factorial combinatorial function. (Scarcely used, but still
1124 * useful in cases, like for exact results of Gamma(n+1/2) for instance.)
1126 * @param n integer argument >= -1
1127 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == (-1)!! == 1
1128 * @exception range_error (argument must be integer >= -1) */
1129 numeric doublefactorial(const numeric & nn)
1131 if (nn == numeric(-1)) {
1134 if (!nn.is_nonneg_integer()) {
1135 throw (std::range_error("numeric::doublefactorial(): argument must be integer >= -1"));
1137 return numeric(::doublefactorial(nn.to_int())); // -> CLN
1140 /** The Binomial coefficients. It computes the binomial coefficients. For
1141 * integer n and k and positive n this is the number of ways of choosing k
1142 * objects from n distinct objects. If n is negative, the formula
1143 * binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */
1144 numeric binomial(const numeric & n, const numeric & k)
1146 if (n.is_integer() && k.is_integer()) {
1147 if (n.is_nonneg_integer()) {
1148 if (k.compare(n)!=1 && k.compare(_num0())!=-1)
1149 return numeric(::binomial(n.to_int(),k.to_int())); // -> CLN
1153 return _num_1().power(k)*binomial(k-n-_num1(),k);
1157 // should really be gamma(n+1)/(gamma(r+1)/gamma(n-r+1) or a suitable limit
1158 throw (std::range_error("numeric::binomial(): donĀ“t know how to evaluate that."));
1161 /** Bernoulli number. The nth Bernoulli number is the coefficient of x^n/n!
1162 * in the expansion of the function x/(e^x-1).
1164 * @return the nth Bernoulli number (a rational number).
1165 * @exception range_error (argument must be integer >= 0) */
1166 numeric bernoulli(const numeric & nn)
1168 if (!nn.is_integer() || nn.is_negative())
1169 throw (std::range_error("numeric::bernoulli(): argument must be integer >= 0"));
1172 if (!nn.compare(_num1()))
1173 return numeric(-1,2);
1176 // Until somebody has the Blues and comes up with a much better idea and
1177 // codes it (preferably in CLN) we make this a remembering function which
1178 // computes its results using the formula
1179 // B(nn) == - 1/(nn+1) * sum_{k=0}^{nn-1}(binomial(nn+1,k)*B(k))
1181 static vector<numeric> results;
1182 static int highest_result = -1;
1183 int n = nn.sub(_num2()).div(_num2()).to_int();
1184 if (n <= highest_result)
1186 if (results.capacity() < (unsigned)(n+1))
1187 results.reserve(n+1);
1189 numeric tmp; // used to store the sum
1190 for (int i=highest_result+1; i<=n; ++i) {
1191 // the first two elements:
1192 tmp = numeric(-2*i-1,2);
1193 // accumulate the remaining elements:
1194 for (int j=0; j<i; ++j)
1195 tmp += binomial(numeric(2*i+3),numeric(j*2+2))*results[j];
1196 // divide by -(nn+1) and store result:
1197 results.push_back(-tmp/numeric(2*i+3));
1203 /** Absolute value. */
1204 numeric abs(const numeric & x)
1206 return ::abs(*x.value); // -> CLN
1209 /** Modulus (in positive representation).
1210 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1211 * sign of a or is zero. This is different from Maple's modp, where the sign
1212 * of b is ignored. It is in agreement with Mathematica's Mod.
1214 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1215 * integer, 0 otherwise. */
1216 numeric mod(const numeric & a, const numeric & b)
1218 if (a.is_integer() && b.is_integer())
1219 return ::mod(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1221 return _num0(); // Throw?
1224 /** Modulus (in symmetric representation).
1225 * Equivalent to Maple's mods.
1227 * @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1228 numeric smod(const numeric & a, const numeric & b)
1230 // FIXME: Should this become a member function?
1231 if (a.is_integer() && b.is_integer()) {
1232 cl_I b2 = The(cl_I)(ceiling1(The(cl_I)(*b.value) / 2)) - 1;
1233 return ::mod(The(cl_I)(*a.value) + b2, The(cl_I)(*b.value)) - b2;
1235 return _num0(); // Throw?
1238 /** Numeric integer remainder.
1239 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1240 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1241 * sign of a or is zero.
1243 * @return remainder of a/b if both are integer, 0 otherwise. */
1244 numeric irem(const numeric & a, const numeric & b)
1246 if (a.is_integer() && b.is_integer())
1247 return ::rem(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1249 return _num0(); // Throw?
1252 /** Numeric integer remainder.
1253 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1254 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1255 * and irem(a,b) has the sign of a or is zero.
1257 * @return remainder of a/b and quotient stored in q if both are integer,
1259 numeric irem(const numeric & a, const numeric & b, numeric & q)
1261 if (a.is_integer() && b.is_integer()) { // -> CLN
1262 cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1263 q = rem_quo.quotient;
1264 return rem_quo.remainder;
1268 return _num0(); // Throw?
1272 /** Numeric integer quotient.
1273 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1275 * @return truncated quotient of a/b if both are integer, 0 otherwise. */
1276 numeric iquo(const numeric & a, const numeric & b)
1278 if (a.is_integer() && b.is_integer())
1279 return truncate1(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1281 return _num0(); // Throw?
1284 /** Numeric integer quotient.
1285 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1286 * r == a - iquo(a,b,r)*b.
1288 * @return truncated quotient of a/b and remainder stored in r if both are
1289 * integer, 0 otherwise. */
1290 numeric iquo(const numeric & a, const numeric & b, numeric & r)
1292 if (a.is_integer() && b.is_integer()) { // -> CLN
1293 cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1294 r = rem_quo.remainder;
1295 return rem_quo.quotient;
1298 return _num0(); // Throw?
1302 /** Numeric square root.
1303 * If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4)
1304 * should return integer 2.
1306 * @param z numeric argument
1307 * @return square root of z. Branch cut along negative real axis, the negative
1308 * real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part
1309 * where imag(z)>0. */
1310 numeric sqrt(const numeric & z)
1312 return ::sqrt(*z.value); // -> CLN
1315 /** Integer numeric square root. */
1316 numeric isqrt(const numeric & x)
1318 if (x.is_integer()) {
1320 ::isqrt(The(cl_I)(*x.value), &root); // -> CLN
1323 return _num0(); // Throw?
1326 /** Greatest Common Divisor.
1328 * @return The GCD of two numbers if both are integer, a numerical 1
1329 * if they are not. */
1330 numeric gcd(const numeric & a, const numeric & b)
1332 if (a.is_integer() && b.is_integer())
1333 return ::gcd(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1338 /** Least Common Multiple.
1340 * @return The LCM of two numbers if both are integer, the product of those
1341 * two numbers if they are not. */
1342 numeric lcm(const numeric & a, const numeric & b)
1344 if (a.is_integer() && b.is_integer())
1345 return ::lcm(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1347 return *a.value * *b.value;
1352 return numeric(cl_pi(cl_default_float_format)); // -> CLN
1355 ex EulerGammaEvalf(void)
1357 return numeric(cl_eulerconst(cl_default_float_format)); // -> CLN
1360 ex CatalanEvalf(void)
1362 return numeric(cl_catalanconst(cl_default_float_format)); // -> CLN
1365 // It initializes to 17 digits, because in CLN cl_float_format(17) turns out to
1366 // be 61 (<64) while cl_float_format(18)=65. We want to have a cl_LF instead
1367 // of cl_SF, cl_FF or cl_DF but everything else is basically arbitrary.
1368 _numeric_digits::_numeric_digits()
1373 cl_default_float_format = cl_float_format(17);
1376 _numeric_digits& _numeric_digits::operator=(long prec)
1379 cl_default_float_format = cl_float_format(prec);
1383 _numeric_digits::operator long()
1385 return (long)digits;
1388 void _numeric_digits::print(ostream & os) const
1390 debugmsg("_numeric_digits print", LOGLEVEL_PRINT);
1394 ostream& operator<<(ostream& os, _numeric_digits const & e)
1401 // static member variables
1406 bool _numeric_digits::too_late = false;
1408 /** Accuracy in decimal digits. Only object of this type! Can be set using
1409 * assignment from C++ unsigned ints and evaluated like any built-in type. */
1410 _numeric_digits Digits;
1412 #ifndef NO_GINAC_NAMESPACE
1413 } // namespace GiNaC
1414 #endif // ndef NO_GINAC_NAMESPACE