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-2000 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
30 #include <strstream> //!!
39 // CLN should not pollute the global namespace, hence we include it here
40 // instead of in some header file where it would propagate to other parts:
47 #ifndef NO_GINAC_NAMESPACE
49 #endif // ndef NO_GINAC_NAMESPACE
51 // linker has no problems finding text symbols for numerator or denominator
54 GINAC_IMPLEMENT_REGISTERED_CLASS(numeric, basic)
57 // default constructor, destructor, copy constructor assignment
58 // operator and helpers
63 /** default ctor. Numerically it initializes to an integer zero. */
64 numeric::numeric() : basic(TINFO_numeric)
66 debugmsg("numeric default constructor", LOGLEVEL_CONSTRUCT);
70 setflag(status_flags::evaluated|
71 status_flags::hash_calculated);
76 debugmsg("numeric destructor" ,LOGLEVEL_DESTRUCT);
80 numeric::numeric(const numeric & other)
82 debugmsg("numeric copy constructor", LOGLEVEL_CONSTRUCT);
86 const numeric & numeric::operator=(const numeric & other)
88 debugmsg("numeric operator=", LOGLEVEL_ASSIGNMENT);
98 void numeric::copy(const numeric & other)
101 value = new cl_N(*other.value);
104 void numeric::destroy(bool call_parent)
107 if (call_parent) basic::destroy(call_parent);
111 // other constructors
116 numeric::numeric(int i) : basic(TINFO_numeric)
118 debugmsg("numeric constructor from int",LOGLEVEL_CONSTRUCT);
119 // Not the whole int-range is available if we don't cast to long
120 // first. This is due to the behaviour of the cl_I-ctor, which
121 // emphasizes efficiency:
122 value = new cl_I((long) i);
124 setflag(status_flags::evaluated|
125 status_flags::hash_calculated);
128 numeric::numeric(unsigned int i) : basic(TINFO_numeric)
130 debugmsg("numeric constructor from uint",LOGLEVEL_CONSTRUCT);
131 // Not the whole uint-range is available if we don't cast to ulong
132 // first. This is due to the behaviour of the cl_I-ctor, which
133 // emphasizes efficiency:
134 value = new cl_I((unsigned long)i);
136 setflag(status_flags::evaluated|
137 status_flags::hash_calculated);
140 numeric::numeric(long i) : basic(TINFO_numeric)
142 debugmsg("numeric constructor from long",LOGLEVEL_CONSTRUCT);
145 setflag(status_flags::evaluated|
146 status_flags::hash_calculated);
149 numeric::numeric(unsigned long i) : basic(TINFO_numeric)
151 debugmsg("numeric constructor from ulong",LOGLEVEL_CONSTRUCT);
154 setflag(status_flags::evaluated|
155 status_flags::hash_calculated);
158 /** Ctor for rational numerics a/b.
160 * @exception overflow_error (division by zero) */
161 numeric::numeric(long numer, long denom) : basic(TINFO_numeric)
163 debugmsg("numeric constructor from long/long",LOGLEVEL_CONSTRUCT);
165 throw (std::overflow_error("division by zero"));
166 value = new cl_I(numer);
167 *value = *value / cl_I(denom);
169 setflag(status_flags::evaluated|
170 status_flags::hash_calculated);
173 numeric::numeric(double d) : basic(TINFO_numeric)
175 debugmsg("numeric constructor from double",LOGLEVEL_CONSTRUCT);
176 // We really want to explicitly use the type cl_LF instead of the
177 // more general cl_F, since that would give us a cl_DF only which
178 // will not be promoted to cl_LF if overflow occurs:
180 *value = cl_float(d, cl_default_float_format);
182 setflag(status_flags::evaluated|
183 status_flags::hash_calculated);
186 numeric::numeric(char const *s) : basic(TINFO_numeric)
187 { // MISSING: treatment of complex and ints and rationals.
188 debugmsg("numeric constructor from string",LOGLEVEL_CONSTRUCT);
190 value = new cl_LF(s);
194 setflag(status_flags::evaluated|
195 status_flags::hash_calculated);
198 /** Ctor from CLN types. This is for the initiated user or internal use
200 numeric::numeric(cl_N const & z) : basic(TINFO_numeric)
202 debugmsg("numeric constructor from cl_N", LOGLEVEL_CONSTRUCT);
205 setflag(status_flags::evaluated|
206 status_flags::hash_calculated);
213 /** Construct object from archive_node. */
214 numeric::numeric(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
216 debugmsg("numeric constructor from archive_node", LOGLEVEL_CONSTRUCT);
219 // This is how it should be implemented but we have no istringstream here...
221 if (n.find_string("number", str)) {
222 istringstream s(str);
226 // Workaround for the above: read from strstream
228 if (n.find_string("number", str)) {
229 istrstream f(str.c_str(), str.size() + 1);
234 setflag(status_flags::evaluated|
235 status_flags::hash_calculated);
238 /** Unarchive the object. */
239 ex numeric::unarchive(const archive_node &n, const lst &sym_lst)
241 return (new numeric(n, sym_lst))->setflag(status_flags::dynallocated);
244 /** Archive the object. */
245 void numeric::archive(archive_node &n) const
247 inherited::archive(n);
249 // This is how it should be implemented but we have no ostringstream here...
252 n.add_string("number", s.str());
254 // Workaround for the above: write to strstream
256 ostrstream f(buf, 1024);
259 n.add_string("number", str);
264 // functions overriding virtual functions from bases classes
269 basic * numeric::duplicate() const
271 debugmsg("numeric duplicate", LOGLEVEL_DUPLICATE);
272 return new numeric(*this);
275 void numeric::print(ostream & os, unsigned upper_precedence) const
277 // The method print adds to the output so it blends more consistently
278 // together with the other routines and produces something compatible to
280 debugmsg("numeric print", LOGLEVEL_PRINT);
282 // case 1, real: x or -x
283 if ((precedence<=upper_precedence) && (!is_pos_integer())) {
284 os << "(" << *value << ")";
289 // case 2, imaginary: y*I or -y*I
290 if (realpart(*value) == 0) {
291 if ((precedence<=upper_precedence) && (imagpart(*value) < 0)) {
292 if (imagpart(*value) == -1) {
295 os << "(" << imagpart(*value) << "*I)";
298 if (imagpart(*value) == 1) {
301 if (imagpart (*value) == -1) {
304 os << imagpart(*value) << "*I";
309 // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I
310 if (precedence <= upper_precedence) os << "(";
311 os << realpart(*value);
312 if (imagpart(*value) < 0) {
313 if (imagpart(*value) == -1) {
316 os << imagpart(*value) << "*I";
319 if (imagpart(*value) == 1) {
322 os << "+" << imagpart(*value) << "*I";
325 if (precedence <= upper_precedence) os << ")";
331 void numeric::printraw(ostream & os) const
333 // The method printraw doesn't do much, it simply uses CLN's operator<<()
334 // for output, which is ugly but reliable. e.g: 2+2i
335 debugmsg("numeric printraw", LOGLEVEL_PRINT);
336 os << "numeric(" << *value << ")";
338 void numeric::printtree(ostream & os, unsigned indent) const
340 debugmsg("numeric printtree", LOGLEVEL_PRINT);
341 os << string(indent,' ') << *value
343 << "hash=" << hashvalue << " (0x" << hex << hashvalue << dec << ")"
344 << ", flags=" << flags << endl;
347 void numeric::printcsrc(ostream & os, unsigned type, unsigned upper_precedence) const
349 debugmsg("numeric print csrc", LOGLEVEL_PRINT);
350 ios::fmtflags oldflags = os.flags();
351 os.setf(ios::scientific);
352 if (is_rational() && !is_integer()) {
353 if (compare(_num0()) > 0) {
355 if (type == csrc_types::ctype_cl_N)
356 os << "cl_F(\"" << numer().evalf() << "\")";
358 os << numer().to_double();
361 if (type == csrc_types::ctype_cl_N)
362 os << "cl_F(\"" << -numer().evalf() << "\")";
364 os << -numer().to_double();
367 if (type == csrc_types::ctype_cl_N)
368 os << "cl_F(\"" << denom().evalf() << "\")";
370 os << denom().to_double();
373 if (type == csrc_types::ctype_cl_N)
374 os << "cl_F(\"" << evalf() << "\")";
381 bool numeric::info(unsigned inf) const
384 case info_flags::numeric:
385 case info_flags::polynomial:
386 case info_flags::rational_function:
388 case info_flags::real:
390 case info_flags::rational:
391 case info_flags::rational_polynomial:
392 return is_rational();
393 case info_flags::crational:
394 case info_flags::crational_polynomial:
395 return is_crational();
396 case info_flags::integer:
397 case info_flags::integer_polynomial:
399 case info_flags::cinteger:
400 case info_flags::cinteger_polynomial:
401 return is_cinteger();
402 case info_flags::positive:
403 return is_positive();
404 case info_flags::negative:
405 return is_negative();
406 case info_flags::nonnegative:
407 return compare(_num0())>=0;
408 case info_flags::posint:
409 return is_pos_integer();
410 case info_flags::negint:
411 return is_integer() && (compare(_num0())<0);
412 case info_flags::nonnegint:
413 return is_nonneg_integer();
414 case info_flags::even:
416 case info_flags::odd:
418 case info_flags::prime:
424 /** Cast numeric into a floating-point object. For example exact numeric(1) is
425 * returned as a 1.0000000000000000000000 and so on according to how Digits is
428 * @param level ignored, but needed for overriding basic::evalf.
429 * @return an ex-handle to a numeric. */
430 ex numeric::evalf(int level) const
432 // level can safely be discarded for numeric objects.
433 return numeric(cl_float(1.0, cl_default_float_format) * (*value)); // -> CLN
438 int numeric::compare_same_type(basic const & other) const
440 GINAC_ASSERT(is_exactly_of_type(other, numeric));
441 const numeric & o = static_cast<numeric &>(const_cast<basic &>(other));
443 if (*value == *o.value) {
450 bool numeric::is_equal_same_type(basic const & other) const
452 GINAC_ASSERT(is_exactly_of_type(other,numeric));
453 const numeric *o = static_cast<const numeric *>(&other);
459 unsigned numeric::calchash(void) const
461 double d=to_double();
467 return 0x88000000U+s*unsigned(d/0x07FF0000);
473 // new virtual functions which can be overridden by derived classes
479 // non-virtual functions in this class
484 /** Numerical addition method. Adds argument to *this and returns result as
485 * a new numeric object. */
486 numeric numeric::add(const numeric & other) const
488 return numeric((*value)+(*other.value));
491 /** Numerical subtraction method. Subtracts argument from *this and returns
492 * result as a new numeric object. */
493 numeric numeric::sub(const numeric & other) const
495 return numeric((*value)-(*other.value));
498 /** Numerical multiplication method. Multiplies *this and argument and returns
499 * result as a new numeric object. */
500 numeric numeric::mul(const numeric & other) const
502 static const numeric * _num1p=&_num1();
505 } else if (&other==_num1p) {
508 return numeric((*value)*(*other.value));
511 /** Numerical division method. Divides *this by argument and returns result as
512 * a new numeric object.
514 * @exception overflow_error (division by zero) */
515 numeric numeric::div(const numeric & other) const
517 if (::zerop(*other.value))
518 throw (std::overflow_error("division by zero"));
519 return numeric((*value)/(*other.value));
522 numeric numeric::power(const numeric & other) const
524 static const numeric * _num1p=&_num1();
527 if (::zerop(*value) && other.is_real() && ::minusp(realpart(*other.value)))
528 throw (std::overflow_error("division by zero"));
529 return numeric(::expt(*value,*other.value));
532 /** Inverse of a number. */
533 numeric numeric::inverse(void) const
535 return numeric(::recip(*value)); // -> CLN
538 const numeric & numeric::add_dyn(const numeric & other) const
540 return static_cast<const numeric &>((new numeric((*value)+(*other.value)))->
541 setflag(status_flags::dynallocated));
544 const numeric & numeric::sub_dyn(const numeric & other) const
546 return static_cast<const numeric &>((new numeric((*value)-(*other.value)))->
547 setflag(status_flags::dynallocated));
550 const numeric & numeric::mul_dyn(const numeric & other) const
552 static const numeric * _num1p=&_num1();
555 } else if (&other==_num1p) {
558 return static_cast<const numeric &>((new numeric((*value)*(*other.value)))->
559 setflag(status_flags::dynallocated));
562 const numeric & numeric::div_dyn(const numeric & other) const
564 if (::zerop(*other.value))
565 throw (std::overflow_error("division by zero"));
566 return static_cast<const numeric &>((new numeric((*value)/(*other.value)))->
567 setflag(status_flags::dynallocated));
570 const numeric & numeric::power_dyn(const numeric & other) const
572 static const numeric * _num1p=&_num1();
575 if (::zerop(*value) && other.is_real() && ::minusp(realpart(*other.value)))
576 throw (std::overflow_error("division by zero"));
577 return static_cast<const numeric &>((new numeric(::expt(*value,*other.value)))->
578 setflag(status_flags::dynallocated));
581 const numeric & numeric::operator=(int i)
583 return operator=(numeric(i));
586 const numeric & numeric::operator=(unsigned int i)
588 return operator=(numeric(i));
591 const numeric & numeric::operator=(long i)
593 return operator=(numeric(i));
596 const numeric & numeric::operator=(unsigned long i)
598 return operator=(numeric(i));
601 const numeric & numeric::operator=(double d)
603 return operator=(numeric(d));
606 const numeric & numeric::operator=(char const * s)
608 return operator=(numeric(s));
611 /** Return the complex half-plane (left or right) in which the number lies.
612 * csgn(x)==0 for x==0, csgn(x)==1 for Re(x)>0 or Re(x)=0 and Im(x)>0,
613 * csgn(x)==-1 for Re(x)<0 or Re(x)=0 and Im(x)<0.
615 * @see numeric::compare(const numeric & other) */
616 int numeric::csgn(void) const
620 if (!::zerop(realpart(*value))) {
621 if (::plusp(realpart(*value)))
626 if (::plusp(imagpart(*value)))
633 /** This method establishes a canonical order on all numbers. For complex
634 * numbers this is not possible in a mathematically consistent way but we need
635 * to establish some order and it ought to be fast. So we simply define it
636 * to be compatible with our method csgn.
638 * @return csgn(*this-other)
639 * @see numeric::csgn(void) */
640 int numeric::compare(const numeric & other) const
642 // Comparing two real numbers?
643 if (is_real() && other.is_real())
644 // Yes, just compare them
645 return ::cl_compare(The(cl_R)(*value), The(cl_R)(*other.value));
647 // No, first compare real parts
648 cl_signean real_cmp = ::cl_compare(realpart(*value), realpart(*other.value));
652 return ::cl_compare(imagpart(*value), imagpart(*other.value));
656 bool numeric::is_equal(const numeric & other) const
658 return (*value == *other.value);
661 /** True if object is zero. */
662 bool numeric::is_zero(void) const
664 return ::zerop(*value); // -> CLN
667 /** True if object is not complex and greater than zero. */
668 bool numeric::is_positive(void) const
671 return ::plusp(The(cl_R)(*value)); // -> CLN
675 /** True if object is not complex and less than zero. */
676 bool numeric::is_negative(void) const
679 return ::minusp(The(cl_R)(*value)); // -> CLN
683 /** True if object is a non-complex integer. */
684 bool numeric::is_integer(void) const
686 return ::instanceof(*value, cl_I_ring); // -> CLN
689 /** True if object is an exact integer greater than zero. */
690 bool numeric::is_pos_integer(void) const
692 return (is_integer() && ::plusp(The(cl_I)(*value))); // -> CLN
695 /** True if object is an exact integer greater or equal zero. */
696 bool numeric::is_nonneg_integer(void) const
698 return (is_integer() && !::minusp(The(cl_I)(*value))); // -> CLN
701 /** True if object is an exact even integer. */
702 bool numeric::is_even(void) const
704 return (is_integer() && ::evenp(The(cl_I)(*value))); // -> CLN
707 /** True if object is an exact odd integer. */
708 bool numeric::is_odd(void) const
710 return (is_integer() && ::oddp(The(cl_I)(*value))); // -> CLN
713 /** Probabilistic primality test.
715 * @return true if object is exact integer and prime. */
716 bool numeric::is_prime(void) const
718 return (is_integer() && ::isprobprime(The(cl_I)(*value))); // -> CLN
721 /** True if object is an exact rational number, may even be complex
722 * (denominator may be unity). */
723 bool numeric::is_rational(void) const
725 return ::instanceof(*value, cl_RA_ring); // -> CLN
728 /** True if object is a real integer, rational or float (but not complex). */
729 bool numeric::is_real(void) const
731 return ::instanceof(*value, cl_R_ring); // -> CLN
734 bool numeric::operator==(const numeric & other) const
736 return (*value == *other.value); // -> CLN
739 bool numeric::operator!=(const numeric & other) const
741 return (*value != *other.value); // -> CLN
744 /** True if object is element of the domain of integers extended by I, i.e. is
745 * of the form a+b*I, where a and b are integers. */
746 bool numeric::is_cinteger(void) const
748 if (::instanceof(*value, cl_I_ring))
750 else if (!is_real()) { // complex case, handle n+m*I
751 if (::instanceof(realpart(*value), cl_I_ring) &&
752 ::instanceof(imagpart(*value), cl_I_ring))
758 /** True if object is an exact rational number, may even be complex
759 * (denominator may be unity). */
760 bool numeric::is_crational(void) const
762 if (::instanceof(*value, cl_RA_ring))
764 else if (!is_real()) { // complex case, handle Q(i):
765 if (::instanceof(realpart(*value), cl_RA_ring) &&
766 ::instanceof(imagpart(*value), cl_RA_ring))
772 /** Numerical comparison: less.
774 * @exception invalid_argument (complex inequality) */
775 bool numeric::operator<(const numeric & other) const
777 if (is_real() && other.is_real())
778 return (bool)(The(cl_R)(*value) < The(cl_R)(*other.value)); // -> CLN
779 throw (std::invalid_argument("numeric::operator<(): complex inequality"));
780 return false; // make compiler shut up
783 /** Numerical comparison: less or equal.
785 * @exception invalid_argument (complex inequality) */
786 bool numeric::operator<=(const numeric & other) const
788 if (is_real() && other.is_real())
789 return (bool)(The(cl_R)(*value) <= The(cl_R)(*other.value)); // -> CLN
790 throw (std::invalid_argument("numeric::operator<=(): complex inequality"));
791 return false; // make compiler shut up
794 /** Numerical comparison: greater.
796 * @exception invalid_argument (complex inequality) */
797 bool numeric::operator>(const numeric & other) const
799 if (is_real() && other.is_real())
800 return (bool)(The(cl_R)(*value) > The(cl_R)(*other.value)); // -> CLN
801 throw (std::invalid_argument("numeric::operator>(): complex inequality"));
802 return false; // make compiler shut up
805 /** Numerical comparison: greater or equal.
807 * @exception invalid_argument (complex inequality) */
808 bool numeric::operator>=(const numeric & other) const
810 if (is_real() && other.is_real())
811 return (bool)(The(cl_R)(*value) >= The(cl_R)(*other.value)); // -> CLN
812 throw (std::invalid_argument("numeric::operator>=(): complex inequality"));
813 return false; // make compiler shut up
816 /** Converts numeric types to machine's int. You should check with is_integer()
817 * if the number is really an integer before calling this method. */
818 int numeric::to_int(void) const
820 GINAC_ASSERT(is_integer());
821 return ::cl_I_to_int(The(cl_I)(*value)); // -> CLN
824 /** Converts numeric types to machine's double. You should check with is_real()
825 * if the number is really not complex before calling this method. */
826 double numeric::to_double(void) const
828 GINAC_ASSERT(is_real());
829 return ::cl_double_approx(realpart(*value)); // -> CLN
832 /** Real part of a number. */
833 numeric numeric::real(void) const
835 return numeric(::realpart(*value)); // -> CLN
838 /** Imaginary part of a number. */
839 numeric numeric::imag(void) const
841 return numeric(::imagpart(*value)); // -> CLN
845 // Unfortunately, CLN did not provide an official way to access the numerator
846 // or denominator of a rational number (cl_RA). Doing some excavations in CLN
847 // one finds how it works internally in src/rational/cl_RA.h:
848 struct cl_heap_ratio : cl_heap {
853 inline cl_heap_ratio* TheRatio (const cl_N& obj)
854 { return (cl_heap_ratio*)(obj.pointer); }
855 #endif // ndef SANE_LINKER
857 /** Numerator. Computes the numerator of rational numbers, rationalized
858 * numerator of complex if real and imaginary part are both rational numbers
859 * (i.e numer(4/3+5/6*I) == 8+5*I), the number carrying the sign in all other
861 numeric numeric::numer(void) const
864 return numeric(*this);
867 else if (::instanceof(*value, cl_RA_ring)) {
868 return numeric(::numerator(The(cl_RA)(*value)));
870 else if (!is_real()) { // complex case, handle Q(i):
871 cl_R r = ::realpart(*value);
872 cl_R i = ::imagpart(*value);
873 if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_I_ring))
874 return numeric(*this);
875 if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_RA_ring))
876 return numeric(complex(r*::denominator(The(cl_RA)(i)), ::numerator(The(cl_RA)(i))));
877 if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_I_ring))
878 return numeric(complex(::numerator(The(cl_RA)(r)), i*::denominator(The(cl_RA)(r))));
879 if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_RA_ring)) {
880 cl_I s = lcm(::denominator(The(cl_RA)(r)), ::denominator(The(cl_RA)(i)));
881 return numeric(complex(::numerator(The(cl_RA)(r))*(exquo(s,::denominator(The(cl_RA)(r)))),
882 ::numerator(The(cl_RA)(i))*(exquo(s,::denominator(The(cl_RA)(i))))));
886 else if (instanceof(*value, cl_RA_ring)) {
887 return numeric(TheRatio(*value)->numerator);
889 else if (!is_real()) { // complex case, handle Q(i):
890 cl_R r = realpart(*value);
891 cl_R i = imagpart(*value);
892 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
893 return numeric(*this);
894 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
895 return numeric(complex(r*TheRatio(i)->denominator, TheRatio(i)->numerator));
896 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
897 return numeric(complex(TheRatio(r)->numerator, i*TheRatio(r)->denominator));
898 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) {
899 cl_I s = lcm(TheRatio(r)->denominator, TheRatio(i)->denominator);
900 return numeric(complex(TheRatio(r)->numerator*(exquo(s,TheRatio(r)->denominator)),
901 TheRatio(i)->numerator*(exquo(s,TheRatio(i)->denominator))));
904 #endif // def SANE_LINKER
905 // at least one float encountered
906 return numeric(*this);
909 /** Denominator. Computes the denominator of rational numbers, common integer
910 * denominator of complex if real and imaginary part are both rational numbers
911 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
912 numeric numeric::denom(void) const
918 if (instanceof(*value, cl_RA_ring)) {
919 return numeric(::denominator(The(cl_RA)(*value)));
921 if (!is_real()) { // complex case, handle Q(i):
922 cl_R r = realpart(*value);
923 cl_R i = imagpart(*value);
924 if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_I_ring))
926 if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_RA_ring))
927 return numeric(::denominator(The(cl_RA)(i)));
928 if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_I_ring))
929 return numeric(::denominator(The(cl_RA)(r)));
930 if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_RA_ring))
931 return numeric(lcm(::denominator(The(cl_RA)(r)), ::denominator(The(cl_RA)(i))));
934 if (instanceof(*value, cl_RA_ring)) {
935 return numeric(TheRatio(*value)->denominator);
937 if (!is_real()) { // complex case, handle Q(i):
938 cl_R r = realpart(*value);
939 cl_R i = imagpart(*value);
940 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
942 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
943 return numeric(TheRatio(i)->denominator);
944 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
945 return numeric(TheRatio(r)->denominator);
946 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring))
947 return numeric(lcm(TheRatio(r)->denominator, TheRatio(i)->denominator));
949 #endif // def SANE_LINKER
950 // at least one float encountered
954 /** Size in binary notation. For integers, this is the smallest n >= 0 such
955 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
956 * 2^(n-1) <= x < 2^n.
958 * @return number of bits (excluding sign) needed to represent that number
959 * in two's complement if it is an integer, 0 otherwise. */
960 int numeric::int_length(void) const
963 return ::integer_length(The(cl_I)(*value)); // -> CLN
970 // static member variables
975 unsigned numeric::precedence = 30;
981 const numeric some_numeric;
982 type_info const & typeid_numeric=typeid(some_numeric);
983 /** Imaginary unit. This is not a constant but a numeric since we are
984 * natively handing complex numbers anyways. */
985 const numeric I = numeric(complex(cl_I(0),cl_I(1)));
987 /** Exponential function.
989 * @return arbitrary precision numerical exp(x). */
990 numeric exp(const numeric & x)
992 return ::exp(*x.value); // -> CLN
995 /** Natural logarithm.
997 * @param z complex number
998 * @return arbitrary precision numerical log(x).
999 * @exception overflow_error (logarithmic singularity) */
1000 numeric log(const numeric & z)
1003 throw (std::overflow_error("log(): logarithmic singularity"));
1004 return ::log(*z.value); // -> CLN
1007 /** Numeric sine (trigonometric function).
1009 * @return arbitrary precision numerical sin(x). */
1010 numeric sin(const numeric & x)
1012 return ::sin(*x.value); // -> CLN
1015 /** Numeric cosine (trigonometric function).
1017 * @return arbitrary precision numerical cos(x). */
1018 numeric cos(const numeric & x)
1020 return ::cos(*x.value); // -> CLN
1023 /** Numeric tangent (trigonometric function).
1025 * @return arbitrary precision numerical tan(x). */
1026 numeric tan(const numeric & x)
1028 return ::tan(*x.value); // -> CLN
1031 /** Numeric inverse sine (trigonometric function).
1033 * @return arbitrary precision numerical asin(x). */
1034 numeric asin(const numeric & x)
1036 return ::asin(*x.value); // -> CLN
1039 /** Numeric inverse cosine (trigonometric function).
1041 * @return arbitrary precision numerical acos(x). */
1042 numeric acos(const numeric & x)
1044 return ::acos(*x.value); // -> CLN
1049 * @param z complex number
1051 * @exception overflow_error (logarithmic singularity) */
1052 numeric atan(const numeric & x)
1055 x.real().is_zero() &&
1056 !abs(x.imag()).is_equal(_num1()))
1057 throw (std::overflow_error("atan(): logarithmic singularity"));
1058 return ::atan(*x.value); // -> CLN
1063 * @param x real number
1064 * @param y real number
1065 * @return atan(y/x) */
1066 numeric atan(const numeric & y, const numeric & x)
1068 if (x.is_real() && y.is_real())
1069 return ::atan(realpart(*x.value), realpart(*y.value)); // -> CLN
1071 throw (std::invalid_argument("numeric::atan(): complex argument"));
1074 /** Numeric hyperbolic sine (trigonometric function).
1076 * @return arbitrary precision numerical sinh(x). */
1077 numeric sinh(const numeric & x)
1079 return ::sinh(*x.value); // -> CLN
1082 /** Numeric hyperbolic cosine (trigonometric function).
1084 * @return arbitrary precision numerical cosh(x). */
1085 numeric cosh(const numeric & x)
1087 return ::cosh(*x.value); // -> CLN
1090 /** Numeric hyperbolic tangent (trigonometric function).
1092 * @return arbitrary precision numerical tanh(x). */
1093 numeric tanh(const numeric & x)
1095 return ::tanh(*x.value); // -> CLN
1098 /** Numeric inverse hyperbolic sine (trigonometric function).
1100 * @return arbitrary precision numerical asinh(x). */
1101 numeric asinh(const numeric & x)
1103 return ::asinh(*x.value); // -> CLN
1106 /** Numeric inverse hyperbolic cosine (trigonometric function).
1108 * @return arbitrary precision numerical acosh(x). */
1109 numeric acosh(const numeric & x)
1111 return ::acosh(*x.value); // -> CLN
1114 /** Numeric inverse hyperbolic tangent (trigonometric function).
1116 * @return arbitrary precision numerical atanh(x). */
1117 numeric atanh(const numeric & x)
1119 return ::atanh(*x.value); // -> CLN
1122 /** Numeric evaluation of Riemann's Zeta function. Currently works only for
1123 * integer arguments. */
1124 numeric zeta(const numeric & x)
1126 // A dirty hack to allow for things like zeta(3.0), since CLN currently
1127 // only knows about integer arguments and zeta(3).evalf() automatically
1128 // cascades down to zeta(3.0).evalf(). The trick is to rely on 3.0-3
1129 // being an exact zero for CLN, which can be tested and then we can just
1130 // pass the number casted to an int:
1132 int aux = (int)(::cl_double_approx(realpart(*x.value)));
1133 if (zerop(*x.value-aux))
1134 return ::cl_zeta(aux); // -> CLN
1136 clog << "zeta(" << x
1137 << "): Does anybody know good way to calculate this numerically?"
1142 /** The gamma function.
1143 * This is only a stub! */
1144 numeric gamma(const numeric & x)
1146 clog << "gamma(" << x
1147 << "): Does anybody know good way to calculate this numerically?"
1152 /** The psi function (aka polygamma function).
1153 * This is only a stub! */
1154 numeric psi(const numeric & x)
1157 << "): Does anybody know good way to calculate this numerically?"
1162 /** The psi functions (aka polygamma functions).
1163 * This is only a stub! */
1164 numeric psi(const numeric & n, const numeric & x)
1166 clog << "psi(" << n << "," << x
1167 << "): Does anybody know good way to calculate this numerically?"
1172 /** Factorial combinatorial function.
1174 * @exception range_error (argument must be integer >= 0) */
1175 numeric factorial(const numeric & nn)
1177 if (!nn.is_nonneg_integer())
1178 throw (std::range_error("numeric::factorial(): argument must be integer >= 0"));
1179 return numeric(::factorial(nn.to_int())); // -> CLN
1182 /** The double factorial combinatorial function. (Scarcely used, but still
1183 * useful in cases, like for exact results of Gamma(n+1/2) for instance.)
1185 * @param n integer argument >= -1
1186 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == (-1)!! == 1
1187 * @exception range_error (argument must be integer >= -1) */
1188 numeric doublefactorial(const numeric & nn)
1190 if (nn == numeric(-1)) {
1193 if (!nn.is_nonneg_integer()) {
1194 throw (std::range_error("numeric::doublefactorial(): argument must be integer >= -1"));
1196 return numeric(::doublefactorial(nn.to_int())); // -> CLN
1199 /** The Binomial coefficients. It computes the binomial coefficients. For
1200 * integer n and k and positive n this is the number of ways of choosing k
1201 * objects from n distinct objects. If n is negative, the formula
1202 * binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */
1203 numeric binomial(const numeric & n, const numeric & k)
1205 if (n.is_integer() && k.is_integer()) {
1206 if (n.is_nonneg_integer()) {
1207 if (k.compare(n)!=1 && k.compare(_num0())!=-1)
1208 return numeric(::binomial(n.to_int(),k.to_int())); // -> CLN
1212 return _num_1().power(k)*binomial(k-n-_num1(),k);
1216 // should really be gamma(n+1)/(gamma(r+1)/gamma(n-r+1) or a suitable limit
1217 throw (std::range_error("numeric::binomial(): donĀ“t know how to evaluate that."));
1220 /** Bernoulli number. The nth Bernoulli number is the coefficient of x^n/n!
1221 * in the expansion of the function x/(e^x-1).
1223 * @return the nth Bernoulli number (a rational number).
1224 * @exception range_error (argument must be integer >= 0) */
1225 numeric bernoulli(const numeric & nn)
1227 if (!nn.is_integer() || nn.is_negative())
1228 throw (std::range_error("numeric::bernoulli(): argument must be integer >= 0"));
1231 if (!nn.compare(_num1()))
1232 return numeric(-1,2);
1235 // Until somebody has the Blues and comes up with a much better idea and
1236 // codes it (preferably in CLN) we make this a remembering function which
1237 // computes its results using the formula
1238 // B(nn) == - 1/(nn+1) * sum_{k=0}^{nn-1}(binomial(nn+1,k)*B(k))
1240 static vector<numeric> results;
1241 static int highest_result = -1;
1242 int n = nn.sub(_num2()).div(_num2()).to_int();
1243 if (n <= highest_result)
1245 if (results.capacity() < (unsigned)(n+1))
1246 results.reserve(n+1);
1248 numeric tmp; // used to store the sum
1249 for (int i=highest_result+1; i<=n; ++i) {
1250 // the first two elements:
1251 tmp = numeric(-2*i-1,2);
1252 // accumulate the remaining elements:
1253 for (int j=0; j<i; ++j)
1254 tmp += binomial(numeric(2*i+3),numeric(j*2+2))*results[j];
1255 // divide by -(nn+1) and store result:
1256 results.push_back(-tmp/numeric(2*i+3));
1262 /** Absolute value. */
1263 numeric abs(const numeric & x)
1265 return ::abs(*x.value); // -> CLN
1268 /** Modulus (in positive representation).
1269 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1270 * sign of a or is zero. This is different from Maple's modp, where the sign
1271 * of b is ignored. It is in agreement with Mathematica's Mod.
1273 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1274 * integer, 0 otherwise. */
1275 numeric mod(const numeric & a, const numeric & b)
1277 if (a.is_integer() && b.is_integer())
1278 return ::mod(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1280 return _num0(); // Throw?
1283 /** Modulus (in symmetric representation).
1284 * Equivalent to Maple's mods.
1286 * @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1287 numeric smod(const numeric & a, const numeric & b)
1289 // FIXME: Should this become a member function?
1290 if (a.is_integer() && b.is_integer()) {
1291 cl_I b2 = The(cl_I)(ceiling1(The(cl_I)(*b.value) / 2)) - 1;
1292 return ::mod(The(cl_I)(*a.value) + b2, The(cl_I)(*b.value)) - b2;
1294 return _num0(); // Throw?
1297 /** Numeric integer remainder.
1298 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1299 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1300 * sign of a or is zero.
1302 * @return remainder of a/b if both are integer, 0 otherwise. */
1303 numeric irem(const numeric & a, const numeric & b)
1305 if (a.is_integer() && b.is_integer())
1306 return ::rem(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1308 return _num0(); // Throw?
1311 /** Numeric integer remainder.
1312 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1313 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1314 * and irem(a,b) has the sign of a or is zero.
1316 * @return remainder of a/b and quotient stored in q if both are integer,
1318 numeric irem(const numeric & a, const numeric & b, numeric & q)
1320 if (a.is_integer() && b.is_integer()) { // -> CLN
1321 cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1322 q = rem_quo.quotient;
1323 return rem_quo.remainder;
1327 return _num0(); // Throw?
1331 /** Numeric integer quotient.
1332 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1334 * @return truncated quotient of a/b if both are integer, 0 otherwise. */
1335 numeric iquo(const numeric & a, const numeric & b)
1337 if (a.is_integer() && b.is_integer())
1338 return truncate1(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1340 return _num0(); // Throw?
1343 /** Numeric integer quotient.
1344 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1345 * r == a - iquo(a,b,r)*b.
1347 * @return truncated quotient of a/b and remainder stored in r if both are
1348 * integer, 0 otherwise. */
1349 numeric iquo(const numeric & a, const numeric & b, numeric & r)
1351 if (a.is_integer() && b.is_integer()) { // -> CLN
1352 cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1353 r = rem_quo.remainder;
1354 return rem_quo.quotient;
1357 return _num0(); // Throw?
1361 /** Numeric square root.
1362 * If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4)
1363 * should return integer 2.
1365 * @param z numeric argument
1366 * @return square root of z. Branch cut along negative real axis, the negative
1367 * real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part
1368 * where imag(z)>0. */
1369 numeric sqrt(const numeric & z)
1371 return ::sqrt(*z.value); // -> CLN
1374 /** Integer numeric square root. */
1375 numeric isqrt(const numeric & x)
1377 if (x.is_integer()) {
1379 ::isqrt(The(cl_I)(*x.value), &root); // -> CLN
1382 return _num0(); // Throw?
1385 /** Greatest Common Divisor.
1387 * @return The GCD of two numbers if both are integer, a numerical 1
1388 * if they are not. */
1389 numeric gcd(const numeric & a, const numeric & b)
1391 if (a.is_integer() && b.is_integer())
1392 return ::gcd(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1397 /** Least Common Multiple.
1399 * @return The LCM of two numbers if both are integer, the product of those
1400 * two numbers if they are not. */
1401 numeric lcm(const numeric & a, const numeric & b)
1403 if (a.is_integer() && b.is_integer())
1404 return ::lcm(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1406 return *a.value * *b.value;
1411 return numeric(cl_pi(cl_default_float_format)); // -> CLN
1414 ex EulerGammaEvalf(void)
1416 return numeric(cl_eulerconst(cl_default_float_format)); // -> CLN
1419 ex CatalanEvalf(void)
1421 return numeric(cl_catalanconst(cl_default_float_format)); // -> CLN
1424 // It initializes to 17 digits, because in CLN cl_float_format(17) turns out to
1425 // be 61 (<64) while cl_float_format(18)=65. We want to have a cl_LF instead
1426 // of cl_SF, cl_FF or cl_DF but everything else is basically arbitrary.
1427 _numeric_digits::_numeric_digits()
1432 cl_default_float_format = cl_float_format(17);
1435 _numeric_digits& _numeric_digits::operator=(long prec)
1438 cl_default_float_format = cl_float_format(prec);
1442 _numeric_digits::operator long()
1444 return (long)digits;
1447 void _numeric_digits::print(ostream & os) const
1449 debugmsg("_numeric_digits print", LOGLEVEL_PRINT);
1453 ostream& operator<<(ostream& os, _numeric_digits const & e)
1460 // static member variables
1465 bool _numeric_digits::too_late = false;
1467 /** Accuracy in decimal digits. Only object of this type! Can be set using
1468 * assignment from C++ unsigned ints and evaluated like any built-in type. */
1469 _numeric_digits Digits;
1471 #ifndef NO_GINAC_NAMESPACE
1472 } // namespace GiNaC
1473 #endif // ndef NO_GINAC_NAMESPACE