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 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
35 // CLN should not pollute the global namespace, hence we include it here
36 // instead of in some header file where it would propagate to other parts:
43 #ifndef NO_GINAC_NAMESPACE
45 #endif // ndef NO_GINAC_NAMESPACE
47 // linker has no problems finding text symbols for numerator or denominator
51 // default constructor, destructor, copy constructor assignment
52 // operator and helpers
57 /** default ctor. Numerically it initializes to an integer zero. */
58 numeric::numeric() : basic(TINFO_numeric)
60 debugmsg("numeric default constructor", LOGLEVEL_CONSTRUCT);
64 setflag(status_flags::evaluated|
65 status_flags::hash_calculated);
70 debugmsg("numeric destructor" ,LOGLEVEL_DESTRUCT);
74 numeric::numeric(numeric const & other)
76 debugmsg("numeric copy constructor", LOGLEVEL_CONSTRUCT);
80 numeric const & numeric::operator=(numeric const & other)
82 debugmsg("numeric operator=", LOGLEVEL_ASSIGNMENT);
92 void numeric::copy(numeric const & other)
95 value = new cl_N(*other.value);
98 void numeric::destroy(bool call_parent)
101 if (call_parent) basic::destroy(call_parent);
105 // other constructors
110 numeric::numeric(int i) : basic(TINFO_numeric)
112 debugmsg("numeric constructor from int",LOGLEVEL_CONSTRUCT);
113 // Not the whole int-range is available if we don't cast to long
114 // first. This is due to the behaviour of the cl_I-ctor, which
115 // emphasizes efficiency:
116 value = new cl_I((long) i);
118 setflag(status_flags::evaluated|
119 status_flags::hash_calculated);
122 numeric::numeric(unsigned int i) : basic(TINFO_numeric)
124 debugmsg("numeric constructor from uint",LOGLEVEL_CONSTRUCT);
125 // Not the whole uint-range is available if we don't cast to ulong
126 // first. This is due to the behaviour of the cl_I-ctor, which
127 // emphasizes efficiency:
128 value = new cl_I((unsigned long)i);
130 setflag(status_flags::evaluated|
131 status_flags::hash_calculated);
134 numeric::numeric(long i) : basic(TINFO_numeric)
136 debugmsg("numeric constructor from long",LOGLEVEL_CONSTRUCT);
139 setflag(status_flags::evaluated|
140 status_flags::hash_calculated);
143 numeric::numeric(unsigned long i) : basic(TINFO_numeric)
145 debugmsg("numeric constructor from ulong",LOGLEVEL_CONSTRUCT);
148 setflag(status_flags::evaluated|
149 status_flags::hash_calculated);
152 /** Ctor for rational numerics a/b.
154 * @exception overflow_error (division by zero) */
155 numeric::numeric(long numer, long denom) : basic(TINFO_numeric)
157 debugmsg("numeric constructor from long/long",LOGLEVEL_CONSTRUCT);
159 throw (std::overflow_error("division by zero"));
160 value = new cl_I(numer);
161 *value = *value / cl_I(denom);
163 setflag(status_flags::evaluated|
164 status_flags::hash_calculated);
167 numeric::numeric(double d) : basic(TINFO_numeric)
169 debugmsg("numeric constructor from double",LOGLEVEL_CONSTRUCT);
170 // We really want to explicitly use the type cl_LF instead of the
171 // more general cl_F, since that would give us a cl_DF only which
172 // will not be promoted to cl_LF if overflow occurs:
174 *value = cl_float(d, cl_default_float_format);
176 setflag(status_flags::evaluated|
177 status_flags::hash_calculated);
180 numeric::numeric(char const *s) : basic(TINFO_numeric)
181 { // MISSING: treatment of complex and ints and rationals.
182 debugmsg("numeric constructor from string",LOGLEVEL_CONSTRUCT);
184 value = new cl_LF(s);
188 setflag(status_flags::evaluated|
189 status_flags::hash_calculated);
192 /** Ctor from CLN types. This is for the initiated user or internal use
194 numeric::numeric(cl_N const & z) : basic(TINFO_numeric)
196 debugmsg("numeric constructor from cl_N", LOGLEVEL_CONSTRUCT);
199 setflag(status_flags::evaluated|
200 status_flags::hash_calculated);
204 // functions overriding virtual functions from bases classes
209 basic * numeric::duplicate() const
211 debugmsg("numeric duplicate", LOGLEVEL_DUPLICATE);
212 return new numeric(*this);
215 // The method printraw doesn't do much, it simply uses CLN's operator<<() for
216 // output, which is ugly but reliable. Examples:
218 void numeric::printraw(ostream & os) const
220 debugmsg("numeric printraw", LOGLEVEL_PRINT);
221 os << "numeric(" << *value << ")";
224 // The method print adds to the output so it blends more consistently together
225 // with the other routines and produces something compatible to Maple input.
226 void numeric::print(ostream & os, unsigned upper_precedence) const
228 debugmsg("numeric print", LOGLEVEL_PRINT);
230 // case 1, real: x or -x
231 if ((precedence<=upper_precedence) && (!is_pos_integer())) {
232 os << "(" << *value << ")";
237 // case 2, imaginary: y*I or -y*I
238 if (realpart(*value) == 0) {
239 if ((precedence<=upper_precedence) && (imagpart(*value) < 0)) {
240 if (imagpart(*value) == -1) {
243 os << "(" << imagpart(*value) << "*I)";
246 if (imagpart(*value) == 1) {
249 if (imagpart (*value) == -1) {
252 os << imagpart(*value) << "*I";
257 // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I
258 if (precedence <= upper_precedence) os << "(";
259 os << realpart(*value);
260 if (imagpart(*value) < 0) {
261 if (imagpart(*value) == -1) {
264 os << imagpart(*value) << "*I";
267 if (imagpart(*value) == 1) {
270 os << "+" << imagpart(*value) << "*I";
273 if (precedence <= upper_precedence) os << ")";
278 bool numeric::info(unsigned inf) const
281 case info_flags::numeric:
282 case info_flags::polynomial:
283 case info_flags::rational_function:
285 case info_flags::real:
287 case info_flags::rational:
288 case info_flags::rational_polynomial:
289 return is_rational();
290 case info_flags::integer:
291 case info_flags::integer_polynomial:
293 case info_flags::positive:
294 return is_positive();
295 case info_flags::negative:
296 return is_negative();
297 case info_flags::nonnegative:
298 return compare(numZERO())>=0;
299 case info_flags::posint:
300 return is_pos_integer();
301 case info_flags::negint:
302 return is_integer() && (compare(numZERO())<0);
303 case info_flags::nonnegint:
304 return is_nonneg_integer();
305 case info_flags::even:
307 case info_flags::odd:
309 case info_flags::prime:
315 /** Cast numeric into a floating-point object. For example exact numeric(1) is
316 * returned as a 1.0000000000000000000000 and so on according to how Digits is
319 * @param level ignored, but needed for overriding basic::evalf.
320 * @return an ex-handle to a numeric. */
321 ex numeric::evalf(int level) const
323 // level can safely be discarded for numeric objects.
324 return numeric(cl_float(1.0, cl_default_float_format) * (*value)); // -> CLN
329 int numeric::compare_same_type(basic const & other) const
331 GINAC_ASSERT(is_exactly_of_type(other, numeric));
332 numeric const & o = static_cast<numeric &>(const_cast<basic &>(other));
334 if (*value == *o.value) {
341 bool numeric::is_equal_same_type(basic const & other) const
343 GINAC_ASSERT(is_exactly_of_type(other,numeric));
344 numeric const *o = static_cast<numeric const *>(&other);
350 unsigned numeric::calchash(void) const
352 double d=to_double();
358 return 0x88000000U+s*unsigned(d/0x07FF0000);
364 // new virtual functions which can be overridden by derived classes
370 // non-virtual functions in this class
375 /** Numerical addition method. Adds argument to *this and returns result as
376 * a new numeric object. */
377 numeric numeric::add(numeric const & other) const
379 return numeric((*value)+(*other.value));
382 /** Numerical subtraction method. Subtracts argument from *this and returns
383 * result as a new numeric object. */
384 numeric numeric::sub(numeric const & other) const
386 return numeric((*value)-(*other.value));
389 /** Numerical multiplication method. Multiplies *this and argument and returns
390 * result as a new numeric object. */
391 numeric numeric::mul(numeric const & other) const
393 static const numeric * numONEp=&numONE();
396 } else if (&other==numONEp) {
399 return numeric((*value)*(*other.value));
402 /** Numerical division method. Divides *this by argument and returns result as
403 * a new numeric object.
405 * @exception overflow_error (division by zero) */
406 numeric numeric::div(numeric const & other) const
408 if (zerop(*other.value))
409 throw (std::overflow_error("division by zero"));
410 return numeric((*value)/(*other.value));
413 numeric numeric::power(numeric const & other) const
415 static const numeric * numONEp=&numONE();
416 if (&other==numONEp) {
419 if (zerop(*value) && other.is_real() && minusp(realpart(*other.value)))
420 throw (std::overflow_error("division by zero"));
421 return numeric(expt(*value,*other.value));
424 /** Inverse of a number. */
425 numeric numeric::inverse(void) const
427 return numeric(recip(*value)); // -> CLN
430 numeric const & numeric::add_dyn(numeric const & other) const
432 return static_cast<numeric const &>((new numeric((*value)+(*other.value)))->
433 setflag(status_flags::dynallocated));
436 numeric const & numeric::sub_dyn(numeric const & other) const
438 return static_cast<numeric const &>((new numeric((*value)-(*other.value)))->
439 setflag(status_flags::dynallocated));
442 numeric const & numeric::mul_dyn(numeric const & other) const
444 static const numeric * numONEp=&numONE();
447 } else if (&other==numONEp) {
450 return static_cast<numeric const &>((new numeric((*value)*(*other.value)))->
451 setflag(status_flags::dynallocated));
454 numeric const & numeric::div_dyn(numeric const & other) const
456 if (zerop(*other.value))
457 throw (std::overflow_error("division by zero"));
458 return static_cast<numeric const &>((new numeric((*value)/(*other.value)))->
459 setflag(status_flags::dynallocated));
462 numeric const & numeric::power_dyn(numeric const & other) const
464 static const numeric * numONEp=&numONE();
465 if (&other==numONEp) {
468 // The ifs are only a workaround for a bug in CLN. It gets stuck otherwise:
469 if ( !other.is_integer() &&
470 other.is_rational() &&
471 (*this).is_nonneg_integer() ) {
472 if ( !zerop(*value) ) {
473 return static_cast<numeric const &>((new numeric(exp(*other.value * log(*value))))->
474 setflag(status_flags::dynallocated));
476 if ( !zerop(*other.value) ) { // 0^(n/m)
477 return static_cast<numeric const &>((new numeric(0))->
478 setflag(status_flags::dynallocated));
479 } else { // raise FPE (0^0 requested)
480 return static_cast<numeric const &>((new numeric(1/(*other.value)))->
481 setflag(status_flags::dynallocated));
484 } else { // default -> CLN
485 return static_cast<numeric const &>((new numeric(expt(*value,*other.value)))->
486 setflag(status_flags::dynallocated));
490 numeric const & numeric::operator=(int i)
492 return operator=(numeric(i));
495 numeric const & numeric::operator=(unsigned int i)
497 return operator=(numeric(i));
500 numeric const & numeric::operator=(long i)
502 return operator=(numeric(i));
505 numeric const & numeric::operator=(unsigned long i)
507 return operator=(numeric(i));
510 numeric const & numeric::operator=(double d)
512 return operator=(numeric(d));
515 numeric const & numeric::operator=(char const * s)
517 return operator=(numeric(s));
520 /** Return the complex half-plane (left or right) in which the number lies.
521 * csgn(x)==0 for x==0, csgn(x)==1 for Re(x)>0 or Re(x)=0 and Im(x)>0,
522 * csgn(x)==-1 for Re(x)<0 or Re(x)=0 and Im(x)<0.
524 * @see numeric::compare(numeric const & other) */
525 int numeric::csgn(void) const
529 if (!zerop(realpart(*value))) {
530 if (plusp(realpart(*value)))
535 if (plusp(imagpart(*value)))
542 /** This method establishes a canonical order on all numbers. For complex
543 * numbers this is not possible in a mathematically consistent way but we need
544 * to establish some order and it ought to be fast. So we simply define it
545 * to be compatible with our method csgn.
547 * @return csgn(*this-other)
548 * @see numeric::csgn(void) */
549 int numeric::compare(numeric const & other) const
551 // Comparing two real numbers?
552 if (is_real() && other.is_real())
553 // Yes, just compare them
554 return cl_compare(The(cl_R)(*value), The(cl_R)(*other.value));
556 // No, first compare real parts
557 cl_signean real_cmp = cl_compare(realpart(*value), realpart(*other.value));
561 return cl_compare(imagpart(*value), imagpart(*other.value));
565 bool numeric::is_equal(numeric const & other) const
567 return (*value == *other.value);
570 /** True if object is zero. */
571 bool numeric::is_zero(void) const
573 return zerop(*value); // -> CLN
576 /** True if object is not complex and greater than zero. */
577 bool numeric::is_positive(void) const
580 return plusp(The(cl_R)(*value)); // -> CLN
585 /** True if object is not complex and less than zero. */
586 bool numeric::is_negative(void) const
589 return minusp(The(cl_R)(*value)); // -> CLN
594 /** True if object is a non-complex integer. */
595 bool numeric::is_integer(void) const
597 return (bool)instanceof(*value, cl_I_ring); // -> CLN
600 /** True if object is an exact integer greater than zero. */
601 bool numeric::is_pos_integer(void) const
603 return (is_integer() &&
604 plusp(The(cl_I)(*value))); // -> CLN
607 /** True if object is an exact integer greater or equal zero. */
608 bool numeric::is_nonneg_integer(void) const
610 return (is_integer() &&
611 !minusp(The(cl_I)(*value))); // -> CLN
614 /** True if object is an exact even integer. */
615 bool numeric::is_even(void) const
617 return (is_integer() &&
618 evenp(The(cl_I)(*value))); // -> CLN
621 /** True if object is an exact odd integer. */
622 bool numeric::is_odd(void) const
624 return (is_integer() &&
625 oddp(The(cl_I)(*value))); // -> CLN
628 /** Probabilistic primality test.
630 * @return true if object is exact integer and prime. */
631 bool numeric::is_prime(void) const
633 return (is_integer() &&
634 isprobprime(The(cl_I)(*value))); // -> CLN
637 /** True if object is an exact rational number, may even be complex
638 * (denominator may be unity). */
639 bool numeric::is_rational(void) const
641 if (instanceof(*value, cl_RA_ring)) {
643 } else if (!is_real()) { // complex case, handle Q(i):
644 if ( instanceof(realpart(*value), cl_RA_ring) &&
645 instanceof(imagpart(*value), cl_RA_ring) )
651 /** True if object is a real integer, rational or float (but not complex). */
652 bool numeric::is_real(void) const
654 return (bool)instanceof(*value, cl_R_ring); // -> CLN
657 bool numeric::operator==(numeric const & other) const
659 return (*value == *other.value); // -> CLN
662 bool numeric::operator!=(numeric const & other) const
664 return (*value != *other.value); // -> CLN
667 /** Numerical comparison: less.
669 * @exception invalid_argument (complex inequality) */
670 bool numeric::operator<(numeric const & other) const
672 if ( is_real() && other.is_real() ) {
673 return (bool)(The(cl_R)(*value) < The(cl_R)(*other.value)); // -> CLN
675 throw (std::invalid_argument("numeric::operator<(): complex inequality"));
676 return false; // make compiler shut up
679 /** Numerical comparison: less or equal.
681 * @exception invalid_argument (complex inequality) */
682 bool numeric::operator<=(numeric const & other) const
684 if ( is_real() && other.is_real() ) {
685 return (bool)(The(cl_R)(*value) <= The(cl_R)(*other.value)); // -> CLN
687 throw (std::invalid_argument("numeric::operator<=(): complex inequality"));
688 return false; // make compiler shut up
691 /** Numerical comparison: greater.
693 * @exception invalid_argument (complex inequality) */
694 bool numeric::operator>(numeric const & other) const
696 if ( is_real() && other.is_real() ) {
697 return (bool)(The(cl_R)(*value) > The(cl_R)(*other.value)); // -> CLN
699 throw (std::invalid_argument("numeric::operator>(): complex inequality"));
700 return false; // make compiler shut up
703 /** Numerical comparison: greater or equal.
705 * @exception invalid_argument (complex inequality) */
706 bool numeric::operator>=(numeric const & other) const
708 if ( is_real() && other.is_real() ) {
709 return (bool)(The(cl_R)(*value) >= The(cl_R)(*other.value)); // -> CLN
711 throw (std::invalid_argument("numeric::operator>=(): complex inequality"));
712 return false; // make compiler shut up
715 /** Converts numeric types to machine's int. You should check with is_integer()
716 * if the number is really an integer before calling this method. */
717 int numeric::to_int(void) const
719 GINAC_ASSERT(is_integer());
720 return cl_I_to_int(The(cl_I)(*value));
723 /** Converts numeric types to machine's double. You should check with is_real()
724 * if the number is really not complex before calling this method. */
725 double numeric::to_double(void) const
727 GINAC_ASSERT(is_real());
728 return cl_double_approx(realpart(*value));
731 /** Real part of a number. */
732 numeric numeric::real(void) const
734 return numeric(realpart(*value)); // -> CLN
737 /** Imaginary part of a number. */
738 numeric numeric::imag(void) const
740 return numeric(imagpart(*value)); // -> CLN
744 // Unfortunately, CLN did not provide an official way to access the numerator
745 // or denominator of a rational number (cl_RA). Doing some excavations in CLN
746 // one finds how it works internally in src/rational/cl_RA.h:
747 struct cl_heap_ratio : cl_heap {
752 inline cl_heap_ratio* TheRatio (const cl_N& obj)
753 { return (cl_heap_ratio*)(obj.pointer); }
754 #endif // ndef SANE_LINKER
756 /** Numerator. Computes the numerator of rational numbers, rationalized
757 * numerator of complex if real and imaginary part are both rational numbers
758 * (i.e numer(4/3+5/6*I) == 8+5*I), the number carrying the sign in all other
760 numeric numeric::numer(void) const
763 return numeric(*this);
766 else if (instanceof(*value, cl_RA_ring)) {
767 return numeric(numerator(The(cl_RA)(*value)));
769 else if (!is_real()) { // complex case, handle Q(i):
770 cl_R r = realpart(*value);
771 cl_R i = imagpart(*value);
772 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
773 return numeric(*this);
774 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
775 return numeric(complex(r*denominator(The(cl_RA)(i)), numerator(The(cl_RA)(i))));
776 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
777 return numeric(complex(numerator(The(cl_RA)(r)), i*denominator(The(cl_RA)(r))));
778 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) {
779 cl_I s = lcm(denominator(The(cl_RA)(r)), denominator(The(cl_RA)(i)));
780 return numeric(complex(numerator(The(cl_RA)(r))*(exquo(s,denominator(The(cl_RA)(r)))),
781 numerator(The(cl_RA)(i))*(exquo(s,denominator(The(cl_RA)(i))))));
785 else if (instanceof(*value, cl_RA_ring)) {
786 return numeric(TheRatio(*value)->numerator);
788 else if (!is_real()) { // complex case, handle Q(i):
789 cl_R r = realpart(*value);
790 cl_R i = imagpart(*value);
791 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
792 return numeric(*this);
793 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
794 return numeric(complex(r*TheRatio(i)->denominator, TheRatio(i)->numerator));
795 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
796 return numeric(complex(TheRatio(r)->numerator, i*TheRatio(r)->denominator));
797 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) {
798 cl_I s = lcm(TheRatio(r)->denominator, TheRatio(i)->denominator);
799 return numeric(complex(TheRatio(r)->numerator*(exquo(s,TheRatio(r)->denominator)),
800 TheRatio(i)->numerator*(exquo(s,TheRatio(i)->denominator))));
803 #endif // def SANE_LINKER
804 // at least one float encountered
805 return numeric(*this);
808 /** Denominator. Computes the denominator of rational numbers, common integer
809 * denominator of complex if real and imaginary part are both rational numbers
810 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
811 numeric numeric::denom(void) const
817 if (instanceof(*value, cl_RA_ring)) {
818 return numeric(denominator(The(cl_RA)(*value)));
820 if (!is_real()) { // complex case, handle Q(i):
821 cl_R r = realpart(*value);
822 cl_R i = imagpart(*value);
823 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
825 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
826 return numeric(denominator(The(cl_RA)(i)));
827 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
828 return numeric(denominator(The(cl_RA)(r)));
829 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring))
830 return numeric(lcm(denominator(The(cl_RA)(r)), denominator(The(cl_RA)(i))));
833 if (instanceof(*value, cl_RA_ring)) {
834 return numeric(TheRatio(*value)->denominator);
836 if (!is_real()) { // complex case, handle Q(i):
837 cl_R r = realpart(*value);
838 cl_R i = imagpart(*value);
839 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
841 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
842 return numeric(TheRatio(i)->denominator);
843 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
844 return numeric(TheRatio(r)->denominator);
845 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring))
846 return numeric(lcm(TheRatio(r)->denominator, TheRatio(i)->denominator));
848 #endif // def SANE_LINKER
849 // at least one float encountered
853 /** Size in binary notation. For integers, this is the smallest n >= 0 such
854 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
855 * 2^(n-1) <= x < 2^n.
857 * @return number of bits (excluding sign) needed to represent that number
858 * in two's complement if it is an integer, 0 otherwise. */
859 int numeric::int_length(void) const
862 return integer_length(The(cl_I)(*value)); // -> CLN
870 // static member variables
875 unsigned numeric::precedence = 30;
881 const numeric some_numeric;
882 type_info const & typeid_numeric=typeid(some_numeric);
883 /** Imaginary unit. This is not a constant but a numeric since we are
884 * natively handing complex numbers anyways. */
885 const numeric I = numeric(complex(cl_I(0),cl_I(1)));
891 numeric const & numZERO(void)
893 const static ex eZERO = ex((new numeric(0))->setflag(status_flags::dynallocated));
894 const static numeric * nZERO = static_cast<const numeric *>(eZERO.bp);
898 numeric const & numONE(void)
900 const static ex eONE = ex((new numeric(1))->setflag(status_flags::dynallocated));
901 const static numeric * nONE = static_cast<const numeric *>(eONE.bp);
905 numeric const & numTWO(void)
907 const static ex eTWO = ex((new numeric(2))->setflag(status_flags::dynallocated));
908 const static numeric * nTWO = static_cast<const numeric *>(eTWO.bp);
912 numeric const & numTHREE(void)
914 const static ex eTHREE = ex((new numeric(3))->setflag(status_flags::dynallocated));
915 const static numeric * nTHREE = static_cast<const numeric *>(eTHREE.bp);
919 numeric const & numMINUSONE(void)
921 const static ex eMINUSONE = ex((new numeric(-1))->setflag(status_flags::dynallocated));
922 const static numeric * nMINUSONE = static_cast<const numeric *>(eMINUSONE.bp);
926 numeric const & numHALF(void)
928 const static ex eHALF = ex((new numeric(1, 2))->setflag(status_flags::dynallocated));
929 const static numeric * nHALF = static_cast<const numeric *>(eHALF.bp);
933 /** Exponential function.
935 * @return arbitrary precision numerical exp(x). */
936 numeric exp(numeric const & x)
938 return ::exp(*x.value); // -> CLN
941 /** Natural logarithm.
943 * @param z complex number
944 * @return arbitrary precision numerical log(x).
945 * @exception overflow_error (logarithmic singularity) */
946 numeric log(numeric const & z)
949 throw (std::overflow_error("log(): logarithmic singularity"));
950 return ::log(*z.value); // -> CLN
953 /** Numeric sine (trigonometric function).
955 * @return arbitrary precision numerical sin(x). */
956 numeric sin(numeric const & x)
958 return ::sin(*x.value); // -> CLN
961 /** Numeric cosine (trigonometric function).
963 * @return arbitrary precision numerical cos(x). */
964 numeric cos(numeric const & x)
966 return ::cos(*x.value); // -> CLN
969 /** Numeric tangent (trigonometric function).
971 * @return arbitrary precision numerical tan(x). */
972 numeric tan(numeric const & x)
974 return ::tan(*x.value); // -> CLN
977 /** Numeric inverse sine (trigonometric function).
979 * @return arbitrary precision numerical asin(x). */
980 numeric asin(numeric const & x)
982 return ::asin(*x.value); // -> CLN
985 /** Numeric inverse cosine (trigonometric function).
987 * @return arbitrary precision numerical acos(x). */
988 numeric acos(numeric const & x)
990 return ::acos(*x.value); // -> CLN
995 * @param z complex number
997 * @exception overflow_error (logarithmic singularity) */
998 numeric atan(numeric const & x)
1001 x.real().is_zero() &&
1002 !abs(x.imag()).is_equal(numONE()))
1003 throw (std::overflow_error("atan(): logarithmic singularity"));
1004 return ::atan(*x.value); // -> CLN
1009 * @param x real number
1010 * @param y real number
1011 * @return atan(y/x) */
1012 numeric atan(numeric const & y, numeric const & x)
1014 if (x.is_real() && y.is_real())
1015 return ::atan(realpart(*x.value), realpart(*y.value)); // -> CLN
1017 throw (std::invalid_argument("numeric::atan(): complex argument"));
1020 /** Numeric hyperbolic sine (trigonometric function).
1022 * @return arbitrary precision numerical sinh(x). */
1023 numeric sinh(numeric const & x)
1025 return ::sinh(*x.value); // -> CLN
1028 /** Numeric hyperbolic cosine (trigonometric function).
1030 * @return arbitrary precision numerical cosh(x). */
1031 numeric cosh(numeric const & x)
1033 return ::cosh(*x.value); // -> CLN
1036 /** Numeric hyperbolic tangent (trigonometric function).
1038 * @return arbitrary precision numerical tanh(x). */
1039 numeric tanh(numeric const & x)
1041 return ::tanh(*x.value); // -> CLN
1044 /** Numeric inverse hyperbolic sine (trigonometric function).
1046 * @return arbitrary precision numerical asinh(x). */
1047 numeric asinh(numeric const & x)
1049 return ::asinh(*x.value); // -> CLN
1052 /** Numeric inverse hyperbolic cosine (trigonometric function).
1054 * @return arbitrary precision numerical acosh(x). */
1055 numeric acosh(numeric const & x)
1057 return ::acosh(*x.value); // -> CLN
1060 /** Numeric inverse hyperbolic tangent (trigonometric function).
1062 * @return arbitrary precision numerical atanh(x). */
1063 numeric atanh(numeric const & x)
1065 return ::atanh(*x.value); // -> CLN
1068 /** Numeric evaluation of Riemann's Zeta function. Currently works only for
1069 * integer arguments. */
1070 numeric zeta(numeric const & x)
1073 return ::cl_zeta(x.to_int()); // -> CLN
1075 clog << "zeta(): Does anybody know good way to calculate this numerically?" << endl;
1079 /** The gamma function.
1080 * This is only a stub! */
1081 numeric gamma(numeric const & x)
1083 clog << "gamma(): Does anybody know good way to calculate this numerically?" << endl;
1087 /** The psi function (aka polygamma function).
1088 * This is only a stub! */
1089 numeric psi(numeric const & x)
1091 clog << "psi(): Does anybody know good way to calculate this numerically?" << endl;
1095 /** The psi functions (aka polygamma functions).
1096 * This is only a stub! */
1097 numeric psi(numeric const & n, numeric const & x)
1099 clog << "psi(): Does anybody know good way to calculate this numerically?" << endl;
1103 /** Factorial combinatorial function.
1105 * @exception range_error (argument must be integer >= 0) */
1106 numeric factorial(numeric const & nn)
1108 if ( !nn.is_nonneg_integer() ) {
1109 throw (std::range_error("numeric::factorial(): argument must be integer >= 0"));
1112 return numeric(::factorial(nn.to_int())); // -> CLN
1115 /** The double factorial combinatorial function. (Scarcely used, but still
1116 * useful in cases, like for exact results of Gamma(n+1/2) for instance.)
1118 * @param n integer argument >= -1
1119 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == 1 == (-1)!!
1120 * @exception range_error (argument must be integer >= -1) */
1121 numeric doublefactorial(numeric const & nn)
1123 // META-NOTE: The whole shit here will become obsolete and may be moved
1124 // out once CLN learns about double factorial, which should be as soon as
1127 // We store the results separately for even and odd arguments. This has
1128 // the advantage that we don't have to compute any even result at all if
1129 // the function is always called with odd arguments and vice versa. There
1130 // is no tradeoff involved in this, it is guaranteed to save time as well
1131 // as memory. (If this is not enough justification consider the Gamma
1132 // function of half integer arguments: it only needs odd doublefactorials.)
1133 static vector<numeric> evenresults;
1134 static int highest_evenresult = -1;
1135 static vector<numeric> oddresults;
1136 static int highest_oddresult = -1;
1138 if (nn == numeric(-1)) {
1141 if (!nn.is_nonneg_integer()) {
1142 throw (std::range_error("numeric::doublefactorial(): argument must be integer >= -1"));
1145 int n = nn.div(numTWO()).to_int();
1146 if (n <= highest_evenresult) {
1147 return evenresults[n];
1149 if (evenresults.capacity() < (unsigned)(n+1)) {
1150 evenresults.reserve(n+1);
1152 if (highest_evenresult < 0) {
1153 evenresults.push_back(numONE());
1154 highest_evenresult=0;
1156 for (int i=highest_evenresult+1; i<=n; i++) {
1157 evenresults.push_back(numeric(evenresults[i-1].mul(numeric(i*2))));
1159 highest_evenresult=n;
1160 return evenresults[n];
1162 int n = nn.sub(numONE()).div(numTWO()).to_int();
1163 if (n <= highest_oddresult) {
1164 return oddresults[n];
1166 if (oddresults.capacity() < (unsigned)n) {
1167 oddresults.reserve(n+1);
1169 if (highest_oddresult < 0) {
1170 oddresults.push_back(numONE());
1171 highest_oddresult=0;
1173 for (int i=highest_oddresult+1; i<=n; i++) {
1174 oddresults.push_back(numeric(oddresults[i-1].mul(numeric(i*2+1))));
1176 highest_oddresult=n;
1177 return oddresults[n];
1181 /** The Binomial coefficients. It computes the binomial coefficients. For
1182 * integer n and k and positive n this is the number of ways of choosing k
1183 * objects from n distinct objects. If n is negative, the formula
1184 * binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */
1185 numeric binomial(numeric const & n, numeric const & k)
1187 if (n.is_integer() && k.is_integer()) {
1188 if (n.is_nonneg_integer()) {
1189 if (k.compare(n)!=1 && k.compare(numZERO())!=-1)
1190 return numeric(::binomial(n.to_int(),k.to_int())); // -> CLN
1194 return numMINUSONE().power(k)*binomial(k-n-numONE(),k);
1198 // should really be gamma(n+1)/(gamma(r+1)/gamma(n-r+1) or a suitable limit
1199 throw (std::range_error("numeric::binomial(): don´t know how to evaluate that."));
1202 /** Bernoulli number. The nth Bernoulli number is the coefficient of x^n/n!
1203 * in the expansion of the function x/(e^x-1).
1205 * @return the nth Bernoulli number (a rational number).
1206 * @exception range_error (argument must be integer >= 0) */
1207 numeric bernoulli(numeric const & nn)
1209 if (!nn.is_integer() || nn.is_negative())
1210 throw (std::range_error("numeric::bernoulli(): argument must be integer >= 0"));
1213 if (!nn.compare(numONE()))
1214 return numeric(-1,2);
1217 // Until somebody has the Blues and comes up with a much better idea and
1218 // codes it (preferably in CLN) we make this a remembering function which
1219 // computes its results using the formula
1220 // B(nn) == - 1/(nn+1) * sum_{k=0}^{nn-1}(binomial(nn+1,k)*B(k))
1222 static vector<numeric> results;
1223 static int highest_result = -1;
1224 int n = nn.sub(numTWO()).div(numTWO()).to_int();
1225 if (n <= highest_result)
1227 if (results.capacity() < (unsigned)(n+1))
1228 results.reserve(n+1);
1230 numeric tmp; // used to store the sum
1231 for (int i=highest_result+1; i<=n; ++i) {
1232 // the first two elements:
1233 tmp = numeric(-2*i-1,2);
1234 // accumulate the remaining elements:
1235 for (int j=0; j<i; ++j)
1236 tmp += binomial(numeric(2*i+3),numeric(j*2+2))*results[j];
1237 // divide by -(nn+1) and store result:
1238 results.push_back(-tmp/numeric(2*i+3));
1244 /** Absolute value. */
1245 numeric abs(numeric const & x)
1247 return ::abs(*x.value); // -> CLN
1250 /** Modulus (in positive representation).
1251 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1252 * sign of a or is zero. This is different from Maple's modp, where the sign
1253 * of b is ignored. It is in agreement with Mathematica's Mod.
1255 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1256 * integer, 0 otherwise. */
1257 numeric mod(numeric const & a, numeric const & b)
1259 if (a.is_integer() && b.is_integer()) {
1260 return ::mod(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1263 return numZERO(); // Throw?
1267 /** Modulus (in symmetric representation).
1268 * Equivalent to Maple's mods.
1270 * @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1271 numeric smod(numeric const & a, numeric const & b)
1273 if (a.is_integer() && b.is_integer()) {
1274 cl_I b2 = The(cl_I)(ceiling1(The(cl_I)(*b.value) / 2)) - 1;
1275 return ::mod(The(cl_I)(*a.value) + b2, The(cl_I)(*b.value)) - b2;
1277 return numZERO(); // Throw?
1281 /** Numeric integer remainder.
1282 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1283 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1284 * sign of a or is zero.
1286 * @return remainder of a/b if both are integer, 0 otherwise. */
1287 numeric irem(numeric const & a, numeric const & b)
1289 if (a.is_integer() && b.is_integer()) {
1290 return ::rem(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1293 return numZERO(); // Throw?
1297 /** Numeric integer remainder.
1298 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1299 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1300 * and irem(a,b) has the sign of a or is zero.
1302 * @return remainder of a/b and quotient stored in q if both are integer,
1304 numeric irem(numeric const & a, numeric const & b, numeric & q)
1306 if (a.is_integer() && b.is_integer()) { // -> CLN
1307 cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1308 q = rem_quo.quotient;
1309 return rem_quo.remainder;
1313 return numZERO(); // Throw?
1317 /** Numeric integer quotient.
1318 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1320 * @return truncated quotient of a/b if both are integer, 0 otherwise. */
1321 numeric iquo(numeric const & a, numeric const & b)
1323 if (a.is_integer() && b.is_integer()) {
1324 return truncate1(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1326 return numZERO(); // Throw?
1330 /** Numeric integer quotient.
1331 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1332 * r == a - iquo(a,b,r)*b.
1334 * @return truncated quotient of a/b and remainder stored in r if both are
1335 * integer, 0 otherwise. */
1336 numeric iquo(numeric const & a, numeric const & b, numeric & r)
1338 if (a.is_integer() && b.is_integer()) { // -> CLN
1339 cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1340 r = rem_quo.remainder;
1341 return rem_quo.quotient;
1344 return numZERO(); // Throw?
1348 /** Numeric square root.
1349 * If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4)
1350 * should return integer 2.
1352 * @param z numeric argument
1353 * @return square root of z. Branch cut along negative real axis, the negative
1354 * real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part
1355 * where imag(z)>0. */
1356 numeric sqrt(numeric const & z)
1358 return ::sqrt(*z.value); // -> CLN
1361 /** Integer numeric square root. */
1362 numeric isqrt(numeric const & x)
1364 if (x.is_integer()) {
1366 ::isqrt(The(cl_I)(*x.value), &root); // -> CLN
1369 return numZERO(); // Throw?
1372 /** Greatest Common Divisor.
1374 * @return The GCD of two numbers if both are integer, a numerical 1
1375 * if they are not. */
1376 numeric gcd(numeric const & a, numeric const & b)
1378 if (a.is_integer() && b.is_integer())
1379 return ::gcd(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1384 /** Least Common Multiple.
1386 * @return The LCM of two numbers if both are integer, the product of those
1387 * two numbers if they are not. */
1388 numeric lcm(numeric const & a, numeric const & b)
1390 if (a.is_integer() && b.is_integer())
1391 return ::lcm(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1393 return *a.value * *b.value;
1398 return numeric(cl_pi(cl_default_float_format)); // -> CLN
1401 ex EulerGammaEvalf(void)
1403 return numeric(cl_eulerconst(cl_default_float_format)); // -> CLN
1406 ex CatalanEvalf(void)
1408 return numeric(cl_catalanconst(cl_default_float_format)); // -> CLN
1411 // It initializes to 17 digits, because in CLN cl_float_format(17) turns out to
1412 // be 61 (<64) while cl_float_format(18)=65. We want to have a cl_LF instead
1413 // of cl_SF, cl_FF or cl_DF but everything else is basically arbitrary.
1414 _numeric_digits::_numeric_digits()
1419 cl_default_float_format = cl_float_format(17);
1422 _numeric_digits& _numeric_digits::operator=(long prec)
1425 cl_default_float_format = cl_float_format(prec);
1429 _numeric_digits::operator long()
1431 return (long)digits;
1434 void _numeric_digits::print(ostream & os) const
1436 debugmsg("_numeric_digits print", LOGLEVEL_PRINT);
1440 ostream& operator<<(ostream& os, _numeric_digits const & e)
1447 // static member variables
1452 bool _numeric_digits::too_late = false;
1454 /** Accuracy in decimal digits. Only object of this type! Can be set using
1455 * assignment from C++ unsigned ints and evaluated like any built-in type. */
1456 _numeric_digits Digits;
1458 #ifndef NO_GINAC_NAMESPACE
1459 } // namespace GiNaC
1460 #endif // ndef NO_GINAC_NAMESPACE