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
34 // CLN should not pollute the global namespace, hence we include it here
35 // instead of in some header file where it would propagate to other parts:
42 // linker has no problems finding text symbols for numerator or denominator
46 // default constructor, destructor, copy constructor assignment
47 // operator and helpers
52 /** default ctor. Numerically it initializes to an integer zero. */
53 numeric::numeric() : basic(TINFO_numeric)
55 debugmsg("numeric default constructor", LOGLEVEL_CONSTRUCT);
59 setflag(status_flags::evaluated|
60 status_flags::hash_calculated);
65 debugmsg("numeric destructor" ,LOGLEVEL_DESTRUCT);
69 numeric::numeric(numeric const & other)
71 debugmsg("numeric copy constructor", LOGLEVEL_CONSTRUCT);
75 numeric const & numeric::operator=(numeric const & other)
77 debugmsg("numeric operator=", LOGLEVEL_ASSIGNMENT);
87 void numeric::copy(numeric const & other)
90 value = new cl_N(*other.value);
93 void numeric::destroy(bool call_parent)
96 if (call_parent) basic::destroy(call_parent);
100 // other constructors
105 numeric::numeric(int i) : basic(TINFO_numeric)
107 debugmsg("numeric constructor from int",LOGLEVEL_CONSTRUCT);
108 // Not the whole int-range is available if we don't cast to long
109 // first. This is due to the behaviour of the cl_I-ctor, which
110 // emphasizes efficiency:
111 value = new cl_I((long) i);
113 setflag(status_flags::evaluated|
114 status_flags::hash_calculated);
117 numeric::numeric(unsigned int i) : basic(TINFO_numeric)
119 debugmsg("numeric constructor from uint",LOGLEVEL_CONSTRUCT);
120 // Not the whole uint-range is available if we don't cast to ulong
121 // first. This is due to the behaviour of the cl_I-ctor, which
122 // emphasizes efficiency:
123 value = new cl_I((unsigned long)i);
125 setflag(status_flags::evaluated|
126 status_flags::hash_calculated);
129 numeric::numeric(long i) : basic(TINFO_numeric)
131 debugmsg("numeric constructor from long",LOGLEVEL_CONSTRUCT);
134 setflag(status_flags::evaluated|
135 status_flags::hash_calculated);
138 numeric::numeric(unsigned long i) : basic(TINFO_numeric)
140 debugmsg("numeric constructor from ulong",LOGLEVEL_CONSTRUCT);
143 setflag(status_flags::evaluated|
144 status_flags::hash_calculated);
147 /** Ctor for rational numerics a/b.
149 * @exception overflow_error (division by zero) */
150 numeric::numeric(long numer, long denom) : basic(TINFO_numeric)
152 debugmsg("numeric constructor from long/long",LOGLEVEL_CONSTRUCT);
154 throw (std::overflow_error("division by zero"));
155 value = new cl_I(numer);
156 *value = *value / cl_I(denom);
158 setflag(status_flags::evaluated|
159 status_flags::hash_calculated);
162 numeric::numeric(double d) : basic(TINFO_numeric)
164 debugmsg("numeric constructor from double",LOGLEVEL_CONSTRUCT);
165 // We really want to explicitly use the type cl_LF instead of the
166 // more general cl_F, since that would give us a cl_DF only which
167 // will not be promoted to cl_LF if overflow occurs:
169 *value = cl_float(d, cl_default_float_format);
171 setflag(status_flags::evaluated|
172 status_flags::hash_calculated);
175 numeric::numeric(char const *s) : basic(TINFO_numeric)
176 { // MISSING: treatment of complex and ints and rationals.
177 debugmsg("numeric constructor from string",LOGLEVEL_CONSTRUCT);
179 value = new cl_LF(s);
183 setflag(status_flags::evaluated|
184 status_flags::hash_calculated);
187 /** Ctor from CLN types. This is for the initiated user or internal use
189 numeric::numeric(cl_N const & z) : basic(TINFO_numeric)
191 debugmsg("numeric constructor from cl_N", LOGLEVEL_CONSTRUCT);
194 setflag(status_flags::evaluated|
195 status_flags::hash_calculated);
199 // functions overriding virtual functions from bases classes
204 basic * numeric::duplicate() const
206 debugmsg("numeric duplicate", LOGLEVEL_DUPLICATE);
207 return new numeric(*this);
210 // The method printraw doesn't do much, it simply uses CLN's operator<<() for
211 // output, which is ugly but reliable. Examples:
213 void numeric::printraw(ostream & os) const
215 debugmsg("numeric printraw", LOGLEVEL_PRINT);
216 os << "numeric(" << *value << ")";
219 // The method print adds to the output so it blends more consistently together
220 // with the other routines and produces something compatible to Maple input.
221 void numeric::print(ostream & os, unsigned upper_precedence) const
223 debugmsg("numeric print", LOGLEVEL_PRINT);
225 // case 1, real: x or -x
226 if ((precedence<=upper_precedence) && (!is_pos_integer())) {
227 os << "(" << *value << ")";
232 // case 2, imaginary: y*I or -y*I
233 if (realpart(*value) == 0) {
234 if ((precedence<=upper_precedence) && (imagpart(*value) < 0)) {
235 if (imagpart(*value) == -1) {
238 os << "(" << imagpart(*value) << "*I)";
241 if (imagpart(*value) == 1) {
244 if (imagpart (*value) == -1) {
247 os << imagpart(*value) << "*I";
252 // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I
253 if (precedence <= upper_precedence) os << "(";
254 os << realpart(*value);
255 if (imagpart(*value) < 0) {
256 if (imagpart(*value) == -1) {
259 os << imagpart(*value) << "*I";
262 if (imagpart(*value) == 1) {
265 os << "+" << imagpart(*value) << "*I";
268 if (precedence <= upper_precedence) os << ")";
273 bool numeric::info(unsigned inf) const
276 case info_flags::numeric:
277 case info_flags::polynomial:
278 case info_flags::rational_function:
280 case info_flags::real:
282 case info_flags::rational:
283 case info_flags::rational_polynomial:
284 return is_rational();
285 case info_flags::integer:
286 case info_flags::integer_polynomial:
288 case info_flags::positive:
289 return is_positive();
290 case info_flags::negative:
291 return is_negative();
292 case info_flags::nonnegative:
293 return compare(numZERO())>=0;
294 case info_flags::posint:
295 return is_pos_integer();
296 case info_flags::negint:
297 return is_integer() && (compare(numZERO())<0);
298 case info_flags::nonnegint:
299 return is_nonneg_integer();
300 case info_flags::even:
302 case info_flags::odd:
304 case info_flags::prime:
310 /** Cast numeric into a floating-point object. For example exact numeric(1) is
311 * returned as a 1.0000000000000000000000 and so on according to how Digits is
314 * @param level ignored, but needed for overriding basic::evalf.
315 * @return an ex-handle to a numeric. */
316 ex numeric::evalf(int level) const
318 // level can safely be discarded for numeric objects.
319 return numeric(cl_float(1.0, cl_default_float_format) * (*value)); // -> CLN
324 int numeric::compare_same_type(basic const & other) const
326 ASSERT(is_exactly_of_type(other, numeric));
327 numeric const & o = static_cast<numeric &>(const_cast<basic &>(other));
329 if (*value == *o.value) {
336 bool numeric::is_equal_same_type(basic const & other) const
338 ASSERT(is_exactly_of_type(other,numeric));
339 numeric const *o = static_cast<numeric const *>(&other);
345 unsigned numeric::calchash(void) const
347 double d=to_double();
353 return 0x88000000U+s*unsigned(d/0x07FF0000);
359 // new virtual functions which can be overridden by derived classes
365 // non-virtual functions in this class
370 /** Numerical addition method. Adds argument to *this and returns result as
371 * a new numeric object. */
372 numeric numeric::add(numeric const & other) const
374 return numeric((*value)+(*other.value));
377 /** Numerical subtraction method. Subtracts argument from *this and returns
378 * result as a new numeric object. */
379 numeric numeric::sub(numeric const & other) const
381 return numeric((*value)-(*other.value));
384 /** Numerical multiplication method. Multiplies *this and argument and returns
385 * result as a new numeric object. */
386 numeric numeric::mul(numeric const & other) const
388 static const numeric * numONEp=&numONE();
391 } else if (&other==numONEp) {
394 return numeric((*value)*(*other.value));
397 /** Numerical division method. Divides *this by argument and returns result as
398 * a new numeric object.
400 * @exception overflow_error (division by zero) */
401 numeric numeric::div(numeric const & other) const
403 if (zerop(*other.value))
404 throw (std::overflow_error("division by zero"));
405 return numeric((*value)/(*other.value));
408 numeric numeric::power(numeric const & other) const
410 static const numeric * numONEp=&numONE();
411 if (&other==numONEp) {
414 if (zerop(*value) && other.is_real() && minusp(realpart(*other.value)))
415 throw (std::overflow_error("division by zero"));
416 return numeric(expt(*value,*other.value));
419 /** Inverse of a number. */
420 numeric numeric::inverse(void) const
422 return numeric(recip(*value)); // -> CLN
425 numeric const & numeric::add_dyn(numeric const & other) const
427 return static_cast<numeric const &>((new numeric((*value)+(*other.value)))->
428 setflag(status_flags::dynallocated));
431 numeric const & numeric::sub_dyn(numeric const & other) const
433 return static_cast<numeric const &>((new numeric((*value)-(*other.value)))->
434 setflag(status_flags::dynallocated));
437 numeric const & numeric::mul_dyn(numeric const & other) const
439 static const numeric * numONEp=&numONE();
442 } else if (&other==numONEp) {
445 return static_cast<numeric const &>((new numeric((*value)*(*other.value)))->
446 setflag(status_flags::dynallocated));
449 numeric const & numeric::div_dyn(numeric const & other) const
451 if (zerop(*other.value))
452 throw (std::overflow_error("division by zero"));
453 return static_cast<numeric const &>((new numeric((*value)/(*other.value)))->
454 setflag(status_flags::dynallocated));
457 numeric const & numeric::power_dyn(numeric const & other) const
459 static const numeric * numONEp=&numONE();
460 if (&other==numONEp) {
463 // The ifs are only a workaround for a bug in CLN. It gets stuck otherwise:
464 if ( !other.is_integer() &&
465 other.is_rational() &&
466 (*this).is_nonneg_integer() ) {
467 if ( !zerop(*value) ) {
468 return static_cast<numeric const &>((new numeric(exp(*other.value * log(*value))))->
469 setflag(status_flags::dynallocated));
471 if ( !zerop(*other.value) ) { // 0^(n/m)
472 return static_cast<numeric const &>((new numeric(0))->
473 setflag(status_flags::dynallocated));
474 } else { // raise FPE (0^0 requested)
475 return static_cast<numeric const &>((new numeric(1/(*other.value)))->
476 setflag(status_flags::dynallocated));
479 } else { // default -> CLN
480 return static_cast<numeric const &>((new numeric(expt(*value,*other.value)))->
481 setflag(status_flags::dynallocated));
485 numeric const & numeric::operator=(int i)
487 return operator=(numeric(i));
490 numeric const & numeric::operator=(unsigned int i)
492 return operator=(numeric(i));
495 numeric const & numeric::operator=(long i)
497 return operator=(numeric(i));
500 numeric const & numeric::operator=(unsigned long i)
502 return operator=(numeric(i));
505 numeric const & numeric::operator=(double d)
507 return operator=(numeric(d));
510 numeric const & numeric::operator=(char const * s)
512 return operator=(numeric(s));
515 /** This method establishes a canonical order on all numbers. For complex
516 * numbers this is not possible in a mathematically consistent way but we need
517 * to establish some order and it ought to be fast. So we simply define it
518 * similar to Maple's csgn. */
519 int numeric::compare(numeric const & other) const
521 // Comparing two real numbers?
522 if (is_real() && other.is_real())
523 // Yes, just compare them
524 return cl_compare(The(cl_R)(*value), The(cl_R)(*other.value));
526 // No, first compare real parts
527 cl_signean real_cmp = cl_compare(realpart(*value), realpart(*other.value));
531 return cl_compare(imagpart(*value), imagpart(*other.value));
535 bool numeric::is_equal(numeric const & other) const
537 return (*value == *other.value);
540 /** True if object is zero. */
541 bool numeric::is_zero(void) const
543 return zerop(*value); // -> CLN
546 /** True if object is not complex and greater than zero. */
547 bool numeric::is_positive(void) const
550 return plusp(The(cl_R)(*value)); // -> CLN
555 /** True if object is not complex and less than zero. */
556 bool numeric::is_negative(void) const
559 return minusp(The(cl_R)(*value)); // -> CLN
564 /** True if object is a non-complex integer. */
565 bool numeric::is_integer(void) const
567 return (bool)instanceof(*value, cl_I_ring); // -> CLN
570 /** True if object is an exact integer greater than zero. */
571 bool numeric::is_pos_integer(void) const
573 return (is_integer() &&
574 plusp(The(cl_I)(*value))); // -> CLN
577 /** True if object is an exact integer greater or equal zero. */
578 bool numeric::is_nonneg_integer(void) const
580 return (is_integer() &&
581 !minusp(The(cl_I)(*value))); // -> CLN
584 /** True if object is an exact even integer. */
585 bool numeric::is_even(void) const
587 return (is_integer() &&
588 evenp(The(cl_I)(*value))); // -> CLN
591 /** True if object is an exact odd integer. */
592 bool numeric::is_odd(void) const
594 return (is_integer() &&
595 oddp(The(cl_I)(*value))); // -> CLN
598 /** Probabilistic primality test.
600 * @return true if object is exact integer and prime. */
601 bool numeric::is_prime(void) const
603 return (is_integer() &&
604 isprobprime(The(cl_I)(*value))); // -> CLN
607 /** True if object is an exact rational number, may even be complex
608 * (denominator may be unity). */
609 bool numeric::is_rational(void) const
611 if (instanceof(*value, cl_RA_ring)) {
613 } else if (!is_real()) { // complex case, handle Q(i):
614 if ( instanceof(realpart(*value), cl_RA_ring) &&
615 instanceof(imagpart(*value), cl_RA_ring) )
621 /** True if object is a real integer, rational or float (but not complex). */
622 bool numeric::is_real(void) const
624 return (bool)instanceof(*value, cl_R_ring); // -> CLN
627 bool numeric::operator==(numeric const & other) const
629 return (*value == *other.value); // -> CLN
632 bool numeric::operator!=(numeric const & other) const
634 return (*value != *other.value); // -> CLN
637 /** Numerical comparison: less.
639 * @exception invalid_argument (complex inequality) */
640 bool numeric::operator<(numeric const & other) const
642 if ( is_real() && other.is_real() ) {
643 return (bool)(The(cl_R)(*value) < The(cl_R)(*other.value)); // -> CLN
645 throw (std::invalid_argument("numeric::operator<(): complex inequality"));
646 return false; // make compiler shut up
649 /** Numerical comparison: less or equal.
651 * @exception invalid_argument (complex inequality) */
652 bool numeric::operator<=(numeric const & other) const
654 if ( is_real() && other.is_real() ) {
655 return (bool)(The(cl_R)(*value) <= The(cl_R)(*other.value)); // -> CLN
657 throw (std::invalid_argument("numeric::operator<=(): complex inequality"));
658 return false; // make compiler shut up
661 /** Numerical comparison: greater.
663 * @exception invalid_argument (complex inequality) */
664 bool numeric::operator>(numeric const & other) const
666 if ( is_real() && other.is_real() ) {
667 return (bool)(The(cl_R)(*value) > The(cl_R)(*other.value)); // -> CLN
669 throw (std::invalid_argument("numeric::operator>(): complex inequality"));
670 return false; // make compiler shut up
673 /** Numerical comparison: greater or equal.
675 * @exception invalid_argument (complex inequality) */
676 bool numeric::operator>=(numeric const & other) const
678 if ( is_real() && other.is_real() ) {
679 return (bool)(The(cl_R)(*value) >= The(cl_R)(*other.value)); // -> CLN
681 throw (std::invalid_argument("numeric::operator>=(): complex inequality"));
682 return false; // make compiler shut up
685 /** Converts numeric types to machine's int. You should check with is_integer()
686 * if the number is really an integer before calling this method. */
687 int numeric::to_int(void) const
689 ASSERT(is_integer());
690 return cl_I_to_int(The(cl_I)(*value));
693 /** Converts numeric types to machine's double. You should check with is_real()
694 * if the number is really not complex before calling this method. */
695 double numeric::to_double(void) const
698 return cl_double_approx(realpart(*value));
701 /** Real part of a number. */
702 numeric numeric::real(void) const
704 return numeric(realpart(*value)); // -> CLN
707 /** Imaginary part of a number. */
708 numeric numeric::imag(void) const
710 return numeric(imagpart(*value)); // -> CLN
714 // Unfortunately, CLN did not provide an official way to access the numerator
715 // or denominator of a rational number (cl_RA). Doing some excavations in CLN
716 // one finds how it works internally in src/rational/cl_RA.h:
717 struct cl_heap_ratio : cl_heap {
722 inline cl_heap_ratio* TheRatio (const cl_N& obj)
723 { return (cl_heap_ratio*)(obj.pointer); }
724 #endif // ndef SANE_LINKER
726 /** Numerator. Computes the numerator of rational numbers, rationalized
727 * numerator of complex if real and imaginary part are both rational numbers
728 * (i.e numer(4/3+5/6*I) == 8+5*I), the number itself in all other cases. */
729 numeric numeric::numer(void) const
732 return numeric(*this);
735 else if (instanceof(*value, cl_RA_ring)) {
736 return numeric(numerator(The(cl_RA)(*value)));
738 else if (!is_real()) { // complex case, handle Q(i):
739 cl_R r = realpart(*value);
740 cl_R i = imagpart(*value);
741 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
742 return numeric(*this);
743 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
744 return numeric(complex(r*denominator(The(cl_RA)(i)), numerator(The(cl_RA)(i))));
745 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
746 return numeric(complex(numerator(The(cl_RA)(r)), i*denominator(The(cl_RA)(r))));
747 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) {
748 cl_I s = lcm(denominator(The(cl_RA)(r)), denominator(The(cl_RA)(i)));
749 return numeric(complex(numerator(The(cl_RA)(r))*(exquo(s,denominator(The(cl_RA)(r)))),
750 numerator(The(cl_RA)(i))*(exquo(s,denominator(The(cl_RA)(i))))));
754 else if (instanceof(*value, cl_RA_ring)) {
755 return numeric(TheRatio(*value)->numerator);
757 else if (!is_real()) { // complex case, handle Q(i):
758 cl_R r = realpart(*value);
759 cl_R i = imagpart(*value);
760 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
761 return numeric(*this);
762 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
763 return numeric(complex(r*TheRatio(i)->denominator, TheRatio(i)->numerator));
764 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
765 return numeric(complex(TheRatio(r)->numerator, i*TheRatio(r)->denominator));
766 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) {
767 cl_I s = lcm(TheRatio(r)->denominator, TheRatio(i)->denominator);
768 return numeric(complex(TheRatio(r)->numerator*(exquo(s,TheRatio(r)->denominator)),
769 TheRatio(i)->numerator*(exquo(s,TheRatio(i)->denominator))));
772 #endif // def SANE_LINKER
773 // at least one float encountered
774 return numeric(*this);
777 /** Denominator. Computes the denominator of rational numbers, common integer
778 * denominator of complex if real and imaginary part are both rational numbers
779 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
780 numeric numeric::denom(void) const
786 if (instanceof(*value, cl_RA_ring)) {
787 return numeric(denominator(The(cl_RA)(*value)));
789 if (!is_real()) { // complex case, handle Q(i):
790 cl_R r = realpart(*value);
791 cl_R i = imagpart(*value);
792 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
794 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
795 return numeric(denominator(The(cl_RA)(i)));
796 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
797 return numeric(denominator(The(cl_RA)(r)));
798 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring))
799 return numeric(lcm(denominator(The(cl_RA)(r)), denominator(The(cl_RA)(i))));
802 if (instanceof(*value, cl_RA_ring)) {
803 return numeric(TheRatio(*value)->denominator);
805 if (!is_real()) { // complex case, handle Q(i):
806 cl_R r = realpart(*value);
807 cl_R i = imagpart(*value);
808 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
810 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
811 return numeric(TheRatio(i)->denominator);
812 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
813 return numeric(TheRatio(r)->denominator);
814 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring))
815 return numeric(lcm(TheRatio(r)->denominator, TheRatio(i)->denominator));
817 #endif // def SANE_LINKER
818 // at least one float encountered
822 /** Size in binary notation. For integers, this is the smallest n >= 0 such
823 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
824 * 2^(n-1) <= x < 2^n.
826 * @return number of bits (excluding sign) needed to represent that number
827 * in two's complement if it is an integer, 0 otherwise. */
828 int numeric::int_length(void) const
831 return integer_length(The(cl_I)(*value)); // -> CLN
839 // static member variables
844 unsigned numeric::precedence = 30;
850 const numeric some_numeric;
851 type_info const & typeid_numeric=typeid(some_numeric);
852 /** Imaginary unit. This is not a constant but a numeric since we are
853 * natively handing complex numbers anyways. */
854 const numeric I = (complex(cl_I(0),cl_I(1)));
860 numeric const & numZERO(void)
862 const static ex eZERO = ex((new numeric(0))->setflag(status_flags::dynallocated));
863 const static numeric * nZERO = static_cast<const numeric *>(eZERO.bp);
867 numeric const & numONE(void)
869 const static ex eONE = ex((new numeric(1))->setflag(status_flags::dynallocated));
870 const static numeric * nONE = static_cast<const numeric *>(eONE.bp);
874 numeric const & numTWO(void)
876 const static ex eTWO = ex((new numeric(2))->setflag(status_flags::dynallocated));
877 const static numeric * nTWO = static_cast<const numeric *>(eTWO.bp);
881 numeric const & numTHREE(void)
883 const static ex eTHREE = ex((new numeric(3))->setflag(status_flags::dynallocated));
884 const static numeric * nTHREE = static_cast<const numeric *>(eTHREE.bp);
888 numeric const & numMINUSONE(void)
890 const static ex eMINUSONE = ex((new numeric(-1))->setflag(status_flags::dynallocated));
891 const static numeric * nMINUSONE = static_cast<const numeric *>(eMINUSONE.bp);
895 numeric const & numHALF(void)
897 const static ex eHALF = ex((new numeric(1, 2))->setflag(status_flags::dynallocated));
898 const static numeric * nHALF = static_cast<const numeric *>(eHALF.bp);
902 /** Exponential function.
904 * @return arbitrary precision numerical exp(x). */
905 numeric exp(numeric const & x)
907 return exp(*x.value); // -> CLN
910 /** Natural logarithm.
912 * @param z complex number
913 * @return arbitrary precision numerical log(x).
914 * @exception overflow_error (logarithmic singularity) */
915 numeric log(numeric const & z)
918 throw (std::overflow_error("log(): logarithmic singularity"));
919 return log(*z.value); // -> CLN
922 /** Numeric sine (trigonometric function).
924 * @return arbitrary precision numerical sin(x). */
925 numeric sin(numeric const & x)
927 return sin(*x.value); // -> CLN
930 /** Numeric cosine (trigonometric function).
932 * @return arbitrary precision numerical cos(x). */
933 numeric cos(numeric const & x)
935 return cos(*x.value); // -> CLN
938 /** Numeric tangent (trigonometric function).
940 * @return arbitrary precision numerical tan(x). */
941 numeric tan(numeric const & x)
943 return tan(*x.value); // -> CLN
946 /** Numeric inverse sine (trigonometric function).
948 * @return arbitrary precision numerical asin(x). */
949 numeric asin(numeric const & x)
951 return asin(*x.value); // -> CLN
954 /** Numeric inverse cosine (trigonometric function).
956 * @return arbitrary precision numerical acos(x). */
957 numeric acos(numeric const & x)
959 return acos(*x.value); // -> CLN
964 * @param z complex number
966 * @exception overflow_error (logarithmic singularity) */
967 numeric atan(numeric const & x)
970 x.real().is_zero() &&
971 !abs(x.imag()).is_equal(numONE()))
972 throw (std::overflow_error("atan(): logarithmic singularity"));
973 return atan(*x.value); // -> CLN
978 * @param x real number
979 * @param y real number
980 * @return atan(y/x) */
981 numeric atan(numeric const & y, numeric const & x)
983 if (x.is_real() && y.is_real())
984 return atan(realpart(*x.value), realpart(*y.value)); // -> CLN
986 throw (std::invalid_argument("numeric::atan(): complex argument"));
989 /** Numeric hyperbolic sine (trigonometric function).
991 * @return arbitrary precision numerical sinh(x). */
992 numeric sinh(numeric const & x)
994 return sinh(*x.value); // -> CLN
997 /** Numeric hyperbolic cosine (trigonometric function).
999 * @return arbitrary precision numerical cosh(x). */
1000 numeric cosh(numeric const & x)
1002 return cosh(*x.value); // -> CLN
1005 /** Numeric hyperbolic tangent (trigonometric function).
1007 * @return arbitrary precision numerical tanh(x). */
1008 numeric tanh(numeric const & x)
1010 return tanh(*x.value); // -> CLN
1013 /** Numeric inverse hyperbolic sine (trigonometric function).
1015 * @return arbitrary precision numerical asinh(x). */
1016 numeric asinh(numeric const & x)
1018 return asinh(*x.value); // -> CLN
1021 /** Numeric inverse hyperbolic cosine (trigonometric function).
1023 * @return arbitrary precision numerical acosh(x). */
1024 numeric acosh(numeric const & x)
1026 return acosh(*x.value); // -> CLN
1029 /** Numeric inverse hyperbolic tangent (trigonometric function).
1031 * @return arbitrary precision numerical atanh(x). */
1032 numeric atanh(numeric const & x)
1034 return atanh(*x.value); // -> CLN
1037 /** The gamma function.
1038 * stub stub stub stub stub stub! */
1039 numeric gamma(numeric const & x)
1041 clog << "gamma(): Nobody expects the Spanish inquisition" << endl;
1045 /** Factorial combinatorial function.
1047 * @exception range_error (argument must be integer >= 0) */
1048 numeric factorial(numeric const & nn)
1050 if ( !nn.is_nonneg_integer() ) {
1051 throw (std::range_error("numeric::factorial(): argument must be integer >= 0"));
1054 return numeric(factorial(nn.to_int())); // -> CLN
1057 /** The double factorial combinatorial function. (Scarcely used, but still
1058 * useful in cases, like for exact results of Gamma(n+1/2) for instance.)
1060 * @param n integer argument >= -1
1061 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == 1 == (-1)!!
1062 * @exception range_error (argument must be integer >= -1) */
1063 numeric doublefactorial(numeric const & nn)
1065 // We store the results separately for even and odd arguments. This has
1066 // the advantage that we don't have to compute any even result at all if
1067 // the function is always called with odd arguments and vice versa. There
1068 // is no tradeoff involved in this, it is guaranteed to save time as well
1069 // as memory. (If this is not enough justification consider the Gamma
1070 // function of half integer arguments: it only needs odd doublefactorials.)
1071 static vector<numeric> evenresults;
1072 static int highest_evenresult = -1;
1073 static vector<numeric> oddresults;
1074 static int highest_oddresult = -1;
1076 if ( nn == numeric(-1) ) {
1079 if ( !nn.is_nonneg_integer() ) {
1080 throw (std::range_error("numeric::doublefactorial(): argument must be integer >= -1"));
1082 if ( nn.is_even() ) {
1083 int n = nn.div(numTWO()).to_int();
1084 if ( n <= highest_evenresult ) {
1085 return evenresults[n];
1087 if ( evenresults.capacity() < (unsigned)(n+1) ) {
1088 evenresults.reserve(n+1);
1090 if ( highest_evenresult < 0 ) {
1091 evenresults.push_back(numONE());
1092 highest_evenresult=0;
1094 for (int i=highest_evenresult+1; i<=n; i++) {
1095 evenresults.push_back(numeric(evenresults[i-1].mul(numeric(i*2))));
1097 highest_evenresult=n;
1098 return evenresults[n];
1100 int n = nn.sub(numONE()).div(numTWO()).to_int();
1101 if ( n <= highest_oddresult ) {
1102 return oddresults[n];
1104 if ( oddresults.capacity() < (unsigned)n ) {
1105 oddresults.reserve(n+1);
1107 if ( highest_oddresult < 0 ) {
1108 oddresults.push_back(numONE());
1109 highest_oddresult=0;
1111 for (int i=highest_oddresult+1; i<=n; i++) {
1112 oddresults.push_back(numeric(oddresults[i-1].mul(numeric(i*2+1))));
1114 highest_oddresult=n;
1115 return oddresults[n];
1119 /** The Binomial function. It computes the binomial coefficients. If the
1120 * arguments are both nonnegative integers and 0 <= k <= n, then
1121 * binomial(n, k) = n!/k!/(n-k)! which is the number of ways of choosing k
1122 * objects from n distinct objects. If k > n, then binomial(n,k) returns 0. */
1123 numeric binomial(numeric const & n, numeric const & k)
1125 if (n.is_nonneg_integer() && k.is_nonneg_integer()) {
1126 return numeric(binomial(n.to_int(),k.to_int())); // -> CLN
1128 // should really be gamma(n+1)/(gamma(r+1)/gamma(n-r+1)
1131 // return factorial(n).div(factorial(k).mul(factorial(n.sub(k))));
1134 /** Absolute value. */
1135 numeric abs(numeric const & x)
1137 return abs(*x.value); // -> CLN
1140 /** Modulus (in positive representation).
1141 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1142 * sign of a or is zero. This is different from Maple's modp, where the sign
1143 * of b is ignored. It is in agreement with Mathematica's Mod.
1145 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1146 * integer, 0 otherwise. */
1147 numeric mod(numeric const & a, numeric const & b)
1149 if (a.is_integer() && b.is_integer()) {
1150 return mod(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1153 return numZERO(); // Throw?
1157 /** Modulus (in symmetric representation).
1158 * Equivalent to Maple's mods.
1160 * @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1161 numeric smod(numeric const & a, numeric const & b)
1163 if (a.is_integer() && b.is_integer()) {
1164 cl_I b2 = The(cl_I)(ceiling1(The(cl_I)(*b.value) / 2)) - 1;
1165 return mod(The(cl_I)(*a.value) + b2, The(cl_I)(*b.value)) - b2;
1167 return numZERO(); // Throw?
1171 /** Numeric integer remainder.
1172 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1173 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1174 * sign of a or is zero.
1176 * @return remainder of a/b if both are integer, 0 otherwise. */
1177 numeric irem(numeric const & a, numeric const & b)
1179 if (a.is_integer() && b.is_integer()) {
1180 return rem(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1183 return numZERO(); // Throw?
1187 /** Numeric integer remainder.
1188 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1189 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1190 * and irem(a,b) has the sign of a or is zero.
1192 * @return remainder of a/b and quotient stored in q if both are integer,
1194 numeric irem(numeric const & a, numeric const & b, numeric & q)
1196 if (a.is_integer() && b.is_integer()) { // -> CLN
1197 cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1198 q = rem_quo.quotient;
1199 return rem_quo.remainder;
1203 return numZERO(); // Throw?
1207 /** Numeric integer quotient.
1208 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1210 * @return truncated quotient of a/b if both are integer, 0 otherwise. */
1211 numeric iquo(numeric const & a, numeric const & b)
1213 if (a.is_integer() && b.is_integer()) {
1214 return truncate1(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1216 return numZERO(); // Throw?
1220 /** Numeric integer quotient.
1221 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1222 * r == a - iquo(a,b,r)*b.
1224 * @return truncated quotient of a/b and remainder stored in r if both are
1225 * integer, 0 otherwise. */
1226 numeric iquo(numeric const & a, numeric const & b, numeric & r)
1228 if (a.is_integer() && b.is_integer()) { // -> CLN
1229 cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1230 r = rem_quo.remainder;
1231 return rem_quo.quotient;
1234 return numZERO(); // Throw?
1238 /** Numeric square root.
1239 * If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4)
1240 * should return integer 2.
1242 * @param z numeric argument
1243 * @return square root of z. Branch cut along negative real axis, the negative
1244 * real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part
1245 * where imag(z)>0. */
1246 numeric sqrt(numeric const & z)
1248 return sqrt(*z.value); // -> CLN
1251 /** Integer numeric square root. */
1252 numeric isqrt(numeric const & x)
1254 if (x.is_integer()) {
1256 isqrt(The(cl_I)(*x.value), &root); // -> CLN
1259 return numZERO(); // Throw?
1262 /** Greatest Common Divisor.
1264 * @return The GCD of two numbers if both are integer, a numerical 1
1265 * if they are not. */
1266 numeric gcd(numeric const & a, numeric const & b)
1268 if (a.is_integer() && b.is_integer())
1269 return gcd(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1274 /** Least Common Multiple.
1276 * @return The LCM of two numbers if both are integer, the product of those
1277 * two numbers if they are not. */
1278 numeric lcm(numeric const & a, numeric const & b)
1280 if (a.is_integer() && b.is_integer())
1281 return lcm(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1283 return *a.value * *b.value;
1288 return numeric(cl_pi(cl_default_float_format)); // -> CLN
1291 ex EulerGammaEvalf(void)
1293 return numeric(cl_eulerconst(cl_default_float_format)); // -> CLN
1296 ex CatalanEvalf(void)
1298 return numeric(cl_catalanconst(cl_default_float_format)); // -> CLN
1301 // It initializes to 17 digits, because in CLN cl_float_format(17) turns out to
1302 // be 61 (<64) while cl_float_format(18)=65. We want to have a cl_LF instead
1303 // of cl_SF, cl_FF or cl_DF but everything else is basically arbitrary.
1304 _numeric_digits::_numeric_digits()
1309 cl_default_float_format = cl_float_format(17);
1312 _numeric_digits& _numeric_digits::operator=(long prec)
1315 cl_default_float_format = cl_float_format(prec);
1319 _numeric_digits::operator long()
1321 return (long)digits;
1324 void _numeric_digits::print(ostream & os) const
1326 debugmsg("_numeric_digits print", LOGLEVEL_PRINT);
1330 ostream& operator<<(ostream& os, _numeric_digits const & e)
1337 // static member variables
1342 bool _numeric_digits::too_late = false;
1344 /** Accuracy in decimal digits. Only object of this type! Can be set using
1345 * assignment from C++ unsigned ints and evaluated like any built-in type. */
1346 _numeric_digits Digits;