3 * This file contains the interface to the underlying bignum package.
4 * Its most important design principle is to completely hide the inner
5 * working of that other package from the user of GiNaC. It must either
6 * provide implementation of arithmetic operators and numerical evaluation
7 * of special functions or implement the interface to the bignum package. */
10 * GiNaC Copyright (C) 1999 Johannes Gutenberg University Mainz, Germany
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
35 // CLN should not pollute the global namespace, hence we include it here
36 // instead of in some header file where it would propagate to other parts:
45 // linker has no problems finding text symbols for numerator or denominator
49 // default constructor, destructor, copy constructor assignment
50 // operator and helpers
55 /** default ctor. Numerically it initializes to an integer zero. */
56 numeric::numeric() : basic(TINFO_numeric)
58 debugmsg("numeric default constructor", LOGLEVEL_CONSTRUCT);
62 setflag(status_flags::evaluated|
63 status_flags::hash_calculated);
68 debugmsg("numeric destructor" ,LOGLEVEL_DESTRUCT);
72 numeric::numeric(numeric const & other)
74 debugmsg("numeric copy constructor", LOGLEVEL_CONSTRUCT);
78 numeric const & numeric::operator=(numeric const & other)
80 debugmsg("numeric operator=", LOGLEVEL_ASSIGNMENT);
90 void numeric::copy(numeric const & other)
93 value = new cl_N(*other.value);
96 void numeric::destroy(bool call_parent)
99 if (call_parent) basic::destroy(call_parent);
103 // other constructors
108 numeric::numeric(int i) : basic(TINFO_numeric)
110 debugmsg("numeric constructor from int",LOGLEVEL_CONSTRUCT);
111 // Not the whole int-range is available if we don't cast to long
112 // first. This is due to the behaviour of the cl_I-ctor, which
113 // emphasizes efficiency:
114 value = new cl_I((long) i);
116 setflag(status_flags::evaluated|
117 status_flags::hash_calculated);
120 numeric::numeric(unsigned int i) : basic(TINFO_numeric)
122 debugmsg("numeric constructor from uint",LOGLEVEL_CONSTRUCT);
123 // Not the whole uint-range is available if we don't cast to ulong
124 // first. This is due to the behaviour of the cl_I-ctor, which
125 // emphasizes efficiency:
126 value = new cl_I((unsigned long)i);
128 setflag(status_flags::evaluated|
129 status_flags::hash_calculated);
132 numeric::numeric(long i) : basic(TINFO_numeric)
134 debugmsg("numeric constructor from long",LOGLEVEL_CONSTRUCT);
137 setflag(status_flags::evaluated|
138 status_flags::hash_calculated);
141 numeric::numeric(unsigned long i) : basic(TINFO_numeric)
143 debugmsg("numeric constructor from ulong",LOGLEVEL_CONSTRUCT);
146 setflag(status_flags::evaluated|
147 status_flags::hash_calculated);
150 /** Ctor for rational numerics a/b.
152 * @exception overflow_error (division by zero) */
153 numeric::numeric(long numer, long denom) : basic(TINFO_numeric)
155 debugmsg("numeric constructor from long/long",LOGLEVEL_CONSTRUCT);
157 throw (std::overflow_error("division by zero"));
158 value = new cl_I(numer);
159 *value = *value / cl_I(denom);
161 setflag(status_flags::evaluated|
162 status_flags::hash_calculated);
165 numeric::numeric(double d) : basic(TINFO_numeric)
167 debugmsg("numeric constructor from double",LOGLEVEL_CONSTRUCT);
168 // We really want to explicitly use the type cl_LF instead of the
169 // more general cl_F, since that would give us a cl_DF only which
170 // will not be promoted to cl_LF if overflow occurs:
172 *value = cl_float(d, cl_default_float_format);
174 setflag(status_flags::evaluated|
175 status_flags::hash_calculated);
178 numeric::numeric(char const *s) : basic(TINFO_numeric)
179 { // MISSING: treatment of complex and ints and rationals.
180 debugmsg("numeric constructor from string",LOGLEVEL_CONSTRUCT);
182 value = new cl_LF(s);
186 setflag(status_flags::evaluated|
187 status_flags::hash_calculated);
190 /** Ctor from CLN types. This is for the initiated user or internal use
192 numeric::numeric(cl_N const & z) : basic(TINFO_numeric)
194 debugmsg("numeric constructor from cl_N", LOGLEVEL_CONSTRUCT);
197 setflag(status_flags::evaluated|
198 status_flags::hash_calculated);
202 // functions overriding virtual functions from bases classes
207 basic * numeric::duplicate() const
209 debugmsg("numeric duplicate", LOGLEVEL_DUPLICATE);
210 return new numeric(*this);
213 // The method printraw doesn't do much, it simply uses CLN's operator<<() for
214 // output, which is ugly but reliable. Examples:
216 void numeric::printraw(ostream & os) const
218 debugmsg("numeric printraw", LOGLEVEL_PRINT);
219 os << "numeric(" << *value << ")";
222 // The method print adds to the output so it blends more consistently together
223 // with the other routines and produces something compatible to Maple input.
224 void numeric::print(ostream & os, unsigned upper_precedence) const
226 debugmsg("numeric print", LOGLEVEL_PRINT);
228 // case 1, real: x or -x
229 if ((precedence<=upper_precedence) && (!is_pos_integer())) {
230 os << "(" << *value << ")";
235 // case 2, imaginary: y*I or -y*I
236 if (realpart(*value) == 0) {
237 if ((precedence<=upper_precedence) && (imagpart(*value) < 0)) {
238 if (imagpart(*value) == -1) {
241 os << "(" << imagpart(*value) << "*I)";
244 if (imagpart(*value) == 1) {
247 if (imagpart (*value) == -1) {
250 os << imagpart(*value) << "*I";
255 // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I
256 if (precedence <= upper_precedence) os << "(";
257 os << realpart(*value);
258 if (imagpart(*value) < 0) {
259 if (imagpart(*value) == -1) {
262 os << imagpart(*value) << "*I";
265 if (imagpart(*value) == 1) {
268 os << "+" << imagpart(*value) << "*I";
271 if (precedence <= upper_precedence) os << ")";
276 bool numeric::info(unsigned inf) const
279 case info_flags::numeric:
280 case info_flags::polynomial:
281 case info_flags::rational_function:
283 case info_flags::real:
285 case info_flags::rational:
286 case info_flags::rational_polynomial:
287 return is_rational();
288 case info_flags::integer:
289 case info_flags::integer_polynomial:
291 case info_flags::positive:
292 return is_positive();
293 case info_flags::negative:
294 return is_negative();
295 case info_flags::nonnegative:
296 return compare(numZERO())>=0;
297 case info_flags::posint:
298 return is_pos_integer();
299 case info_flags::negint:
300 return is_integer() && (compare(numZERO())<0);
301 case info_flags::nonnegint:
302 return is_nonneg_integer();
303 case info_flags::even:
305 case info_flags::odd:
307 case info_flags::prime:
313 /** Cast numeric into a floating-point object. For example exact numeric(1) is
314 * returned as a 1.0000000000000000000000 and so on according to how Digits is
317 * @param level ignored, but needed for overriding basic::evalf.
318 * @return an ex-handle to a numeric. */
319 ex numeric::evalf(int level) const
321 // level can safely be discarded for numeric objects.
322 return numeric(cl_float(1.0, cl_default_float_format) * (*value)); // -> CLN
327 int numeric::compare_same_type(basic const & other) const
329 GINAC_ASSERT(is_exactly_of_type(other, numeric));
330 numeric const & o = static_cast<numeric &>(const_cast<basic &>(other));
332 if (*value == *o.value) {
339 bool numeric::is_equal_same_type(basic const & other) const
341 GINAC_ASSERT(is_exactly_of_type(other,numeric));
342 numeric const *o = static_cast<numeric const *>(&other);
348 unsigned numeric::calchash(void) const
350 double d=to_double();
356 return 0x88000000U+s*unsigned(d/0x07FF0000);
362 // new virtual functions which can be overridden by derived classes
368 // non-virtual functions in this class
373 /** Numerical addition method. Adds argument to *this and returns result as
374 * a new numeric object. */
375 numeric numeric::add(numeric const & other) const
377 return numeric((*value)+(*other.value));
380 /** Numerical subtraction method. Subtracts argument from *this and returns
381 * result as a new numeric object. */
382 numeric numeric::sub(numeric const & other) const
384 return numeric((*value)-(*other.value));
387 /** Numerical multiplication method. Multiplies *this and argument and returns
388 * result as a new numeric object. */
389 numeric numeric::mul(numeric const & other) const
391 static const numeric * numONEp=&numONE();
394 } else if (&other==numONEp) {
397 return numeric((*value)*(*other.value));
400 /** Numerical division method. Divides *this by argument and returns result as
401 * a new numeric object.
403 * @exception overflow_error (division by zero) */
404 numeric numeric::div(numeric const & other) const
406 if (zerop(*other.value))
407 throw (std::overflow_error("division by zero"));
408 return numeric((*value)/(*other.value));
411 numeric numeric::power(numeric const & other) const
413 static const numeric * numONEp=&numONE();
414 if (&other==numONEp) {
417 if (zerop(*value) && other.is_real() && minusp(realpart(*other.value)))
418 throw (std::overflow_error("division by zero"));
419 return numeric(expt(*value,*other.value));
422 /** Inverse of a number. */
423 numeric numeric::inverse(void) const
425 return numeric(recip(*value)); // -> CLN
428 numeric const & numeric::add_dyn(numeric const & other) const
430 return static_cast<numeric const &>((new numeric((*value)+(*other.value)))->
431 setflag(status_flags::dynallocated));
434 numeric const & numeric::sub_dyn(numeric const & other) const
436 return static_cast<numeric const &>((new numeric((*value)-(*other.value)))->
437 setflag(status_flags::dynallocated));
440 numeric const & numeric::mul_dyn(numeric const & other) const
442 static const numeric * numONEp=&numONE();
445 } else if (&other==numONEp) {
448 return static_cast<numeric const &>((new numeric((*value)*(*other.value)))->
449 setflag(status_flags::dynallocated));
452 numeric const & numeric::div_dyn(numeric const & other) const
454 if (zerop(*other.value))
455 throw (std::overflow_error("division by zero"));
456 return static_cast<numeric const &>((new numeric((*value)/(*other.value)))->
457 setflag(status_flags::dynallocated));
460 numeric const & numeric::power_dyn(numeric const & other) const
462 static const numeric * numONEp=&numONE();
463 if (&other==numONEp) {
466 // The ifs are only a workaround for a bug in CLN. It gets stuck otherwise:
467 if ( !other.is_integer() &&
468 other.is_rational() &&
469 (*this).is_nonneg_integer() ) {
470 if ( !zerop(*value) ) {
471 return static_cast<numeric const &>((new numeric(exp(*other.value * log(*value))))->
472 setflag(status_flags::dynallocated));
474 if ( !zerop(*other.value) ) { // 0^(n/m)
475 return static_cast<numeric const &>((new numeric(0))->
476 setflag(status_flags::dynallocated));
477 } else { // raise FPE (0^0 requested)
478 return static_cast<numeric const &>((new numeric(1/(*other.value)))->
479 setflag(status_flags::dynallocated));
482 } else { // default -> CLN
483 return static_cast<numeric const &>((new numeric(expt(*value,*other.value)))->
484 setflag(status_flags::dynallocated));
488 numeric const & numeric::operator=(int i)
490 return operator=(numeric(i));
493 numeric const & numeric::operator=(unsigned int i)
495 return operator=(numeric(i));
498 numeric const & numeric::operator=(long i)
500 return operator=(numeric(i));
503 numeric const & numeric::operator=(unsigned long i)
505 return operator=(numeric(i));
508 numeric const & numeric::operator=(double d)
510 return operator=(numeric(d));
513 numeric const & numeric::operator=(char const * s)
515 return operator=(numeric(s));
518 /** Return the complex half-plane (left or right) in which the number lies.
519 * csgn(x)==0 for x==0, csgn(x)==1 for Re(x)>0 or Re(x)=0 and Im(x)>0,
520 * csgn(x)==-1 for Re(x)<0 or Re(x)=0 and Im(x)<0.
522 * @see numeric::compare(numeric const & other) */
523 int numeric::csgn(void) const
527 if (!zerop(realpart(*value))) {
528 if (plusp(realpart(*value)))
533 if (plusp(imagpart(*value)))
540 /** This method establishes a canonical order on all numbers. For complex
541 * numbers this is not possible in a mathematically consistent way but we need
542 * to establish some order and it ought to be fast. So we simply define it
543 * to be compatible with our method csgn.
545 * @return csgn(*this-other)
546 * @see numeric::csgn(void) */
547 int numeric::compare(numeric const & other) const
549 // Comparing two real numbers?
550 if (is_real() && other.is_real())
551 // Yes, just compare them
552 return cl_compare(The(cl_R)(*value), The(cl_R)(*other.value));
554 // No, first compare real parts
555 cl_signean real_cmp = cl_compare(realpart(*value), realpart(*other.value));
559 return cl_compare(imagpart(*value), imagpart(*other.value));
563 bool numeric::is_equal(numeric const & other) const
565 return (*value == *other.value);
568 /** True if object is zero. */
569 bool numeric::is_zero(void) const
571 return zerop(*value); // -> CLN
574 /** True if object is not complex and greater than zero. */
575 bool numeric::is_positive(void) const
578 return plusp(The(cl_R)(*value)); // -> CLN
583 /** True if object is not complex and less than zero. */
584 bool numeric::is_negative(void) const
587 return minusp(The(cl_R)(*value)); // -> CLN
592 /** True if object is a non-complex integer. */
593 bool numeric::is_integer(void) const
595 return (bool)instanceof(*value, cl_I_ring); // -> CLN
598 /** True if object is an exact integer greater than zero. */
599 bool numeric::is_pos_integer(void) const
601 return (is_integer() &&
602 plusp(The(cl_I)(*value))); // -> CLN
605 /** True if object is an exact integer greater or equal zero. */
606 bool numeric::is_nonneg_integer(void) const
608 return (is_integer() &&
609 !minusp(The(cl_I)(*value))); // -> CLN
612 /** True if object is an exact even integer. */
613 bool numeric::is_even(void) const
615 return (is_integer() &&
616 evenp(The(cl_I)(*value))); // -> CLN
619 /** True if object is an exact odd integer. */
620 bool numeric::is_odd(void) const
622 return (is_integer() &&
623 oddp(The(cl_I)(*value))); // -> CLN
626 /** Probabilistic primality test.
628 * @return true if object is exact integer and prime. */
629 bool numeric::is_prime(void) const
631 return (is_integer() &&
632 isprobprime(The(cl_I)(*value))); // -> CLN
635 /** True if object is an exact rational number, may even be complex
636 * (denominator may be unity). */
637 bool numeric::is_rational(void) const
639 if (instanceof(*value, cl_RA_ring)) {
641 } else if (!is_real()) { // complex case, handle Q(i):
642 if ( instanceof(realpart(*value), cl_RA_ring) &&
643 instanceof(imagpart(*value), cl_RA_ring) )
649 /** True if object is a real integer, rational or float (but not complex). */
650 bool numeric::is_real(void) const
652 return (bool)instanceof(*value, cl_R_ring); // -> CLN
655 bool numeric::operator==(numeric const & other) const
657 return (*value == *other.value); // -> CLN
660 bool numeric::operator!=(numeric const & other) const
662 return (*value != *other.value); // -> CLN
665 /** Numerical comparison: less.
667 * @exception invalid_argument (complex inequality) */
668 bool numeric::operator<(numeric const & other) const
670 if ( is_real() && other.is_real() ) {
671 return (bool)(The(cl_R)(*value) < The(cl_R)(*other.value)); // -> CLN
673 throw (std::invalid_argument("numeric::operator<(): complex inequality"));
674 return false; // make compiler shut up
677 /** Numerical comparison: less or equal.
679 * @exception invalid_argument (complex inequality) */
680 bool numeric::operator<=(numeric const & other) const
682 if ( is_real() && other.is_real() ) {
683 return (bool)(The(cl_R)(*value) <= The(cl_R)(*other.value)); // -> CLN
685 throw (std::invalid_argument("numeric::operator<=(): complex inequality"));
686 return false; // make compiler shut up
689 /** Numerical comparison: greater.
691 * @exception invalid_argument (complex inequality) */
692 bool numeric::operator>(numeric const & other) const
694 if ( is_real() && other.is_real() ) {
695 return (bool)(The(cl_R)(*value) > The(cl_R)(*other.value)); // -> CLN
697 throw (std::invalid_argument("numeric::operator>(): complex inequality"));
698 return false; // make compiler shut up
701 /** Numerical comparison: greater or equal.
703 * @exception invalid_argument (complex inequality) */
704 bool numeric::operator>=(numeric const & other) const
706 if ( is_real() && other.is_real() ) {
707 return (bool)(The(cl_R)(*value) >= The(cl_R)(*other.value)); // -> CLN
709 throw (std::invalid_argument("numeric::operator>=(): complex inequality"));
710 return false; // make compiler shut up
713 /** Converts numeric types to machine's int. You should check with is_integer()
714 * if the number is really an integer before calling this method. */
715 int numeric::to_int(void) const
717 GINAC_ASSERT(is_integer());
718 return cl_I_to_int(The(cl_I)(*value));
721 /** Converts numeric types to machine's double. You should check with is_real()
722 * if the number is really not complex before calling this method. */
723 double numeric::to_double(void) const
725 GINAC_ASSERT(is_real());
726 return cl_double_approx(realpart(*value));
729 /** Real part of a number. */
730 numeric numeric::real(void) const
732 return numeric(realpart(*value)); // -> CLN
735 /** Imaginary part of a number. */
736 numeric numeric::imag(void) const
738 return numeric(imagpart(*value)); // -> CLN
742 // Unfortunately, CLN did not provide an official way to access the numerator
743 // or denominator of a rational number (cl_RA). Doing some excavations in CLN
744 // one finds how it works internally in src/rational/cl_RA.h:
745 struct cl_heap_ratio : cl_heap {
750 inline cl_heap_ratio* TheRatio (const cl_N& obj)
751 { return (cl_heap_ratio*)(obj.pointer); }
752 #endif // ndef SANE_LINKER
754 /** Numerator. Computes the numerator of rational numbers, rationalized
755 * numerator of complex if real and imaginary part are both rational numbers
756 * (i.e numer(4/3+5/6*I) == 8+5*I), the number carrying the sign in all other
758 numeric numeric::numer(void) const
761 return numeric(*this);
764 else if (instanceof(*value, cl_RA_ring)) {
765 return numeric(numerator(The(cl_RA)(*value)));
767 else if (!is_real()) { // complex case, handle Q(i):
768 cl_R r = realpart(*value);
769 cl_R i = imagpart(*value);
770 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
771 return numeric(*this);
772 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
773 return numeric(complex(r*denominator(The(cl_RA)(i)), numerator(The(cl_RA)(i))));
774 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
775 return numeric(complex(numerator(The(cl_RA)(r)), i*denominator(The(cl_RA)(r))));
776 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) {
777 cl_I s = lcm(denominator(The(cl_RA)(r)), denominator(The(cl_RA)(i)));
778 return numeric(complex(numerator(The(cl_RA)(r))*(exquo(s,denominator(The(cl_RA)(r)))),
779 numerator(The(cl_RA)(i))*(exquo(s,denominator(The(cl_RA)(i))))));
783 else if (instanceof(*value, cl_RA_ring)) {
784 return numeric(TheRatio(*value)->numerator);
786 else if (!is_real()) { // complex case, handle Q(i):
787 cl_R r = realpart(*value);
788 cl_R i = imagpart(*value);
789 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
790 return numeric(*this);
791 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
792 return numeric(complex(r*TheRatio(i)->denominator, TheRatio(i)->numerator));
793 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
794 return numeric(complex(TheRatio(r)->numerator, i*TheRatio(r)->denominator));
795 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) {
796 cl_I s = lcm(TheRatio(r)->denominator, TheRatio(i)->denominator);
797 return numeric(complex(TheRatio(r)->numerator*(exquo(s,TheRatio(r)->denominator)),
798 TheRatio(i)->numerator*(exquo(s,TheRatio(i)->denominator))));
801 #endif // def SANE_LINKER
802 // at least one float encountered
803 return numeric(*this);
806 /** Denominator. Computes the denominator of rational numbers, common integer
807 * denominator of complex if real and imaginary part are both rational numbers
808 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
809 numeric numeric::denom(void) const
815 if (instanceof(*value, cl_RA_ring)) {
816 return numeric(denominator(The(cl_RA)(*value)));
818 if (!is_real()) { // complex case, handle Q(i):
819 cl_R r = realpart(*value);
820 cl_R i = imagpart(*value);
821 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
823 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
824 return numeric(denominator(The(cl_RA)(i)));
825 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
826 return numeric(denominator(The(cl_RA)(r)));
827 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring))
828 return numeric(lcm(denominator(The(cl_RA)(r)), denominator(The(cl_RA)(i))));
831 if (instanceof(*value, cl_RA_ring)) {
832 return numeric(TheRatio(*value)->denominator);
834 if (!is_real()) { // complex case, handle Q(i):
835 cl_R r = realpart(*value);
836 cl_R i = imagpart(*value);
837 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
839 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
840 return numeric(TheRatio(i)->denominator);
841 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
842 return numeric(TheRatio(r)->denominator);
843 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring))
844 return numeric(lcm(TheRatio(r)->denominator, TheRatio(i)->denominator));
846 #endif // def SANE_LINKER
847 // at least one float encountered
851 /** Size in binary notation. For integers, this is the smallest n >= 0 such
852 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
853 * 2^(n-1) <= x < 2^n.
855 * @return number of bits (excluding sign) needed to represent that number
856 * in two's complement if it is an integer, 0 otherwise. */
857 int numeric::int_length(void) const
860 return integer_length(The(cl_I)(*value)); // -> CLN
868 // static member variables
873 unsigned numeric::precedence = 30;
879 const numeric some_numeric;
880 type_info const & typeid_numeric=typeid(some_numeric);
881 /** Imaginary unit. This is not a constant but a numeric since we are
882 * natively handing complex numbers anyways. */
883 const numeric I = numeric(complex(cl_I(0),cl_I(1)));
889 numeric const & numZERO(void)
891 const static ex eZERO = ex((new numeric(0))->setflag(status_flags::dynallocated));
892 const static numeric * nZERO = static_cast<const numeric *>(eZERO.bp);
896 numeric const & numONE(void)
898 const static ex eONE = ex((new numeric(1))->setflag(status_flags::dynallocated));
899 const static numeric * nONE = static_cast<const numeric *>(eONE.bp);
903 numeric const & numTWO(void)
905 const static ex eTWO = ex((new numeric(2))->setflag(status_flags::dynallocated));
906 const static numeric * nTWO = static_cast<const numeric *>(eTWO.bp);
910 numeric const & numTHREE(void)
912 const static ex eTHREE = ex((new numeric(3))->setflag(status_flags::dynallocated));
913 const static numeric * nTHREE = static_cast<const numeric *>(eTHREE.bp);
917 numeric const & numMINUSONE(void)
919 const static ex eMINUSONE = ex((new numeric(-1))->setflag(status_flags::dynallocated));
920 const static numeric * nMINUSONE = static_cast<const numeric *>(eMINUSONE.bp);
924 numeric const & numHALF(void)
926 const static ex eHALF = ex((new numeric(1, 2))->setflag(status_flags::dynallocated));
927 const static numeric * nHALF = static_cast<const numeric *>(eHALF.bp);
931 /** Exponential function.
933 * @return arbitrary precision numerical exp(x). */
934 numeric exp(numeric const & x)
936 return ::exp(*x.value); // -> CLN
939 /** Natural logarithm.
941 * @param z complex number
942 * @return arbitrary precision numerical log(x).
943 * @exception overflow_error (logarithmic singularity) */
944 numeric log(numeric const & z)
947 throw (std::overflow_error("log(): logarithmic singularity"));
948 return ::log(*z.value); // -> CLN
951 /** Numeric sine (trigonometric function).
953 * @return arbitrary precision numerical sin(x). */
954 numeric sin(numeric const & x)
956 return ::sin(*x.value); // -> CLN
959 /** Numeric cosine (trigonometric function).
961 * @return arbitrary precision numerical cos(x). */
962 numeric cos(numeric const & x)
964 return ::cos(*x.value); // -> CLN
967 /** Numeric tangent (trigonometric function).
969 * @return arbitrary precision numerical tan(x). */
970 numeric tan(numeric const & x)
972 return ::tan(*x.value); // -> CLN
975 /** Numeric inverse sine (trigonometric function).
977 * @return arbitrary precision numerical asin(x). */
978 numeric asin(numeric const & x)
980 return ::asin(*x.value); // -> CLN
983 /** Numeric inverse cosine (trigonometric function).
985 * @return arbitrary precision numerical acos(x). */
986 numeric acos(numeric const & x)
988 return ::acos(*x.value); // -> CLN
993 * @param z complex number
995 * @exception overflow_error (logarithmic singularity) */
996 numeric atan(numeric const & x)
999 x.real().is_zero() &&
1000 !abs(x.imag()).is_equal(numONE()))
1001 throw (std::overflow_error("atan(): logarithmic singularity"));
1002 return ::atan(*x.value); // -> CLN
1007 * @param x real number
1008 * @param y real number
1009 * @return atan(y/x) */
1010 numeric atan(numeric const & y, numeric const & x)
1012 if (x.is_real() && y.is_real())
1013 return ::atan(realpart(*x.value), realpart(*y.value)); // -> CLN
1015 throw (std::invalid_argument("numeric::atan(): complex argument"));
1018 /** Numeric hyperbolic sine (trigonometric function).
1020 * @return arbitrary precision numerical sinh(x). */
1021 numeric sinh(numeric const & x)
1023 return ::sinh(*x.value); // -> CLN
1026 /** Numeric hyperbolic cosine (trigonometric function).
1028 * @return arbitrary precision numerical cosh(x). */
1029 numeric cosh(numeric const & x)
1031 return ::cosh(*x.value); // -> CLN
1034 /** Numeric hyperbolic tangent (trigonometric function).
1036 * @return arbitrary precision numerical tanh(x). */
1037 numeric tanh(numeric const & x)
1039 return ::tanh(*x.value); // -> CLN
1042 /** Numeric inverse hyperbolic sine (trigonometric function).
1044 * @return arbitrary precision numerical asinh(x). */
1045 numeric asinh(numeric const & x)
1047 return ::asinh(*x.value); // -> CLN
1050 /** Numeric inverse hyperbolic cosine (trigonometric function).
1052 * @return arbitrary precision numerical acosh(x). */
1053 numeric acosh(numeric const & x)
1055 return ::acosh(*x.value); // -> CLN
1058 /** Numeric inverse hyperbolic tangent (trigonometric function).
1060 * @return arbitrary precision numerical atanh(x). */
1061 numeric atanh(numeric const & x)
1063 return ::atanh(*x.value); // -> CLN
1066 /** Numeric evaluation of Riemann's Zeta function. Currently works only for
1067 * integer arguments. */
1068 numeric zeta(numeric const & x)
1071 return ::cl_zeta(x.to_int()); // -> CLN
1073 clog << "zeta(): Does anybody know good way to calculate this numerically?" << endl;
1077 /** The gamma function.
1078 * This is only a stub! */
1079 numeric gamma(numeric const & x)
1081 clog << "gamma(): Does anybody know good way to calculate this numerically?" << endl;
1085 /** The psi function (aka polygamma function).
1086 * This is only a stub! */
1087 numeric psi(numeric const & x)
1089 clog << "psi(): Does anybody know good way to calculate this numerically?" << endl;
1093 /** The psi functions (aka polygamma functions).
1094 * This is only a stub! */
1095 numeric psi(numeric const & n, numeric const & x)
1097 clog << "psi(): Does anybody know good way to calculate this numerically?" << endl;
1101 /** Factorial combinatorial function.
1103 * @exception range_error (argument must be integer >= 0) */
1104 numeric factorial(numeric const & nn)
1106 if ( !nn.is_nonneg_integer() ) {
1107 throw (std::range_error("numeric::factorial(): argument must be integer >= 0"));
1110 return numeric(::factorial(nn.to_int())); // -> CLN
1113 /** The double factorial combinatorial function. (Scarcely used, but still
1114 * useful in cases, like for exact results of Gamma(n+1/2) for instance.)
1116 * @param n integer argument >= -1
1117 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == 1 == (-1)!!
1118 * @exception range_error (argument must be integer >= -1) */
1119 numeric doublefactorial(numeric const & nn)
1121 // META-NOTE: The whole shit here will become obsolete and may be moved
1122 // out once CLN learns about double factorial, which should be as soon as
1125 // We store the results separately for even and odd arguments. This has
1126 // the advantage that we don't have to compute any even result at all if
1127 // the function is always called with odd arguments and vice versa. There
1128 // is no tradeoff involved in this, it is guaranteed to save time as well
1129 // as memory. (If this is not enough justification consider the Gamma
1130 // function of half integer arguments: it only needs odd doublefactorials.)
1131 static vector<numeric> evenresults;
1132 static int highest_evenresult = -1;
1133 static vector<numeric> oddresults;
1134 static int highest_oddresult = -1;
1136 if (nn == numeric(-1)) {
1139 if (!nn.is_nonneg_integer()) {
1140 throw (std::range_error("numeric::doublefactorial(): argument must be integer >= -1"));
1143 int n = nn.div(numTWO()).to_int();
1144 if (n <= highest_evenresult) {
1145 return evenresults[n];
1147 if (evenresults.capacity() < (unsigned)(n+1)) {
1148 evenresults.reserve(n+1);
1150 if (highest_evenresult < 0) {
1151 evenresults.push_back(numONE());
1152 highest_evenresult=0;
1154 for (int i=highest_evenresult+1; i<=n; i++) {
1155 evenresults.push_back(numeric(evenresults[i-1].mul(numeric(i*2))));
1157 highest_evenresult=n;
1158 return evenresults[n];
1160 int n = nn.sub(numONE()).div(numTWO()).to_int();
1161 if (n <= highest_oddresult) {
1162 return oddresults[n];
1164 if (oddresults.capacity() < (unsigned)n) {
1165 oddresults.reserve(n+1);
1167 if (highest_oddresult < 0) {
1168 oddresults.push_back(numONE());
1169 highest_oddresult=0;
1171 for (int i=highest_oddresult+1; i<=n; i++) {
1172 oddresults.push_back(numeric(oddresults[i-1].mul(numeric(i*2+1))));
1174 highest_oddresult=n;
1175 return oddresults[n];
1179 /** The Binomial coefficients. It computes the binomial coefficients. For
1180 * integer n and k and positive n this is the number of ways of choosing k
1181 * objects from n distinct objects. If n is negative, the formula
1182 * binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */
1183 numeric binomial(numeric const & n, numeric const & k)
1185 if (n.is_integer() && k.is_integer()) {
1186 if (n.is_nonneg_integer()) {
1187 if (k.compare(n)!=1 && k.compare(numZERO())!=-1)
1188 return numeric(::binomial(n.to_int(),k.to_int())); // -> CLN
1192 return numMINUSONE().power(k)*binomial(k-n-numONE(),k);
1196 // should really be gamma(n+1)/(gamma(r+1)/gamma(n-r+1) or a suitable limit
1197 throw (std::range_error("numeric::binomial(): don´t know how to evaluate that."));
1200 /** Bernoulli number. The nth Bernoulli number is the coefficient of x^n/n!
1201 * in the expansion of the function x/(e^x-1).
1203 * @return the nth Bernoulli number (a rational number).
1204 * @exception range_error (argument must be integer >= 0) */
1205 numeric bernoulli(numeric const & nn)
1207 if (!nn.is_integer() || nn.is_negative())
1208 throw (std::range_error("numeric::bernoulli(): argument must be integer >= 0"));
1211 if (!nn.compare(numONE()))
1212 return numeric(-1,2);
1215 // Until somebody has the Blues and comes up with a much better idea and
1216 // codes it (preferably in CLN) we make this a remembering function which
1217 // computes its results using the formula
1218 // B(nn) == - 1/(nn+1) * sum_{k=0}^{nn-1}(binomial(nn+1,k)*B(k))
1220 static vector<numeric> results;
1221 static int highest_result = -1;
1222 int n = nn.sub(numTWO()).div(numTWO()).to_int();
1223 if (n <= highest_result)
1225 if (results.capacity() < (unsigned)(n+1))
1226 results.reserve(n+1);
1228 numeric tmp; // used to store the sum
1229 for (int i=highest_result+1; i<=n; ++i) {
1230 // the first two elements:
1231 tmp = numeric(-2*i-1,2);
1232 // accumulate the remaining elements:
1233 for (int j=0; j<i; ++j)
1234 tmp += binomial(numeric(2*i+3),numeric(j*2+2))*results[j];
1235 // divide by -(nn+1) and store result:
1236 results.push_back(-tmp/numeric(2*i+3));
1242 /** Absolute value. */
1243 numeric abs(numeric const & x)
1245 return ::abs(*x.value); // -> CLN
1248 /** Modulus (in positive representation).
1249 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1250 * sign of a or is zero. This is different from Maple's modp, where the sign
1251 * of b is ignored. It is in agreement with Mathematica's Mod.
1253 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1254 * integer, 0 otherwise. */
1255 numeric mod(numeric const & a, numeric const & b)
1257 if (a.is_integer() && b.is_integer()) {
1258 return ::mod(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1261 return numZERO(); // Throw?
1265 /** Modulus (in symmetric representation).
1266 * Equivalent to Maple's mods.
1268 * @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1269 numeric smod(numeric const & a, numeric const & b)
1271 if (a.is_integer() && b.is_integer()) {
1272 cl_I b2 = The(cl_I)(ceiling1(The(cl_I)(*b.value) / 2)) - 1;
1273 return ::mod(The(cl_I)(*a.value) + b2, The(cl_I)(*b.value)) - b2;
1275 return numZERO(); // Throw?
1279 /** Numeric integer remainder.
1280 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1281 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1282 * sign of a or is zero.
1284 * @return remainder of a/b if both are integer, 0 otherwise. */
1285 numeric irem(numeric const & a, numeric const & b)
1287 if (a.is_integer() && b.is_integer()) {
1288 return ::rem(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1291 return numZERO(); // Throw?
1295 /** Numeric integer remainder.
1296 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1297 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1298 * and irem(a,b) has the sign of a or is zero.
1300 * @return remainder of a/b and quotient stored in q if both are integer,
1302 numeric irem(numeric const & a, numeric const & b, numeric & q)
1304 if (a.is_integer() && b.is_integer()) { // -> CLN
1305 cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1306 q = rem_quo.quotient;
1307 return rem_quo.remainder;
1311 return numZERO(); // Throw?
1315 /** Numeric integer quotient.
1316 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1318 * @return truncated quotient of a/b if both are integer, 0 otherwise. */
1319 numeric iquo(numeric const & a, numeric const & b)
1321 if (a.is_integer() && b.is_integer()) {
1322 return truncate1(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1324 return numZERO(); // Throw?
1328 /** Numeric integer quotient.
1329 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1330 * r == a - iquo(a,b,r)*b.
1332 * @return truncated quotient of a/b and remainder stored in r if both are
1333 * integer, 0 otherwise. */
1334 numeric iquo(numeric const & a, numeric const & b, numeric & r)
1336 if (a.is_integer() && b.is_integer()) { // -> CLN
1337 cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1338 r = rem_quo.remainder;
1339 return rem_quo.quotient;
1342 return numZERO(); // Throw?
1346 /** Numeric square root.
1347 * If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4)
1348 * should return integer 2.
1350 * @param z numeric argument
1351 * @return square root of z. Branch cut along negative real axis, the negative
1352 * real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part
1353 * where imag(z)>0. */
1354 numeric sqrt(numeric const & z)
1356 return ::sqrt(*z.value); // -> CLN
1359 /** Integer numeric square root. */
1360 numeric isqrt(numeric const & x)
1362 if (x.is_integer()) {
1364 ::isqrt(The(cl_I)(*x.value), &root); // -> CLN
1367 return numZERO(); // Throw?
1370 /** Greatest Common Divisor.
1372 * @return The GCD of two numbers if both are integer, a numerical 1
1373 * if they are not. */
1374 numeric gcd(numeric const & a, numeric const & b)
1376 if (a.is_integer() && b.is_integer())
1377 return ::gcd(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1382 /** Least Common Multiple.
1384 * @return The LCM of two numbers if both are integer, the product of those
1385 * two numbers if they are not. */
1386 numeric lcm(numeric const & a, numeric const & b)
1388 if (a.is_integer() && b.is_integer())
1389 return ::lcm(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1391 return *a.value * *b.value;
1396 return numeric(cl_pi(cl_default_float_format)); // -> CLN
1399 ex EulerGammaEvalf(void)
1401 return numeric(cl_eulerconst(cl_default_float_format)); // -> CLN
1404 ex CatalanEvalf(void)
1406 return numeric(cl_catalanconst(cl_default_float_format)); // -> CLN
1409 // It initializes to 17 digits, because in CLN cl_float_format(17) turns out to
1410 // be 61 (<64) while cl_float_format(18)=65. We want to have a cl_LF instead
1411 // of cl_SF, cl_FF or cl_DF but everything else is basically arbitrary.
1412 _numeric_digits::_numeric_digits()
1417 cl_default_float_format = cl_float_format(17);
1420 _numeric_digits& _numeric_digits::operator=(long prec)
1423 cl_default_float_format = cl_float_format(prec);
1427 _numeric_digits::operator long()
1429 return (long)digits;
1432 void _numeric_digits::print(ostream & os) const
1434 debugmsg("_numeric_digits print", LOGLEVEL_PRINT);
1438 ostream& operator<<(ostream& os, _numeric_digits const & e)
1445 // static member variables
1450 bool _numeric_digits::too_late = false;
1452 /** Accuracy in decimal digits. Only object of this type! Can be set using
1453 * assignment from C++ unsigned ints and evaluated like any built-in type. */
1454 _numeric_digits Digits;
1456 } // namespace GiNaC