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. */
14 // CLN should not pollute the global namespace, hence we include it here
15 // instead of in some header file where it would propagate to other parts:
22 // linker has no problems finding text symbols for numerator or denominator
26 // default constructor, destructor, copy constructor assignment
27 // operator and helpers
32 /** default ctor. Numerically it initializes to an integer zero. */
33 numeric::numeric() : basic(TINFO_NUMERIC)
35 debugmsg("numeric default constructor", LOGLEVEL_CONSTRUCT);
39 setflag(status_flags::evaluated|
40 status_flags::hash_calculated);
45 debugmsg("numeric destructor" ,LOGLEVEL_DESTRUCT);
49 numeric::numeric(numeric const & other)
51 debugmsg("numeric copy constructor", LOGLEVEL_CONSTRUCT);
55 numeric const & numeric::operator=(numeric const & other)
57 debugmsg("numeric operator=", LOGLEVEL_ASSIGNMENT);
67 void numeric::copy(numeric const & other)
70 value = new cl_N(*other.value);
73 void numeric::destroy(bool call_parent)
76 if (call_parent) basic::destroy(call_parent);
85 numeric::numeric(int i) : basic(TINFO_NUMERIC)
87 debugmsg("numeric constructor from int",LOGLEVEL_CONSTRUCT);
88 // Not the whole int-range is available if we don't cast to long
89 // first. This is due to the behaviour of the cl_I-ctor, which
90 // emphasizes efficiency:
91 value = new cl_I((long) i);
93 setflag(status_flags::evaluated|
94 status_flags::hash_calculated);
97 numeric::numeric(unsigned int i) : basic(TINFO_NUMERIC)
99 debugmsg("numeric constructor from uint",LOGLEVEL_CONSTRUCT);
100 // Not the whole uint-range is available if we don't cast to ulong
101 // first. This is due to the behaviour of the cl_I-ctor, which
102 // emphasizes efficiency:
103 value = new cl_I((unsigned long)i);
105 setflag(status_flags::evaluated|
106 status_flags::hash_calculated);
109 numeric::numeric(long i) : basic(TINFO_NUMERIC)
111 debugmsg("numeric constructor from long",LOGLEVEL_CONSTRUCT);
114 setflag(status_flags::evaluated|
115 status_flags::hash_calculated);
118 numeric::numeric(unsigned long i) : basic(TINFO_NUMERIC)
120 debugmsg("numeric constructor from ulong",LOGLEVEL_CONSTRUCT);
123 setflag(status_flags::evaluated|
124 status_flags::hash_calculated);
127 /** Ctor for rational numerics a/b.
129 * @exception overflow_error (division by zero) */
130 numeric::numeric(long numer, long denom) : basic(TINFO_NUMERIC)
132 debugmsg("numeric constructor from long/long",LOGLEVEL_CONSTRUCT);
134 throw (std::overflow_error("division by zero"));
135 value = new cl_I(numer);
136 *value = *value / cl_I(denom);
138 setflag(status_flags::evaluated|
139 status_flags::hash_calculated);
142 numeric::numeric(double d) : basic(TINFO_NUMERIC)
144 debugmsg("numeric constructor from double",LOGLEVEL_CONSTRUCT);
145 // We really want to explicitly use the type cl_LF instead of the
146 // more general cl_F, since that would give us a cl_DF only which
147 // will not be promoted to cl_LF if overflow occurs:
149 *value = cl_float(d, cl_default_float_format);
151 setflag(status_flags::evaluated|
152 status_flags::hash_calculated);
155 numeric::numeric(char const *s) : basic(TINFO_NUMERIC)
156 { // MISSING: treatment of complex and ints and rationals.
157 debugmsg("numeric constructor from string",LOGLEVEL_CONSTRUCT);
159 value = new cl_LF(s);
163 setflag(status_flags::evaluated|
164 status_flags::hash_calculated);
167 /** Ctor from CLN types. This is for the initiated user or internal use
169 numeric::numeric(cl_N const & z) : basic(TINFO_NUMERIC)
171 debugmsg("numeric constructor from cl_N", LOGLEVEL_CONSTRUCT);
174 setflag(status_flags::evaluated|
175 status_flags::hash_calculated);
179 // functions overriding virtual functions from bases classes
184 basic * numeric::duplicate() const
186 debugmsg("numeric duplicate", LOGLEVEL_DUPLICATE);
187 return new numeric(*this);
190 // The method printraw doesn't do much, it simply uses CLN's operator<<() for
191 // output, which is ugly but reliable. Examples:
193 void numeric::printraw(ostream & os) const
195 debugmsg("numeric printraw", LOGLEVEL_PRINT);
196 os << "numeric(" << *value << ")";
199 // The method print adds to the output so it blends more consistently together
200 // with the other routines and produces something compatible to Maple input.
201 void numeric::print(ostream & os, unsigned upper_precedence) const
203 debugmsg("numeric print", LOGLEVEL_PRINT);
205 // case 1, real: x or -x
206 if ((precedence<=upper_precedence) && (!is_pos_integer())) {
207 os << "(" << *value << ")";
212 // case 2, imaginary: y*I or -y*I
213 if (realpart(*value) == 0) {
214 if ((precedence<=upper_precedence) && (imagpart(*value) < 0)) {
215 if (imagpart(*value) == -1) {
218 os << "(" << imagpart(*value) << "*I)";
221 if (imagpart(*value) == 1) {
224 if (imagpart (*value) == -1) {
227 os << imagpart(*value) << "*I";
232 // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I
233 if (precedence <= upper_precedence) os << "(";
234 os << realpart(*value);
235 if (imagpart(*value) < 0) {
236 if (imagpart(*value) == -1) {
239 os << imagpart(*value) << "*I";
242 if (imagpart(*value) == 1) {
245 os << "+" << imagpart(*value) << "*I";
248 if (precedence <= upper_precedence) os << ")";
253 bool numeric::info(unsigned inf) const
256 case info_flags::numeric:
257 case info_flags::polynomial:
258 case info_flags::rational_function:
260 case info_flags::real:
262 case info_flags::rational:
263 case info_flags::rational_polynomial:
264 return is_rational();
265 case info_flags::integer:
266 case info_flags::integer_polynomial:
268 case info_flags::positive:
269 return is_positive();
270 case info_flags::negative:
271 return is_negative();
272 case info_flags::nonnegative:
273 return compare(numZERO())>=0;
274 case info_flags::posint:
275 return is_pos_integer();
276 case info_flags::negint:
277 return is_integer() && (compare(numZERO())<0);
278 case info_flags::nonnegint:
279 return is_nonneg_integer();
280 case info_flags::even:
282 case info_flags::odd:
284 case info_flags::prime:
290 /** Cast numeric into a floating-point object. For example exact numeric(1) is
291 * returned as a 1.0000000000000000000000 and so on according to how Digits is
294 * @param level ignored, but needed for overriding basic::evalf.
295 * @return an ex-handle to a numeric. */
296 ex numeric::evalf(int level) const
298 // level can safely be discarded for numeric objects.
299 return numeric(cl_float(1.0, cl_default_float_format) * (*value)); // -> CLN
304 int numeric::compare_same_type(basic const & other) const
306 ASSERT(is_exactly_of_type(other, numeric));
307 numeric const & o = static_cast<numeric &>(const_cast<basic &>(other));
309 if (*value == *o.value) {
316 bool numeric::is_equal_same_type(basic const & other) const
318 ASSERT(is_exactly_of_type(other,numeric));
319 numeric const *o = static_cast<numeric const *>(&other);
325 unsigned numeric::calchash(void) const
327 double d=to_double();
333 return 0x88000000U+s*unsigned(d/0x07FF0000);
339 // new virtual functions which can be overridden by derived classes
345 // non-virtual functions in this class
350 /** Numerical addition method. Adds argument to *this and returns result as
351 * a new numeric object. */
352 numeric numeric::add(numeric const & other) const
354 return numeric((*value)+(*other.value));
357 /** Numerical subtraction method. Subtracts argument from *this and returns
358 * result as a new numeric object. */
359 numeric numeric::sub(numeric const & other) const
361 return numeric((*value)-(*other.value));
364 /** Numerical multiplication method. Multiplies *this and argument and returns
365 * result as a new numeric object. */
366 numeric numeric::mul(numeric const & other) const
368 static const numeric * numONEp=&numONE();
371 } else if (&other==numONEp) {
374 return numeric((*value)*(*other.value));
377 /** Numerical division method. Divides *this by argument and returns result as
378 * a new numeric object.
380 * @exception overflow_error (division by zero) */
381 numeric numeric::div(numeric const & other) const
383 if (zerop(*other.value))
384 throw (std::overflow_error("division by zero"));
385 return numeric((*value)/(*other.value));
388 numeric numeric::power(numeric const & other) const
390 static const numeric * numONEp=&numONE();
391 if (&other==numONEp) {
394 if (zerop(*value) && other.is_real() && minusp(realpart(*other.value)))
395 throw (std::overflow_error("division by zero"));
396 return numeric(expt(*value,*other.value));
399 /** Inverse of a number. */
400 numeric numeric::inverse(void) const
402 return numeric(recip(*value)); // -> CLN
405 numeric const & numeric::add_dyn(numeric const & other) const
407 return static_cast<numeric const &>((new numeric((*value)+(*other.value)))->
408 setflag(status_flags::dynallocated));
411 numeric const & numeric::sub_dyn(numeric const & other) const
413 return static_cast<numeric const &>((new numeric((*value)-(*other.value)))->
414 setflag(status_flags::dynallocated));
417 numeric const & numeric::mul_dyn(numeric const & other) const
419 static const numeric * numONEp=&numONE();
422 } else if (&other==numONEp) {
425 return static_cast<numeric const &>((new numeric((*value)*(*other.value)))->
426 setflag(status_flags::dynallocated));
429 numeric const & numeric::div_dyn(numeric const & other) const
431 if (zerop(*other.value))
432 throw (std::overflow_error("division by zero"));
433 return static_cast<numeric const &>((new numeric((*value)/(*other.value)))->
434 setflag(status_flags::dynallocated));
437 numeric const & numeric::power_dyn(numeric const & other) const
439 static const numeric * numONEp=&numONE();
440 if (&other==numONEp) {
443 // The ifs are only a workaround for a bug in CLN. It gets stuck otherwise:
444 if ( !other.is_integer() &&
445 other.is_rational() &&
446 (*this).is_nonneg_integer() ) {
447 if ( !zerop(*value) ) {
448 return static_cast<numeric const &>((new numeric(exp(*other.value * log(*value))))->
449 setflag(status_flags::dynallocated));
451 if ( !zerop(*other.value) ) { // 0^(n/m)
452 return static_cast<numeric const &>((new numeric(0))->
453 setflag(status_flags::dynallocated));
454 } else { // raise FPE (0^0 requested)
455 return static_cast<numeric const &>((new numeric(1/(*other.value)))->
456 setflag(status_flags::dynallocated));
459 } else { // default -> CLN
460 return static_cast<numeric const &>((new numeric(expt(*value,*other.value)))->
461 setflag(status_flags::dynallocated));
465 numeric const & numeric::operator=(int i)
467 return operator=(numeric(i));
470 numeric const & numeric::operator=(unsigned int i)
472 return operator=(numeric(i));
475 numeric const & numeric::operator=(long i)
477 return operator=(numeric(i));
480 numeric const & numeric::operator=(unsigned long i)
482 return operator=(numeric(i));
485 numeric const & numeric::operator=(double d)
487 return operator=(numeric(d));
490 numeric const & numeric::operator=(char const * s)
492 return operator=(numeric(s));
495 /** This method establishes a canonical order on all numbers. For complex
496 * numbers this is not possible in a mathematically consistent way but we need
497 * to establish some order and it ought to be fast. So we simply define it
498 * similar to Maple's csgn. */
499 int numeric::compare(numeric const & other) const
501 // Comparing two real numbers?
502 if (is_real() && other.is_real())
503 // Yes, just compare them
504 return cl_compare(The(cl_R)(*value), The(cl_R)(*other.value));
506 // No, first compare real parts
507 cl_signean real_cmp = cl_compare(realpart(*value), realpart(*other.value));
511 return cl_compare(imagpart(*value), imagpart(*other.value));
515 bool numeric::is_equal(numeric const & other) const
517 return (*value == *other.value);
520 /** True if object is zero. */
521 bool numeric::is_zero(void) const
523 return zerop(*value); // -> CLN
526 /** True if object is not complex and greater than zero. */
527 bool numeric::is_positive(void) const
530 return plusp(The(cl_R)(*value)); // -> CLN
535 /** True if object is not complex and less than zero. */
536 bool numeric::is_negative(void) const
539 return minusp(The(cl_R)(*value)); // -> CLN
544 /** True if object is a non-complex integer. */
545 bool numeric::is_integer(void) const
547 return (bool)instanceof(*value, cl_I_ring); // -> CLN
550 /** True if object is an exact integer greater than zero. */
551 bool numeric::is_pos_integer(void) const
553 return (is_integer() &&
554 plusp(The(cl_I)(*value))); // -> CLN
557 /** True if object is an exact integer greater or equal zero. */
558 bool numeric::is_nonneg_integer(void) const
560 return (is_integer() &&
561 !minusp(The(cl_I)(*value))); // -> CLN
564 /** True if object is an exact even integer. */
565 bool numeric::is_even(void) const
567 return (is_integer() &&
568 evenp(The(cl_I)(*value))); // -> CLN
571 /** True if object is an exact odd integer. */
572 bool numeric::is_odd(void) const
574 return (is_integer() &&
575 oddp(The(cl_I)(*value))); // -> CLN
578 /** Probabilistic primality test.
580 * @return true if object is exact integer and prime. */
581 bool numeric::is_prime(void) const
583 return (is_integer() &&
584 isprobprime(The(cl_I)(*value))); // -> CLN
587 /** True if object is an exact rational number, may even be complex
588 * (denominator may be unity). */
589 bool numeric::is_rational(void) const
591 if (instanceof(*value, cl_RA_ring)) {
593 } else if (!is_real()) { // complex case, handle Q(i):
594 if ( instanceof(realpart(*value), cl_RA_ring) &&
595 instanceof(imagpart(*value), cl_RA_ring) )
601 /** True if object is a real integer, rational or float (but not complex). */
602 bool numeric::is_real(void) const
604 return (bool)instanceof(*value, cl_R_ring); // -> CLN
607 bool numeric::operator==(numeric const & other) const
609 return (*value == *other.value); // -> CLN
612 bool numeric::operator!=(numeric const & other) const
614 return (*value != *other.value); // -> CLN
617 /** Numerical comparison: less.
619 * @exception invalid_argument (complex inequality) */
620 bool numeric::operator<(numeric const & other) const
622 if ( is_real() && other.is_real() ) {
623 return (bool)(The(cl_R)(*value) < The(cl_R)(*other.value)); // -> CLN
625 throw (std::invalid_argument("numeric::operator<(): complex inequality"));
626 return false; // make compiler shut up
629 /** Numerical comparison: less or equal.
631 * @exception invalid_argument (complex inequality) */
632 bool numeric::operator<=(numeric const & other) const
634 if ( is_real() && other.is_real() ) {
635 return (bool)(The(cl_R)(*value) <= The(cl_R)(*other.value)); // -> CLN
637 throw (std::invalid_argument("numeric::operator<=(): complex inequality"));
638 return false; // make compiler shut up
641 /** Numerical comparison: greater.
643 * @exception invalid_argument (complex inequality) */
644 bool numeric::operator>(numeric const & other) const
646 if ( is_real() && other.is_real() ) {
647 return (bool)(The(cl_R)(*value) > The(cl_R)(*other.value)); // -> CLN
649 throw (std::invalid_argument("numeric::operator>(): complex inequality"));
650 return false; // make compiler shut up
653 /** Numerical comparison: greater or equal.
655 * @exception invalid_argument (complex inequality) */
656 bool numeric::operator>=(numeric const & other) const
658 if ( is_real() && other.is_real() ) {
659 return (bool)(The(cl_R)(*value) >= The(cl_R)(*other.value)); // -> CLN
661 throw (std::invalid_argument("numeric::operator>=(): complex inequality"));
662 return false; // make compiler shut up
665 /** Converts numeric types to machine's int. You should check with is_integer()
666 * if the number is really an integer before calling this method. */
667 int numeric::to_int(void) const
669 ASSERT(is_integer());
670 return cl_I_to_int(The(cl_I)(*value));
673 /** Converts numeric types to machine's double. You should check with is_real()
674 * if the number is really not complex before calling this method. */
675 double numeric::to_double(void) const
678 return cl_double_approx(realpart(*value));
681 /** Real part of a number. */
682 numeric numeric::real(void) const
684 return numeric(realpart(*value)); // -> CLN
687 /** Imaginary part of a number. */
688 numeric numeric::imag(void) const
690 return numeric(imagpart(*value)); // -> CLN
694 // Unfortunately, CLN did not provide an official way to access the numerator
695 // or denominator of a rational number (cl_RA). Doing some excavations in CLN
696 // one finds how it works internally in src/rational/cl_RA.h:
697 struct cl_heap_ratio : cl_heap {
702 inline cl_heap_ratio* TheRatio (const cl_N& obj)
703 { return (cl_heap_ratio*)(obj.pointer); }
704 #endif // ndef SANE_LINKER
706 /** Numerator. Computes the numerator of rational numbers, rationalized
707 * numerator of complex if real and imaginary part are both rational numbers
708 * (i.e numer(4/3+5/6*I) == 8+5*I), the number itself in all other cases. */
709 numeric numeric::numer(void) const
712 return numeric(*this);
715 else if (instanceof(*value, cl_RA_ring)) {
716 return numeric(numerator(The(cl_RA)(*value)));
718 else if (!is_real()) { // complex case, handle Q(i):
719 cl_R r = realpart(*value);
720 cl_R i = imagpart(*value);
721 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
722 return numeric(*this);
723 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
724 return numeric(complex(r*denominator(The(cl_RA)(i)), numerator(The(cl_RA)(i))));
725 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
726 return numeric(complex(numerator(The(cl_RA)(r)), i*denominator(The(cl_RA)(r))));
727 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) {
728 cl_I s = lcm(denominator(The(cl_RA)(r)), denominator(The(cl_RA)(i)));
729 return numeric(complex(numerator(The(cl_RA)(r))*(exquo(s,denominator(The(cl_RA)(r)))),
730 numerator(The(cl_RA)(i))*(exquo(s,denominator(The(cl_RA)(i))))));
734 else if (instanceof(*value, cl_RA_ring)) {
735 return numeric(TheRatio(*value)->numerator);
737 else if (!is_real()) { // complex case, handle Q(i):
738 cl_R r = realpart(*value);
739 cl_R i = imagpart(*value);
740 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
741 return numeric(*this);
742 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
743 return numeric(complex(r*TheRatio(i)->denominator, TheRatio(i)->numerator));
744 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
745 return numeric(complex(TheRatio(r)->numerator, i*TheRatio(r)->denominator));
746 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) {
747 cl_I s = lcm(TheRatio(r)->denominator, TheRatio(i)->denominator);
748 return numeric(complex(TheRatio(r)->numerator*(exquo(s,TheRatio(r)->denominator)),
749 TheRatio(i)->numerator*(exquo(s,TheRatio(i)->denominator))));
752 #endif // def SANE_LINKER
753 // at least one float encountered
754 return numeric(*this);
757 /** Denominator. Computes the denominator of rational numbers, common integer
758 * denominator of complex if real and imaginary part are both rational numbers
759 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
760 numeric numeric::denom(void) const
766 if (instanceof(*value, cl_RA_ring)) {
767 return numeric(denominator(The(cl_RA)(*value)));
769 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))
774 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
775 return numeric(denominator(The(cl_RA)(i)));
776 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
777 return numeric(denominator(The(cl_RA)(r)));
778 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring))
779 return numeric(lcm(denominator(The(cl_RA)(r)), denominator(The(cl_RA)(i))));
782 if (instanceof(*value, cl_RA_ring)) {
783 return numeric(TheRatio(*value)->denominator);
785 if (!is_real()) { // complex case, handle Q(i):
786 cl_R r = realpart(*value);
787 cl_R i = imagpart(*value);
788 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
790 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
791 return numeric(TheRatio(i)->denominator);
792 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
793 return numeric(TheRatio(r)->denominator);
794 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring))
795 return numeric(lcm(TheRatio(r)->denominator, TheRatio(i)->denominator));
797 #endif // def SANE_LINKER
798 // at least one float encountered
802 /** Size in binary notation. For integers, this is the smallest n >= 0 such
803 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
804 * 2^(n-1) <= x < 2^n.
806 * @return number of bits (excluding sign) needed to represent that number
807 * in two's complement if it is an integer, 0 otherwise. */
808 int numeric::int_length(void) const
811 return integer_length(The(cl_I)(*value)); // -> CLN
819 // static member variables
824 unsigned numeric::precedence = 30;
830 const numeric some_numeric;
831 type_info const & typeid_numeric=typeid(some_numeric);
832 /** Imaginary unit. This is not a constant but a numeric since we are
833 * natively handing complex numbers anyways. */
834 const numeric I = (complex(cl_I(0),cl_I(1)));
840 numeric const & numZERO(void)
842 const static ex eZERO = ex((new numeric(0))->setflag(status_flags::dynallocated));
843 const static numeric * nZERO = static_cast<const numeric *>(eZERO.bp);
847 numeric const & numONE(void)
849 const static ex eONE = ex((new numeric(1))->setflag(status_flags::dynallocated));
850 const static numeric * nONE = static_cast<const numeric *>(eONE.bp);
854 numeric const & numTWO(void)
856 const static ex eTWO = ex((new numeric(2))->setflag(status_flags::dynallocated));
857 const static numeric * nTWO = static_cast<const numeric *>(eTWO.bp);
861 numeric const & numTHREE(void)
863 const static ex eTHREE = ex((new numeric(3))->setflag(status_flags::dynallocated));
864 const static numeric * nTHREE = static_cast<const numeric *>(eTHREE.bp);
868 numeric const & numMINUSONE(void)
870 const static ex eMINUSONE = ex((new numeric(-1))->setflag(status_flags::dynallocated));
871 const static numeric * nMINUSONE = static_cast<const numeric *>(eMINUSONE.bp);
875 numeric const & numHALF(void)
877 const static ex eHALF = ex((new numeric(1, 2))->setflag(status_flags::dynallocated));
878 const static numeric * nHALF = static_cast<const numeric *>(eHALF.bp);
882 /** Exponential function.
884 * @return arbitrary precision numerical exp(x). */
885 numeric exp(numeric const & x)
887 return exp(*x.value); // -> CLN
890 /** Natural logarithm.
892 * @param z complex number
893 * @return arbitrary precision numerical log(x).
894 * @exception overflow_error (logarithmic singularity) */
895 numeric log(numeric const & z)
898 throw (std::overflow_error("log(): logarithmic singularity"));
899 return log(*z.value); // -> CLN
902 /** Numeric sine (trigonometric function).
904 * @return arbitrary precision numerical sin(x). */
905 numeric sin(numeric const & x)
907 return sin(*x.value); // -> CLN
910 /** Numeric cosine (trigonometric function).
912 * @return arbitrary precision numerical cos(x). */
913 numeric cos(numeric const & x)
915 return cos(*x.value); // -> CLN
918 /** Numeric tangent (trigonometric function).
920 * @return arbitrary precision numerical tan(x). */
921 numeric tan(numeric const & x)
923 return tan(*x.value); // -> CLN
926 /** Numeric inverse sine (trigonometric function).
928 * @return arbitrary precision numerical asin(x). */
929 numeric asin(numeric const & x)
931 return asin(*x.value); // -> CLN
934 /** Numeric inverse cosine (trigonometric function).
936 * @return arbitrary precision numerical acos(x). */
937 numeric acos(numeric const & x)
939 return acos(*x.value); // -> CLN
944 * @param z complex number
946 * @exception overflow_error (logarithmic singularity) */
947 numeric atan(numeric const & x)
950 x.real().is_zero() &&
951 !abs(x.imag()).is_equal(numONE()))
952 throw (std::overflow_error("atan(): logarithmic singularity"));
953 return atan(*x.value); // -> CLN
958 * @param x real number
959 * @param y real number
960 * @return atan(y/x) */
961 numeric atan(numeric const & y, numeric const & x)
963 if (x.is_real() && y.is_real())
964 return atan(realpart(*x.value), realpart(*y.value)); // -> CLN
966 throw (std::invalid_argument("numeric::atan(): complex argument"));
969 /** Numeric hyperbolic sine (trigonometric function).
971 * @return arbitrary precision numerical sinh(x). */
972 numeric sinh(numeric const & x)
974 return sinh(*x.value); // -> CLN
977 /** Numeric hyperbolic cosine (trigonometric function).
979 * @return arbitrary precision numerical cosh(x). */
980 numeric cosh(numeric const & x)
982 return cosh(*x.value); // -> CLN
985 /** Numeric hyperbolic tangent (trigonometric function).
987 * @return arbitrary precision numerical tanh(x). */
988 numeric tanh(numeric const & x)
990 return tanh(*x.value); // -> CLN
993 /** Numeric inverse hyperbolic sine (trigonometric function).
995 * @return arbitrary precision numerical asinh(x). */
996 numeric asinh(numeric const & x)
998 return asinh(*x.value); // -> CLN
1001 /** Numeric inverse hyperbolic cosine (trigonometric function).
1003 * @return arbitrary precision numerical acosh(x). */
1004 numeric acosh(numeric const & x)
1006 return acosh(*x.value); // -> CLN
1009 /** Numeric inverse hyperbolic tangent (trigonometric function).
1011 * @return arbitrary precision numerical atanh(x). */
1012 numeric atanh(numeric const & x)
1014 return atanh(*x.value); // -> CLN
1017 /** The gamma function.
1018 * stub stub stub stub stub stub! */
1019 numeric gamma(numeric const & x)
1021 clog << "gamma(): Nobody expects the Spanish inquisition" << endl;
1025 /** Factorial combinatorial function.
1027 * @exception range_error (argument must be integer >= 0) */
1028 numeric factorial(numeric const & nn)
1030 if ( !nn.is_nonneg_integer() ) {
1031 throw (std::range_error("numeric::factorial(): argument must be integer >= 0"));
1034 return numeric(factorial(nn.to_int())); // -> CLN
1037 /** The double factorial combinatorial function. (Scarcely used, but still
1038 * useful in cases, like for exact results of Gamma(n+1/2) for instance.)
1040 * @param n integer argument >= -1
1041 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == 1 == (-1)!!
1042 * @exception range_error (argument must be integer >= -1) */
1043 numeric doublefactorial(numeric const & nn)
1045 // We store the results separately for even and odd arguments. This has
1046 // the advantage that we don't have to compute any even result at all if
1047 // the function is always called with odd arguments and vice versa. There
1048 // is no tradeoff involved in this, it is guaranteed to save time as well
1049 // as memory. (If this is not enough justification consider the Gamma
1050 // function of half integer arguments: it only needs odd doublefactorials.)
1051 static vector<numeric> evenresults;
1052 static int highest_evenresult = -1;
1053 static vector<numeric> oddresults;
1054 static int highest_oddresult = -1;
1056 if ( nn == numeric(-1) ) {
1059 if ( !nn.is_nonneg_integer() ) {
1060 throw (std::range_error("numeric::doublefactorial(): argument must be integer >= -1"));
1062 if ( nn.is_even() ) {
1063 int n = nn.div(numTWO()).to_int();
1064 if ( n <= highest_evenresult ) {
1065 return evenresults[n];
1067 if ( evenresults.capacity() < (unsigned)(n+1) ) {
1068 evenresults.reserve(n+1);
1070 if ( highest_evenresult < 0 ) {
1071 evenresults.push_back(numONE());
1072 highest_evenresult=0;
1074 for (int i=highest_evenresult+1; i<=n; i++) {
1075 evenresults.push_back(numeric(evenresults[i-1].mul(numeric(i*2))));
1077 highest_evenresult=n;
1078 return evenresults[n];
1080 int n = nn.sub(numONE()).div(numTWO()).to_int();
1081 if ( n <= highest_oddresult ) {
1082 return oddresults[n];
1084 if ( oddresults.capacity() < (unsigned)n ) {
1085 oddresults.reserve(n+1);
1087 if ( highest_oddresult < 0 ) {
1088 oddresults.push_back(numONE());
1089 highest_oddresult=0;
1091 for (int i=highest_oddresult+1; i<=n; i++) {
1092 oddresults.push_back(numeric(oddresults[i-1].mul(numeric(i*2+1))));
1094 highest_oddresult=n;
1095 return oddresults[n];
1099 /** The Binomial function. It computes the binomial coefficients. If the
1100 * arguments are both nonnegative integers and 0 <= k <= n, then
1101 * binomial(n, k) = n!/k!/(n-k)! which is the number of ways of choosing k
1102 * objects from n distinct objects. If k > n, then binomial(n,k) returns 0. */
1103 numeric binomial(numeric const & n, numeric const & k)
1105 if (n.is_nonneg_integer() && k.is_nonneg_integer()) {
1106 return numeric(binomial(n.to_int(),k.to_int())); // -> CLN
1108 // should really be gamma(n+1)/(gamma(r+1)/gamma(n-r+1)
1111 // return factorial(n).div(factorial(k).mul(factorial(n.sub(k))));
1114 /** Absolute value. */
1115 numeric abs(numeric const & x)
1117 return abs(*x.value); // -> CLN
1120 /** Modulus (in positive representation).
1121 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1122 * sign of a or is zero. This is different from Maple's modp, where the sign
1123 * of b is ignored. It is in agreement with Mathematica's Mod.
1125 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1126 * integer, 0 otherwise. */
1127 numeric mod(numeric const & a, numeric const & b)
1129 if (a.is_integer() && b.is_integer()) {
1130 return mod(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1133 return numZERO(); // Throw?
1137 /** Modulus (in symmetric representation).
1138 * Equivalent to Maple's mods.
1140 * @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1141 numeric smod(numeric const & a, numeric const & b)
1143 if (a.is_integer() && b.is_integer()) {
1144 cl_I b2 = The(cl_I)(ceiling1(The(cl_I)(*b.value) / 2)) - 1;
1145 return mod(The(cl_I)(*a.value) + b2, The(cl_I)(*b.value)) - b2;
1147 return numZERO(); // Throw?
1151 /** Numeric integer remainder.
1152 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1153 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1154 * sign of a or is zero.
1156 * @return remainder of a/b if both are integer, 0 otherwise. */
1157 numeric irem(numeric const & a, numeric const & b)
1159 if (a.is_integer() && b.is_integer()) {
1160 return rem(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1163 return numZERO(); // Throw?
1167 /** Numeric integer remainder.
1168 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1169 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1170 * and irem(a,b) has the sign of a or is zero.
1172 * @return remainder of a/b and quotient stored in q if both are integer,
1174 numeric irem(numeric const & a, numeric const & b, numeric & q)
1176 if (a.is_integer() && b.is_integer()) { // -> CLN
1177 cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1178 q = rem_quo.quotient;
1179 return rem_quo.remainder;
1183 return numZERO(); // Throw?
1187 /** Numeric integer quotient.
1188 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1190 * @return truncated quotient of a/b if both are integer, 0 otherwise. */
1191 numeric iquo(numeric const & a, numeric const & b)
1193 if (a.is_integer() && b.is_integer()) {
1194 return truncate1(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1196 return numZERO(); // Throw?
1200 /** Numeric integer quotient.
1201 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1202 * r == a - iquo(a,b,r)*b.
1204 * @return truncated quotient of a/b and remainder stored in r if both are
1205 * integer, 0 otherwise. */
1206 numeric iquo(numeric const & a, numeric const & b, numeric & r)
1208 if (a.is_integer() && b.is_integer()) { // -> CLN
1209 cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1210 r = rem_quo.remainder;
1211 return rem_quo.quotient;
1214 return numZERO(); // Throw?
1218 /** Numeric square root.
1219 * If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4)
1220 * should return integer 2.
1222 * @param z numeric argument
1223 * @return square root of z. Branch cut along negative real axis, the negative
1224 * real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part
1225 * where imag(z)>0. */
1226 numeric sqrt(numeric const & z)
1228 return sqrt(*z.value); // -> CLN
1231 /** Integer numeric square root. */
1232 numeric isqrt(numeric const & x)
1234 if (x.is_integer()) {
1236 isqrt(The(cl_I)(*x.value), &root); // -> CLN
1239 return numZERO(); // Throw?
1242 /** Greatest Common Divisor.
1244 * @return The GCD of two numbers if both are integer, a numerical 1
1245 * if they are not. */
1246 numeric gcd(numeric const & a, numeric const & b)
1248 if (a.is_integer() && b.is_integer())
1249 return gcd(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1254 /** Least Common Multiple.
1256 * @return The LCM of two numbers if both are integer, the product of those
1257 * two numbers if they are not. */
1258 numeric lcm(numeric const & a, numeric const & b)
1260 if (a.is_integer() && b.is_integer())
1261 return lcm(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1263 return *a.value * *b.value;
1268 return numeric(cl_pi(cl_default_float_format)); // -> CLN
1271 ex EulerGammaEvalf(void)
1273 return numeric(cl_eulerconst(cl_default_float_format)); // -> CLN
1276 ex CatalanEvalf(void)
1278 return numeric(cl_catalanconst(cl_default_float_format)); // -> CLN
1281 // It initializes to 17 digits, because in CLN cl_float_format(17) turns out to
1282 // be 61 (<64) while cl_float_format(18)=65. We want to have a cl_LF instead
1283 // of cl_SF, cl_FF or cl_DF but everything else is basically arbitrary.
1284 _numeric_digits::_numeric_digits()
1289 cl_default_float_format = cl_float_format(17);
1292 _numeric_digits& _numeric_digits::operator=(long prec)
1295 cl_default_float_format = cl_float_format(prec);
1299 _numeric_digits::operator long()
1301 return (long)digits;
1304 void _numeric_digits::print(ostream & os) const
1306 debugmsg("_numeric_digits print", LOGLEVEL_PRINT);
1310 ostream& operator<<(ostream& os, _numeric_digits const & e)
1317 // static member variables
1322 bool _numeric_digits::too_late = false;
1324 /** Accuracy in decimal digits. Only object of this type! Can be set using
1325 * assignment from C++ unsigned ints and evaluated like any built-in type. */
1326 _numeric_digits Digits;