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.
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 ((realpart(*value) < 0) && (precedence <= upper_precedence)) {
207 os << "(" << *value << ")";
212 // case 2, imaginary: y*I or -y*I
213 if (realpart(*value) == 0) {
214 if ((imagpart(*value) < 0) && (precedence <= upper_precedence)) {
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 ((realpart(*value) < 0) && (precedence <= upper_precedence)) {
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)";
249 os << realpart(*value);
250 if (imagpart(*value) < 0) {
251 if (imagpart(*value) == -1) {
254 os << imagpart(*value) << "*I";
257 if (imagpart(*value) == 1) {
260 os << "+" << imagpart(*value) << "*I";
268 bool numeric::info(unsigned inf) const
271 case info_flags::numeric:
272 case info_flags::polynomial:
273 case info_flags::rational_function:
275 case info_flags::real:
277 case info_flags::rational:
278 case info_flags::rational_polynomial:
279 return is_rational();
280 case info_flags::integer:
281 case info_flags::integer_polynomial:
283 case info_flags::positive:
284 return is_positive();
285 case info_flags::negative:
286 return is_negative();
287 case info_flags::nonnegative:
288 return compare(numZERO())>=0;
289 case info_flags::posint:
290 return is_pos_integer();
291 case info_flags::negint:
292 return is_integer() && (compare(numZERO())<0);
293 case info_flags::nonnegint:
294 return is_nonneg_integer();
295 case info_flags::even:
297 case info_flags::odd:
299 case info_flags::prime:
305 /** Cast numeric into a floating-point object. For example exact numeric(1) is
306 * returned as a 1.0000000000000000000000 and so on according to how Digits is
309 * @param level ignored, but needed for overriding basic::evalf.
310 * @return an ex-handle to a numeric. */
311 ex numeric::evalf(int level) const
313 // level can safely be discarded for numeric objects.
314 return numeric(cl_float(1.0, cl_default_float_format) * (*value)); // -> CLN
319 int numeric::compare_same_type(basic const & other) const
321 ASSERT(is_exactly_of_type(other, numeric));
322 numeric const & o = static_cast<numeric &>(const_cast<basic &>(other));
324 if (*value == *o.value) {
331 bool numeric::is_equal_same_type(basic const & other) const
333 ASSERT(is_exactly_of_type(other,numeric));
334 numeric const *o = static_cast<numeric const *>(&other);
340 unsigned numeric::calchash(void) const
342 double d=to_double();
348 return 0x88000000U+s*unsigned(d/0x07FF0000);
354 // new virtual functions which can be overridden by derived classes
360 // non-virtual functions in this class
365 /** Numerical addition method. Adds argument to *this and returns result as
366 * a new numeric object. */
367 numeric numeric::add(numeric const & other) const
369 return numeric((*value)+(*other.value));
372 /** Numerical subtraction method. Subtracts argument from *this and returns
373 * result as a new numeric object. */
374 numeric numeric::sub(numeric const & other) const
376 return numeric((*value)-(*other.value));
379 /** Numerical multiplication method. Multiplies *this and argument and returns
380 * result as a new numeric object. */
381 numeric numeric::mul(numeric const & other) const
383 static const numeric * numONEp=&numONE();
386 } else if (&other==numONEp) {
389 return numeric((*value)*(*other.value));
392 /** Numerical division method. Divides *this by argument and returns result as
393 * a new numeric object.
395 * @exception overflow_error (division by zero) */
396 numeric numeric::div(numeric const & other) const
398 if (zerop(*other.value))
399 throw (std::overflow_error("division by zero"));
400 return numeric((*value)/(*other.value));
403 numeric numeric::power(numeric const & other) const
405 static const numeric * numONEp=&numONE();
406 if (&other==numONEp) {
409 if (zerop(*value) && other.is_real() && minusp(realpart(*other.value)))
410 throw (std::overflow_error("division by zero"));
411 return numeric(expt(*value,*other.value));
414 /** Inverse of a number. */
415 numeric numeric::inverse(void) const
417 return numeric(recip(*value)); // -> CLN
420 numeric const & numeric::add_dyn(numeric const & other) const
422 return static_cast<numeric const &>((new numeric((*value)+(*other.value)))->
423 setflag(status_flags::dynallocated));
426 numeric const & numeric::sub_dyn(numeric const & other) const
428 return static_cast<numeric const &>((new numeric((*value)-(*other.value)))->
429 setflag(status_flags::dynallocated));
432 numeric const & numeric::mul_dyn(numeric const & other) const
434 static const numeric * numONEp=&numONE();
437 } else if (&other==numONEp) {
440 return static_cast<numeric const &>((new numeric((*value)*(*other.value)))->
441 setflag(status_flags::dynallocated));
444 numeric const & numeric::div_dyn(numeric const & other) const
446 if (zerop(*other.value))
447 throw (std::overflow_error("division by zero"));
448 return static_cast<numeric const &>((new numeric((*value)/(*other.value)))->
449 setflag(status_flags::dynallocated));
452 numeric const & numeric::power_dyn(numeric const & other) const
454 static const numeric * numONEp=&numONE();
455 if (&other==numONEp) {
458 // The ifs are only a workaround for a bug in CLN. It gets stuck otherwise:
459 if ( !other.is_integer() &&
460 other.is_rational() &&
461 (*this).is_nonneg_integer() ) {
462 if ( !zerop(*value) ) {
463 return static_cast<numeric const &>((new numeric(exp(*other.value * log(*value))))->
464 setflag(status_flags::dynallocated));
466 if ( !zerop(*other.value) ) { // 0^(n/m)
467 return static_cast<numeric const &>((new numeric(0))->
468 setflag(status_flags::dynallocated));
469 } else { // raise FPE (0^0 requested)
470 return static_cast<numeric const &>((new numeric(1/(*other.value)))->
471 setflag(status_flags::dynallocated));
474 } else { // default -> CLN
475 return static_cast<numeric const &>((new numeric(expt(*value,*other.value)))->
476 setflag(status_flags::dynallocated));
480 numeric const & numeric::operator=(int i)
482 return operator=(numeric(i));
485 numeric const & numeric::operator=(unsigned int i)
487 return operator=(numeric(i));
490 numeric const & numeric::operator=(long i)
492 return operator=(numeric(i));
495 numeric const & numeric::operator=(unsigned long i)
497 return operator=(numeric(i));
500 numeric const & numeric::operator=(double d)
502 return operator=(numeric(d));
505 numeric const & numeric::operator=(char const * s)
507 return operator=(numeric(s));
510 /** This method establishes a canonical order on all numbers. For complex
511 * numbers this is not possible in a mathematically consistent way but we need
512 * to establish some order and it ought to be fast. So we simply define it
513 * similar to Maple's csgn. */
514 int numeric::compare(numeric const & other) const
516 // Comparing two real numbers?
517 if (is_real() && other.is_real())
518 // Yes, just compare them
519 return cl_compare(The(cl_R)(*value), The(cl_R)(*other.value));
521 // No, first compare real parts
522 cl_signean real_cmp = cl_compare(realpart(*value), realpart(*other.value));
526 return cl_compare(imagpart(*value), imagpart(*other.value));
530 bool numeric::is_equal(numeric const & other) const
532 return (*value == *other.value);
535 /** True if object is zero. */
536 bool numeric::is_zero(void) const
538 return zerop(*value); // -> CLN
541 /** True if object is not complex and greater than zero. */
542 bool numeric::is_positive(void) const
545 return plusp(The(cl_R)(*value)); // -> CLN
550 /** True if object is not complex and less than zero. */
551 bool numeric::is_negative(void) const
554 return minusp(The(cl_R)(*value)); // -> CLN
559 /** True if object is a non-complex integer. */
560 bool numeric::is_integer(void) const
562 return (bool)instanceof(*value, cl_I_ring); // -> CLN
565 /** True if object is an exact integer greater than zero. */
566 bool numeric::is_pos_integer(void) const
568 return (is_integer() &&
569 plusp(The(cl_I)(*value))); // -> CLN
572 /** True if object is an exact integer greater or equal zero. */
573 bool numeric::is_nonneg_integer(void) const
575 return (is_integer() &&
576 !minusp(The(cl_I)(*value))); // -> CLN
579 /** True if object is an exact even integer. */
580 bool numeric::is_even(void) const
582 return (is_integer() &&
583 evenp(The(cl_I)(*value))); // -> CLN
586 /** True if object is an exact odd integer. */
587 bool numeric::is_odd(void) const
589 return (is_integer() &&
590 oddp(The(cl_I)(*value))); // -> CLN
593 /** Probabilistic primality test.
595 * @return true if object is exact integer and prime. */
596 bool numeric::is_prime(void) const
598 return (is_integer() &&
599 isprobprime(The(cl_I)(*value))); // -> CLN
602 /** True if object is an exact rational number, may even be complex
603 * (denominator may be unity). */
604 bool numeric::is_rational(void) const
606 if (instanceof(*value, cl_RA_ring)) {
608 } else if (!is_real()) { // complex case, handle Q(i):
609 if ( instanceof(realpart(*value), cl_RA_ring) &&
610 instanceof(imagpart(*value), cl_RA_ring) )
616 /** True if object is a real integer, rational or float (but not complex). */
617 bool numeric::is_real(void) const
619 return (bool)instanceof(*value, cl_R_ring); // -> CLN
622 bool numeric::operator==(numeric const & other) const
624 return (*value == *other.value); // -> CLN
627 bool numeric::operator!=(numeric const & other) const
629 return (*value != *other.value); // -> CLN
632 /** Numerical comparison: less.
634 * @exception invalid_argument (complex inequality) */
635 bool numeric::operator<(numeric const & other) const
637 if ( is_real() && other.is_real() ) {
638 return (bool)(The(cl_R)(*value) < The(cl_R)(*other.value)); // -> CLN
640 throw (std::invalid_argument("numeric::operator<(): complex inequality"));
641 return false; // make compiler shut up
644 /** Numerical comparison: less or equal.
646 * @exception invalid_argument (complex inequality) */
647 bool numeric::operator<=(numeric const & other) const
649 if ( is_real() && other.is_real() ) {
650 return (bool)(The(cl_R)(*value) <= The(cl_R)(*other.value)); // -> CLN
652 throw (std::invalid_argument("numeric::operator<=(): complex inequality"));
653 return false; // make compiler shut up
656 /** Numerical comparison: greater.
658 * @exception invalid_argument (complex inequality) */
659 bool numeric::operator>(numeric const & other) const
661 if ( is_real() && other.is_real() ) {
662 return (bool)(The(cl_R)(*value) > The(cl_R)(*other.value)); // -> CLN
664 throw (std::invalid_argument("numeric::operator>(): complex inequality"));
665 return false; // make compiler shut up
668 /** Numerical comparison: greater or equal.
670 * @exception invalid_argument (complex inequality) */
671 bool numeric::operator>=(numeric const & other) const
673 if ( is_real() && other.is_real() ) {
674 return (bool)(The(cl_R)(*value) >= The(cl_R)(*other.value)); // -> CLN
676 throw (std::invalid_argument("numeric::operator>=(): complex inequality"));
677 return false; // make compiler shut up
680 /** Converts numeric types to machine's int. You should check with is_integer()
681 * if the number is really an integer before calling this method. */
682 int numeric::to_int(void) const
684 ASSERT(is_integer());
685 return cl_I_to_int(The(cl_I)(*value));
688 /** Converts numeric types to machine's double. You should check with is_real()
689 * if the number is really not complex before calling this method. */
690 double numeric::to_double(void) const
693 return cl_double_approx(realpart(*value));
696 /** Real part of a number. */
697 numeric numeric::real(void) const
699 return numeric(realpart(*value)); // -> CLN
702 /** Imaginary part of a number. */
703 numeric numeric::imag(void) const
705 return numeric(imagpart(*value)); // -> CLN
709 // Unfortunately, CLN did not provide an official way to access the numerator
710 // or denominator of a rational number (cl_RA). Doing some excavations in CLN
711 // one finds how it works internally in src/rational/cl_RA.h:
712 struct cl_heap_ratio : cl_heap {
717 inline cl_heap_ratio* TheRatio (const cl_N& obj)
718 { return (cl_heap_ratio*)(obj.pointer); }
719 #endif // ndef SANE_LINKER
721 /** Numerator. Computes the numerator of rational numbers, rationalized
722 * numerator of complex if real and imaginary part are both rational numbers
723 * (i.e numer(4/3+5/6*I) == 8+5*I), the number itself in all other cases. */
724 numeric numeric::numer(void) const
727 return numeric(*this);
730 else if (instanceof(*value, cl_RA_ring)) {
731 return numeric(numerator(The(cl_RA)(*value)));
733 else if (!is_real()) { // complex case, handle Q(i):
734 cl_R r = realpart(*value);
735 cl_R i = imagpart(*value);
736 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
737 return numeric(*this);
738 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
739 return numeric(complex(r*denominator(The(cl_RA)(i)), numerator(The(cl_RA)(i))));
740 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
741 return numeric(complex(numerator(The(cl_RA)(r)), i*denominator(The(cl_RA)(r))));
742 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) {
743 cl_I s = lcm(denominator(The(cl_RA)(r)), denominator(The(cl_RA)(i)));
744 return numeric(complex(numerator(The(cl_RA)(r))*(exquo(s,denominator(The(cl_RA)(r)))),
745 numerator(The(cl_RA)(i))*(exquo(s,denominator(The(cl_RA)(i))))));
749 else if (instanceof(*value, cl_RA_ring)) {
750 return numeric(TheRatio(*value)->numerator);
752 else if (!is_real()) { // complex case, handle Q(i):
753 cl_R r = realpart(*value);
754 cl_R i = imagpart(*value);
755 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
756 return numeric(*this);
757 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
758 return numeric(complex(r*TheRatio(i)->denominator, TheRatio(i)->numerator));
759 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
760 return numeric(complex(TheRatio(r)->numerator, i*TheRatio(r)->denominator));
761 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) {
762 cl_I s = lcm(TheRatio(r)->denominator, TheRatio(i)->denominator);
763 return numeric(complex(TheRatio(r)->numerator*(exquo(s,TheRatio(r)->denominator)),
764 TheRatio(i)->numerator*(exquo(s,TheRatio(i)->denominator))));
767 #endif // def SANE_LINKER
768 // at least one float encountered
769 return numeric(*this);
772 /** Denominator. Computes the denominator of rational numbers, common integer
773 * denominator of complex if real and imaginary part are both rational numbers
774 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
775 numeric numeric::denom(void) const
781 if (instanceof(*value, cl_RA_ring)) {
782 return numeric(denominator(The(cl_RA)(*value)));
784 if (!is_real()) { // complex case, handle Q(i):
785 cl_R r = realpart(*value);
786 cl_R i = imagpart(*value);
787 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
789 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
790 return numeric(denominator(The(cl_RA)(i)));
791 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
792 return numeric(denominator(The(cl_RA)(r)));
793 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring))
794 return numeric(lcm(denominator(The(cl_RA)(r)), denominator(The(cl_RA)(i))));
797 if (instanceof(*value, cl_RA_ring)) {
798 return numeric(TheRatio(*value)->denominator);
800 if (!is_real()) { // complex case, handle Q(i):
801 cl_R r = realpart(*value);
802 cl_R i = imagpart(*value);
803 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
805 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
806 return numeric(TheRatio(i)->denominator);
807 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
808 return numeric(TheRatio(r)->denominator);
809 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring))
810 return numeric(lcm(TheRatio(r)->denominator, TheRatio(i)->denominator));
812 #endif // def SANE_LINKER
813 // at least one float encountered
817 /** Size in binary notation. For integers, this is the smallest n >= 0 such
818 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
819 * 2^(n-1) <= x < 2^n.
821 * @return number of bits (excluding sign) needed to represent that number
822 * in two's complement if it is an integer, 0 otherwise. */
823 int numeric::int_length(void) const
826 return integer_length(The(cl_I)(*value)); // -> CLN
834 // static member variables
839 unsigned numeric::precedence = 30;
845 const numeric some_numeric;
846 type_info const & typeid_numeric=typeid(some_numeric);
847 /** Imaginary unit. This is not a constant but a numeric since we are
848 * natively handing complex numbers anyways. */
849 const numeric I = (complex(cl_I(0),cl_I(1)));
855 numeric const & numZERO(void)
857 const static ex eZERO = ex((new numeric(0))->setflag(status_flags::dynallocated));
858 const static numeric * nZERO = static_cast<const numeric *>(eZERO.bp);
862 numeric const & numONE(void)
864 const static ex eONE = ex((new numeric(1))->setflag(status_flags::dynallocated));
865 const static numeric * nONE = static_cast<const numeric *>(eONE.bp);
869 numeric const & numTWO(void)
871 const static ex eTWO = ex((new numeric(2))->setflag(status_flags::dynallocated));
872 const static numeric * nTWO = static_cast<const numeric *>(eTWO.bp);
876 numeric const & numTHREE(void)
878 const static ex eTHREE = ex((new numeric(3))->setflag(status_flags::dynallocated));
879 const static numeric * nTHREE = static_cast<const numeric *>(eTHREE.bp);
883 numeric const & numMINUSONE(void)
885 const static ex eMINUSONE = ex((new numeric(-1))->setflag(status_flags::dynallocated));
886 const static numeric * nMINUSONE = static_cast<const numeric *>(eMINUSONE.bp);
890 numeric const & numHALF(void)
892 const static ex eHALF = ex((new numeric(1, 2))->setflag(status_flags::dynallocated));
893 const static numeric * nHALF = static_cast<const numeric *>(eHALF.bp);
897 /** Exponential function.
899 * @return arbitrary precision numerical exp(x). */
900 numeric exp(numeric const & x)
902 return exp(*x.value); // -> CLN
905 /** Natural logarithm.
907 * @param z complex number
908 * @return arbitrary precision numerical log(x).
909 * @exception overflow_error (logarithmic singularity) */
910 numeric log(numeric const & z)
913 throw (std::overflow_error("log(): logarithmic singularity"));
914 return log(*z.value); // -> CLN
917 /** Numeric sine (trigonometric function).
919 * @return arbitrary precision numerical sin(x). */
920 numeric sin(numeric const & x)
922 return sin(*x.value); // -> CLN
925 /** Numeric cosine (trigonometric function).
927 * @return arbitrary precision numerical cos(x). */
928 numeric cos(numeric const & x)
930 return cos(*x.value); // -> CLN
933 /** Numeric tangent (trigonometric function).
935 * @return arbitrary precision numerical tan(x). */
936 numeric tan(numeric const & x)
938 return tan(*x.value); // -> CLN
941 /** Numeric inverse sine (trigonometric function).
943 * @return arbitrary precision numerical asin(x). */
944 numeric asin(numeric const & x)
946 return asin(*x.value); // -> CLN
949 /** Numeric inverse cosine (trigonometric function).
951 * @return arbitrary precision numerical acos(x). */
952 numeric acos(numeric const & x)
954 return acos(*x.value); // -> CLN
959 * @param z complex number
961 * @exception overflow_error (logarithmic singularity) */
962 numeric atan(numeric const & x)
965 x.real().is_zero() &&
966 !abs(x.imag()).is_equal(numONE()))
967 throw (std::overflow_error("atan(): logarithmic singularity"));
968 return atan(*x.value); // -> CLN
973 * @param x real number
974 * @param y real number
975 * @return atan(y/x) */
976 numeric atan(numeric const & y, numeric const & x)
978 if (x.is_real() && y.is_real())
979 return atan(realpart(*x.value), realpart(*y.value)); // -> CLN
981 throw (std::invalid_argument("numeric::atan(): complex argument"));
984 /** Numeric hyperbolic sine (trigonometric function).
986 * @return arbitrary precision numerical sinh(x). */
987 numeric sinh(numeric const & x)
989 return sinh(*x.value); // -> CLN
992 /** Numeric hyperbolic cosine (trigonometric function).
994 * @return arbitrary precision numerical cosh(x). */
995 numeric cosh(numeric const & x)
997 return cosh(*x.value); // -> CLN
1000 /** Numeric hyperbolic tangent (trigonometric function).
1002 * @return arbitrary precision numerical tanh(x). */
1003 numeric tanh(numeric const & x)
1005 return tanh(*x.value); // -> CLN
1008 /** Numeric inverse hyperbolic sine (trigonometric function).
1010 * @return arbitrary precision numerical asinh(x). */
1011 numeric asinh(numeric const & x)
1013 return asinh(*x.value); // -> CLN
1016 /** Numeric inverse hyperbolic cosine (trigonometric function).
1018 * @return arbitrary precision numerical acosh(x). */
1019 numeric acosh(numeric const & x)
1021 return acosh(*x.value); // -> CLN
1024 /** Numeric inverse hyperbolic tangent (trigonometric function).
1026 * @return arbitrary precision numerical atanh(x). */
1027 numeric atanh(numeric const & x)
1029 return atanh(*x.value); // -> CLN
1032 /** The gamma function.
1033 * stub stub stub stub stub stub! */
1034 numeric gamma(numeric const & x)
1036 clog << "gamma(): Nobody expects the Spanish inquisition" << endl;
1040 /** Factorial combinatorial function.
1042 * @exception range_error (argument must be integer >= 0) */
1043 numeric factorial(numeric const & nn)
1045 if ( !nn.is_nonneg_integer() ) {
1046 throw (std::range_error("numeric::factorial(): argument must be integer >= 0"));
1049 return numeric(factorial(nn.to_int())); // -> CLN
1052 /** The double factorial combinatorial function. (Scarcely used, but still
1053 * useful in cases, like for exact results of Gamma(n+1/2) for instance.)
1055 * @param n integer argument >= -1
1056 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == 1 == (-1)!!
1057 * @exception range_error (argument must be integer >= -1) */
1058 numeric doublefactorial(numeric const & nn)
1060 // We store the results separately for even and odd arguments. This has
1061 // the advantage that we don't have to compute any even result at all if
1062 // the function is always called with odd arguments and vice versa. There
1063 // is no tradeoff involved in this, it is guaranteed to save time as well
1064 // as memory. (If this is not enough justification consider the Gamma
1065 // function of half integer arguments: it only needs odd doublefactorials.)
1066 static vector<numeric> evenresults;
1067 static int highest_evenresult = -1;
1068 static vector<numeric> oddresults;
1069 static int highest_oddresult = -1;
1071 if ( nn == numeric(-1) ) {
1074 if ( !nn.is_nonneg_integer() ) {
1075 throw (std::range_error("numeric::doublefactorial(): argument must be integer >= -1"));
1077 if ( nn.is_even() ) {
1078 int n = nn.div(numTWO()).to_int();
1079 if ( n <= highest_evenresult ) {
1080 return evenresults[n];
1082 if ( evenresults.capacity() < (unsigned)(n+1) ) {
1083 evenresults.reserve(n+1);
1085 if ( highest_evenresult < 0 ) {
1086 evenresults.push_back(numONE());
1087 highest_evenresult=0;
1089 for (int i=highest_evenresult+1; i<=n; i++) {
1090 evenresults.push_back(numeric(evenresults[i-1].mul(numeric(i*2))));
1092 highest_evenresult=n;
1093 return evenresults[n];
1095 int n = nn.sub(numONE()).div(numTWO()).to_int();
1096 if ( n <= highest_oddresult ) {
1097 return oddresults[n];
1099 if ( oddresults.capacity() < (unsigned)n ) {
1100 oddresults.reserve(n+1);
1102 if ( highest_oddresult < 0 ) {
1103 oddresults.push_back(numONE());
1104 highest_oddresult=0;
1106 for (int i=highest_oddresult+1; i<=n; i++) {
1107 oddresults.push_back(numeric(oddresults[i-1].mul(numeric(i*2+1))));
1109 highest_oddresult=n;
1110 return oddresults[n];
1114 /** The Binomial function. It computes the binomial coefficients. If the
1115 * arguments are both nonnegative integers and 0 <= k <= n, then
1116 * binomial(n, k) = n!/k!/(n-k)! which is the number of ways of choosing k
1117 * objects from n distinct objects. If k > n, then binomial(n,k) returns 0. */
1118 numeric binomial(numeric const & n, numeric const & k)
1120 if (n.is_nonneg_integer() && k.is_nonneg_integer()) {
1121 return numeric(binomial(n.to_int(),k.to_int())); // -> CLN
1123 // should really be gamma(n+1)/(gamma(r+1)/gamma(n-r+1)
1126 // return factorial(n).div(factorial(k).mul(factorial(n.sub(k))));
1129 /** Absolute value. */
1130 numeric abs(numeric const & x)
1132 return abs(*x.value); // -> CLN
1135 /** Modulus (in positive representation).
1136 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1137 * sign of a or is zero. This is different from Maple's modp, where the sign
1138 * of b is ignored. It is in agreement with Mathematica's Mod.
1140 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1141 * integer, 0 otherwise. */
1142 numeric mod(numeric const & a, numeric const & b)
1144 if (a.is_integer() && b.is_integer()) {
1145 return mod(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1148 return numZERO(); // Throw?
1152 /** Modulus (in symmetric representation).
1153 * Equivalent to Maple's mods.
1155 * @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1156 numeric smod(numeric const & a, numeric const & b)
1158 if (a.is_integer() && b.is_integer()) {
1159 cl_I b2 = The(cl_I)(ceiling1(The(cl_I)(*b.value) / 2)) - 1;
1160 return mod(The(cl_I)(*a.value) + b2, The(cl_I)(*b.value)) - b2;
1162 return numZERO(); // Throw?
1166 /** Numeric integer remainder.
1167 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1168 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1169 * sign of a or is zero.
1171 * @return remainder of a/b if both are integer, 0 otherwise. */
1172 numeric irem(numeric const & a, numeric const & b)
1174 if (a.is_integer() && b.is_integer()) {
1175 return rem(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1178 return numZERO(); // Throw?
1182 /** Numeric integer remainder.
1183 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1184 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1185 * and irem(a,b) has the sign of a or is zero.
1187 * @return remainder of a/b and quotient stored in q if both are integer,
1189 numeric irem(numeric const & a, numeric const & b, numeric & q)
1191 if (a.is_integer() && b.is_integer()) { // -> CLN
1192 cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1193 q = rem_quo.quotient;
1194 return rem_quo.remainder;
1198 return numZERO(); // Throw?
1202 /** Numeric integer quotient.
1203 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1205 * @return truncated quotient of a/b if both are integer, 0 otherwise. */
1206 numeric iquo(numeric const & a, numeric const & b)
1208 if (a.is_integer() && b.is_integer()) {
1209 return truncate1(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1211 return numZERO(); // Throw?
1215 /** Numeric integer quotient.
1216 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1217 * r == a - iquo(a,b,r)*b.
1219 * @return truncated quotient of a/b and remainder stored in r if both are
1220 * integer, 0 otherwise. */
1221 numeric iquo(numeric const & a, numeric const & b, numeric & r)
1223 if (a.is_integer() && b.is_integer()) { // -> CLN
1224 cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1225 r = rem_quo.remainder;
1226 return rem_quo.quotient;
1229 return numZERO(); // Throw?
1233 /** Numeric square root.
1234 * If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4)
1235 * should return integer 2.
1237 * @param z numeric argument
1238 * @return square root of z. Branch cut along negative real axis, the negative
1239 * real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part
1240 * where imag(z)>0. */
1241 numeric sqrt(numeric const & z)
1243 return sqrt(*z.value); // -> CLN
1246 /** Integer numeric square root. */
1247 numeric isqrt(numeric const & x)
1249 if (x.is_integer()) {
1251 isqrt(The(cl_I)(*x.value), &root); // -> CLN
1254 return numZERO(); // Throw?
1257 /** Greatest Common Divisor.
1259 * @return The GCD of two numbers if both are integer, a numerical 1
1260 * if they are not. */
1261 numeric gcd(numeric const & a, numeric const & b)
1263 if (a.is_integer() && b.is_integer())
1264 return gcd(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1269 /** Least Common Multiple.
1271 * @return The LCM of two numbers if both are integer, the product of those
1272 * two numbers if they are not. */
1273 numeric lcm(numeric const & a, numeric const & b)
1275 if (a.is_integer() && b.is_integer())
1276 return lcm(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1278 return *a.value * *b.value;
1283 return numeric(cl_pi(cl_default_float_format)); // -> CLN
1286 ex EulerGammaEvalf(void)
1288 return numeric(cl_eulerconst(cl_default_float_format)); // -> CLN
1291 ex CatalanEvalf(void)
1293 return numeric(cl_catalanconst(cl_default_float_format)); // -> CLN
1296 // It initializes to 17 digits, because in CLN cl_float_format(17) turns out to
1297 // be 61 (<64) while cl_float_format(18)=65. We want to have a cl_LF instead
1298 // of cl_SF, cl_FF or cl_DF but everything else is basically arbitrary.
1299 _numeric_digits::_numeric_digits()
1304 cl_default_float_format = cl_float_format(17);
1307 _numeric_digits& _numeric_digits::operator=(long prec)
1310 cl_default_float_format = cl_float_format(prec);
1314 _numeric_digits::operator long()
1316 return (long)digits;
1319 void _numeric_digits::print(ostream & os) const
1321 debugmsg("_numeric_digits print", LOGLEVEL_PRINT);
1325 ostream& operator<<(ostream& os, _numeric_digits const & e)
1332 // static member variables
1337 bool _numeric_digits::too_late = false;
1339 /** Accuracy in decimal digits. Only object of this type! Can be set using
1340 * assignment from C++ unsigned ints and evaluated like any built-in type. */
1341 _numeric_digits Digits;