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.
41 // Also, we only need a subset of CLN, so we don't include the complete cln.h:
43 #include <cln/cl_integer_io.h>
44 #include <cln/cl_integer_ring.h>
45 #include <cln/cl_rational_io.h>
46 #include <cln/cl_rational_ring.h>
47 #include <cln/cl_lfloat_class.h>
48 #include <cln/cl_lfloat_io.h>
49 #include <cln/cl_real_io.h>
50 #include <cln/cl_real_ring.h>
51 #include <cln/cl_complex_io.h>
52 #include <cln/cl_complex_ring.h>
53 #include <cln/cl_numtheory.h>
55 #include <cl_integer_io.h>
56 #include <cl_integer_ring.h>
57 #include <cl_rational_io.h>
58 #include <cl_rational_ring.h>
59 #include <cl_lfloat_class.h>
60 #include <cl_lfloat_io.h>
61 #include <cl_real_io.h>
62 #include <cl_real_ring.h>
63 #include <cl_complex_io.h>
64 #include <cl_complex_ring.h>
65 #include <cl_numtheory.h>
68 #ifndef NO_GINAC_NAMESPACE
70 #endif // ndef NO_GINAC_NAMESPACE
72 // linker has no problems finding text symbols for numerator or denominator
75 GINAC_IMPLEMENT_REGISTERED_CLASS(numeric, basic)
78 // default constructor, destructor, copy constructor assignment
79 // operator and helpers
84 /** default ctor. Numerically it initializes to an integer zero. */
85 numeric::numeric() : basic(TINFO_numeric)
87 debugmsg("numeric default constructor", LOGLEVEL_CONSTRUCT);
91 setflag(status_flags::evaluated|
92 status_flags::hash_calculated);
97 debugmsg("numeric destructor" ,LOGLEVEL_DESTRUCT);
101 numeric::numeric(const numeric & other)
103 debugmsg("numeric copy constructor", LOGLEVEL_CONSTRUCT);
107 const numeric & numeric::operator=(const numeric & other)
109 debugmsg("numeric operator=", LOGLEVEL_ASSIGNMENT);
110 if (this != &other) {
119 void numeric::copy(const numeric & other)
122 value = new cl_N(*other.value);
125 void numeric::destroy(bool call_parent)
128 if (call_parent) basic::destroy(call_parent);
132 // other constructors
137 numeric::numeric(int i) : basic(TINFO_numeric)
139 debugmsg("numeric constructor from int",LOGLEVEL_CONSTRUCT);
140 // Not the whole int-range is available if we don't cast to long
141 // first. This is due to the behaviour of the cl_I-ctor, which
142 // emphasizes efficiency:
143 value = new cl_I((long) i);
145 setflag(status_flags::evaluated|
146 status_flags::hash_calculated);
149 numeric::numeric(unsigned int i) : basic(TINFO_numeric)
151 debugmsg("numeric constructor from uint",LOGLEVEL_CONSTRUCT);
152 // Not the whole uint-range is available if we don't cast to ulong
153 // first. This is due to the behaviour of the cl_I-ctor, which
154 // emphasizes efficiency:
155 value = new cl_I((unsigned long)i);
157 setflag(status_flags::evaluated|
158 status_flags::hash_calculated);
161 numeric::numeric(long i) : basic(TINFO_numeric)
163 debugmsg("numeric constructor from long",LOGLEVEL_CONSTRUCT);
166 setflag(status_flags::evaluated|
167 status_flags::hash_calculated);
170 numeric::numeric(unsigned long i) : basic(TINFO_numeric)
172 debugmsg("numeric constructor from ulong",LOGLEVEL_CONSTRUCT);
175 setflag(status_flags::evaluated|
176 status_flags::hash_calculated);
179 /** Ctor for rational numerics a/b.
181 * @exception overflow_error (division by zero) */
182 numeric::numeric(long numer, long denom) : basic(TINFO_numeric)
184 debugmsg("numeric constructor from long/long",LOGLEVEL_CONSTRUCT);
186 throw (std::overflow_error("division by zero"));
187 value = new cl_I(numer);
188 *value = *value / cl_I(denom);
190 setflag(status_flags::evaluated|
191 status_flags::hash_calculated);
194 numeric::numeric(double d) : basic(TINFO_numeric)
196 debugmsg("numeric constructor from double",LOGLEVEL_CONSTRUCT);
197 // We really want to explicitly use the type cl_LF instead of the
198 // more general cl_F, since that would give us a cl_DF only which
199 // will not be promoted to cl_LF if overflow occurs:
201 *value = cl_float(d, cl_default_float_format);
203 setflag(status_flags::evaluated|
204 status_flags::hash_calculated);
207 numeric::numeric(const char *s) : basic(TINFO_numeric)
208 { // MISSING: treatment of complex and ints and rationals.
209 debugmsg("numeric constructor from string",LOGLEVEL_CONSTRUCT);
211 value = new cl_LF(s);
215 setflag(status_flags::evaluated|
216 status_flags::hash_calculated);
219 /** Ctor from CLN types. This is for the initiated user or internal use
221 numeric::numeric(cl_N const & z) : basic(TINFO_numeric)
223 debugmsg("numeric constructor from cl_N", LOGLEVEL_CONSTRUCT);
226 setflag(status_flags::evaluated|
227 status_flags::hash_calculated);
234 /** Construct object from archive_node. */
235 numeric::numeric(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
237 debugmsg("numeric constructor from archive_node", LOGLEVEL_CONSTRUCT);
240 // This is how it should be implemented but we have no istringstream here...
242 if (n.find_string("number", str)) {
243 istringstream s(str);
247 // Workaround for the above: read from strstream
249 if (n.find_string("number", str)) {
250 istrstream f(str.c_str(), str.size() + 1);
255 setflag(status_flags::evaluated|
256 status_flags::hash_calculated);
259 /** Unarchive the object. */
260 ex numeric::unarchive(const archive_node &n, const lst &sym_lst)
262 return (new numeric(n, sym_lst))->setflag(status_flags::dynallocated);
265 /** Archive the object. */
266 void numeric::archive(archive_node &n) const
268 inherited::archive(n);
270 // This is how it should be implemented but we have no ostringstream here...
273 n.add_string("number", s.str());
275 // Workaround for the above: write to strstream
277 ostrstream f(buf, 1024);
280 n.add_string("number", str);
285 // functions overriding virtual functions from bases classes
290 basic * numeric::duplicate() const
292 debugmsg("numeric duplicate", LOGLEVEL_DUPLICATE);
293 return new numeric(*this);
296 void numeric::print(ostream & os, unsigned upper_precedence) const
298 // The method print adds to the output so it blends more consistently
299 // together with the other routines and produces something compatible to
301 debugmsg("numeric print", LOGLEVEL_PRINT);
303 // case 1, real: x or -x
304 if ((precedence<=upper_precedence) && (!is_pos_integer())) {
305 os << "(" << *value << ")";
310 // case 2, imaginary: y*I or -y*I
311 if (realpart(*value) == 0) {
312 if ((precedence<=upper_precedence) && (imagpart(*value) < 0)) {
313 if (imagpart(*value) == -1) {
316 os << "(" << imagpart(*value) << "*I)";
319 if (imagpart(*value) == 1) {
322 if (imagpart (*value) == -1) {
325 os << imagpart(*value) << "*I";
330 // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I
331 if (precedence <= upper_precedence) os << "(";
332 os << realpart(*value);
333 if (imagpart(*value) < 0) {
334 if (imagpart(*value) == -1) {
337 os << imagpart(*value) << "*I";
340 if (imagpart(*value) == 1) {
343 os << "+" << imagpart(*value) << "*I";
346 if (precedence <= upper_precedence) os << ")";
352 void numeric::printraw(ostream & os) const
354 // The method printraw doesn't do much, it simply uses CLN's operator<<()
355 // for output, which is ugly but reliable. e.g: 2+2i
356 debugmsg("numeric printraw", LOGLEVEL_PRINT);
357 os << "numeric(" << *value << ")";
359 void numeric::printtree(ostream & os, unsigned indent) const
361 debugmsg("numeric printtree", LOGLEVEL_PRINT);
362 os << string(indent,' ') << *value
364 << "hash=" << hashvalue << " (0x" << hex << hashvalue << dec << ")"
365 << ", flags=" << flags << endl;
368 void numeric::printcsrc(ostream & os, unsigned type, unsigned upper_precedence) const
370 debugmsg("numeric print csrc", LOGLEVEL_PRINT);
371 ios::fmtflags oldflags = os.flags();
372 os.setf(ios::scientific);
373 if (is_rational() && !is_integer()) {
374 if (compare(_num0()) > 0) {
376 if (type == csrc_types::ctype_cl_N)
377 os << "cl_F(\"" << numer().evalf() << "\")";
379 os << numer().to_double();
382 if (type == csrc_types::ctype_cl_N)
383 os << "cl_F(\"" << -numer().evalf() << "\")";
385 os << -numer().to_double();
388 if (type == csrc_types::ctype_cl_N)
389 os << "cl_F(\"" << denom().evalf() << "\")";
391 os << denom().to_double();
394 if (type == csrc_types::ctype_cl_N)
395 os << "cl_F(\"" << evalf() << "\")";
402 bool numeric::info(unsigned inf) const
405 case info_flags::numeric:
406 case info_flags::polynomial:
407 case info_flags::rational_function:
409 case info_flags::real:
411 case info_flags::rational:
412 case info_flags::rational_polynomial:
413 return is_rational();
414 case info_flags::crational:
415 case info_flags::crational_polynomial:
416 return is_crational();
417 case info_flags::integer:
418 case info_flags::integer_polynomial:
420 case info_flags::cinteger:
421 case info_flags::cinteger_polynomial:
422 return is_cinteger();
423 case info_flags::positive:
424 return is_positive();
425 case info_flags::negative:
426 return is_negative();
427 case info_flags::nonnegative:
428 return compare(_num0())>=0;
429 case info_flags::posint:
430 return is_pos_integer();
431 case info_flags::negint:
432 return is_integer() && (compare(_num0())<0);
433 case info_flags::nonnegint:
434 return is_nonneg_integer();
435 case info_flags::even:
437 case info_flags::odd:
439 case info_flags::prime:
445 /** Cast numeric into a floating-point object. For example exact numeric(1) is
446 * returned as a 1.0000000000000000000000 and so on according to how Digits is
449 * @param level ignored, but needed for overriding basic::evalf.
450 * @return an ex-handle to a numeric. */
451 ex numeric::evalf(int level) const
453 // level can safely be discarded for numeric objects.
454 return numeric(cl_float(1.0, cl_default_float_format) * (*value)); // -> CLN
459 int numeric::compare_same_type(const basic & other) const
461 GINAC_ASSERT(is_exactly_of_type(other, numeric));
462 const numeric & o = static_cast<numeric &>(const_cast<basic &>(other));
464 if (*value == *o.value) {
471 bool numeric::is_equal_same_type(const basic & other) const
473 GINAC_ASSERT(is_exactly_of_type(other,numeric));
474 const numeric *o = static_cast<const numeric *>(&other);
480 unsigned numeric::calchash(void) const
482 double d=to_double();
488 return 0x88000000U+s*unsigned(d/0x07FF0000);
494 // new virtual functions which can be overridden by derived classes
500 // non-virtual functions in this class
505 /** Numerical addition method. Adds argument to *this and returns result as
506 * a new numeric object. */
507 numeric numeric::add(const numeric & other) const
509 return numeric((*value)+(*other.value));
512 /** Numerical subtraction method. Subtracts argument from *this and returns
513 * result as a new numeric object. */
514 numeric numeric::sub(const numeric & other) const
516 return numeric((*value)-(*other.value));
519 /** Numerical multiplication method. Multiplies *this and argument and returns
520 * result as a new numeric object. */
521 numeric numeric::mul(const numeric & other) const
523 static const numeric * _num1p=&_num1();
526 } else if (&other==_num1p) {
529 return numeric((*value)*(*other.value));
532 /** Numerical division method. Divides *this by argument and returns result as
533 * a new numeric object.
535 * @exception overflow_error (division by zero) */
536 numeric numeric::div(const numeric & other) const
538 if (::zerop(*other.value))
539 throw (std::overflow_error("division by zero"));
540 return numeric((*value)/(*other.value));
543 numeric numeric::power(const numeric & other) const
545 static const numeric * _num1p=&_num1();
548 if (::zerop(*value) && other.is_real() && ::minusp(realpart(*other.value)))
549 throw (std::overflow_error("division by zero"));
550 return numeric(::expt(*value,*other.value));
553 /** Inverse of a number. */
554 numeric numeric::inverse(void) const
556 return numeric(::recip(*value)); // -> CLN
559 const numeric & numeric::add_dyn(const numeric & other) const
561 return static_cast<const numeric &>((new numeric((*value)+(*other.value)))->
562 setflag(status_flags::dynallocated));
565 const numeric & numeric::sub_dyn(const numeric & other) const
567 return static_cast<const numeric &>((new numeric((*value)-(*other.value)))->
568 setflag(status_flags::dynallocated));
571 const numeric & numeric::mul_dyn(const numeric & other) const
573 static const numeric * _num1p=&_num1();
576 } else if (&other==_num1p) {
579 return static_cast<const numeric &>((new numeric((*value)*(*other.value)))->
580 setflag(status_flags::dynallocated));
583 const numeric & numeric::div_dyn(const numeric & other) const
585 if (::zerop(*other.value))
586 throw (std::overflow_error("division by zero"));
587 return static_cast<const numeric &>((new numeric((*value)/(*other.value)))->
588 setflag(status_flags::dynallocated));
591 const numeric & numeric::power_dyn(const numeric & other) const
593 static const numeric * _num1p=&_num1();
596 if (::zerop(*value) && other.is_real() && ::minusp(realpart(*other.value)))
597 throw (std::overflow_error("division by zero"));
598 return static_cast<const numeric &>((new numeric(::expt(*value,*other.value)))->
599 setflag(status_flags::dynallocated));
602 const numeric & numeric::operator=(int i)
604 return operator=(numeric(i));
607 const numeric & numeric::operator=(unsigned int i)
609 return operator=(numeric(i));
612 const numeric & numeric::operator=(long i)
614 return operator=(numeric(i));
617 const numeric & numeric::operator=(unsigned long i)
619 return operator=(numeric(i));
622 const numeric & numeric::operator=(double d)
624 return operator=(numeric(d));
627 const numeric & numeric::operator=(const char * s)
629 return operator=(numeric(s));
632 /** Return the complex half-plane (left or right) in which the number lies.
633 * csgn(x)==0 for x==0, csgn(x)==1 for Re(x)>0 or Re(x)=0 and Im(x)>0,
634 * csgn(x)==-1 for Re(x)<0 or Re(x)=0 and Im(x)<0.
636 * @see numeric::compare(const numeric & other) */
637 int numeric::csgn(void) const
641 if (!::zerop(realpart(*value))) {
642 if (::plusp(realpart(*value)))
647 if (::plusp(imagpart(*value)))
654 /** This method establishes a canonical order on all numbers. For complex
655 * numbers this is not possible in a mathematically consistent way but we need
656 * to establish some order and it ought to be fast. So we simply define it
657 * to be compatible with our method csgn.
659 * @return csgn(*this-other)
660 * @see numeric::csgn(void) */
661 int numeric::compare(const numeric & other) const
663 // Comparing two real numbers?
664 if (is_real() && other.is_real())
665 // Yes, just compare them
666 return ::cl_compare(The(cl_R)(*value), The(cl_R)(*other.value));
668 // No, first compare real parts
669 cl_signean real_cmp = ::cl_compare(realpart(*value), realpart(*other.value));
673 return ::cl_compare(imagpart(*value), imagpart(*other.value));
677 bool numeric::is_equal(const numeric & other) const
679 return (*value == *other.value);
682 /** True if object is zero. */
683 bool numeric::is_zero(void) const
685 return ::zerop(*value); // -> CLN
688 /** True if object is not complex and greater than zero. */
689 bool numeric::is_positive(void) const
692 return ::plusp(The(cl_R)(*value)); // -> CLN
696 /** True if object is not complex and less than zero. */
697 bool numeric::is_negative(void) const
700 return ::minusp(The(cl_R)(*value)); // -> CLN
704 /** True if object is a non-complex integer. */
705 bool numeric::is_integer(void) const
707 return ::instanceof(*value, cl_I_ring); // -> CLN
710 /** True if object is an exact integer greater than zero. */
711 bool numeric::is_pos_integer(void) const
713 return (is_integer() && ::plusp(The(cl_I)(*value))); // -> CLN
716 /** True if object is an exact integer greater or equal zero. */
717 bool numeric::is_nonneg_integer(void) const
719 return (is_integer() && !::minusp(The(cl_I)(*value))); // -> CLN
722 /** True if object is an exact even integer. */
723 bool numeric::is_even(void) const
725 return (is_integer() && ::evenp(The(cl_I)(*value))); // -> CLN
728 /** True if object is an exact odd integer. */
729 bool numeric::is_odd(void) const
731 return (is_integer() && ::oddp(The(cl_I)(*value))); // -> CLN
734 /** Probabilistic primality test.
736 * @return true if object is exact integer and prime. */
737 bool numeric::is_prime(void) const
739 return (is_integer() && ::isprobprime(The(cl_I)(*value))); // -> CLN
742 /** True if object is an exact rational number, may even be complex
743 * (denominator may be unity). */
744 bool numeric::is_rational(void) const
746 return ::instanceof(*value, cl_RA_ring); // -> CLN
749 /** True if object is a real integer, rational or float (but not complex). */
750 bool numeric::is_real(void) const
752 return ::instanceof(*value, cl_R_ring); // -> CLN
755 bool numeric::operator==(const numeric & other) const
757 return (*value == *other.value); // -> CLN
760 bool numeric::operator!=(const numeric & other) const
762 return (*value != *other.value); // -> CLN
765 /** True if object is element of the domain of integers extended by I, i.e. is
766 * of the form a+b*I, where a and b are integers. */
767 bool numeric::is_cinteger(void) const
769 if (::instanceof(*value, cl_I_ring))
771 else if (!is_real()) { // complex case, handle n+m*I
772 if (::instanceof(realpart(*value), cl_I_ring) &&
773 ::instanceof(imagpart(*value), cl_I_ring))
779 /** True if object is an exact rational number, may even be complex
780 * (denominator may be unity). */
781 bool numeric::is_crational(void) const
783 if (::instanceof(*value, cl_RA_ring))
785 else if (!is_real()) { // complex case, handle Q(i):
786 if (::instanceof(realpart(*value), cl_RA_ring) &&
787 ::instanceof(imagpart(*value), cl_RA_ring))
793 /** Numerical comparison: less.
795 * @exception invalid_argument (complex inequality) */
796 bool numeric::operator<(const numeric & other) const
798 if (is_real() && other.is_real())
799 return (bool)(The(cl_R)(*value) < The(cl_R)(*other.value)); // -> CLN
800 throw (std::invalid_argument("numeric::operator<(): complex inequality"));
801 return false; // make compiler shut up
804 /** Numerical comparison: less or equal.
806 * @exception invalid_argument (complex inequality) */
807 bool numeric::operator<=(const numeric & other) const
809 if (is_real() && other.is_real())
810 return (bool)(The(cl_R)(*value) <= The(cl_R)(*other.value)); // -> CLN
811 throw (std::invalid_argument("numeric::operator<=(): complex inequality"));
812 return false; // make compiler shut up
815 /** Numerical comparison: greater.
817 * @exception invalid_argument (complex inequality) */
818 bool numeric::operator>(const numeric & other) const
820 if (is_real() && other.is_real())
821 return (bool)(The(cl_R)(*value) > The(cl_R)(*other.value)); // -> CLN
822 throw (std::invalid_argument("numeric::operator>(): complex inequality"));
823 return false; // make compiler shut up
826 /** Numerical comparison: greater or equal.
828 * @exception invalid_argument (complex inequality) */
829 bool numeric::operator>=(const numeric & other) const
831 if (is_real() && other.is_real())
832 return (bool)(The(cl_R)(*value) >= The(cl_R)(*other.value)); // -> CLN
833 throw (std::invalid_argument("numeric::operator>=(): complex inequality"));
834 return false; // make compiler shut up
837 /** Converts numeric types to machine's int. You should check with is_integer()
838 * if the number is really an integer before calling this method. */
839 int numeric::to_int(void) const
841 GINAC_ASSERT(is_integer());
842 return ::cl_I_to_int(The(cl_I)(*value)); // -> CLN
845 /** Converts numeric types to machine's double. You should check with is_real()
846 * if the number is really not complex before calling this method. */
847 double numeric::to_double(void) const
849 GINAC_ASSERT(is_real());
850 return ::cl_double_approx(realpart(*value)); // -> CLN
853 /** Real part of a number. */
854 numeric numeric::real(void) const
856 return numeric(::realpart(*value)); // -> CLN
859 /** Imaginary part of a number. */
860 numeric numeric::imag(void) const
862 return numeric(::imagpart(*value)); // -> CLN
866 // Unfortunately, CLN did not provide an official way to access the numerator
867 // or denominator of a rational number (cl_RA). Doing some excavations in CLN
868 // one finds how it works internally in src/rational/cl_RA.h:
869 struct cl_heap_ratio : cl_heap {
874 inline cl_heap_ratio* TheRatio (const cl_N& obj)
875 { return (cl_heap_ratio*)(obj.pointer); }
876 #endif // ndef SANE_LINKER
878 /** Numerator. Computes the numerator of rational numbers, rationalized
879 * numerator of complex if real and imaginary part are both rational numbers
880 * (i.e numer(4/3+5/6*I) == 8+5*I), the number carrying the sign in all other
882 numeric numeric::numer(void) const
885 return numeric(*this);
888 else if (::instanceof(*value, cl_RA_ring)) {
889 return numeric(::numerator(The(cl_RA)(*value)));
891 else if (!is_real()) { // complex case, handle Q(i):
892 cl_R r = ::realpart(*value);
893 cl_R i = ::imagpart(*value);
894 if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_I_ring))
895 return numeric(*this);
896 if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_RA_ring))
897 return numeric(complex(r*::denominator(The(cl_RA)(i)), ::numerator(The(cl_RA)(i))));
898 if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_I_ring))
899 return numeric(complex(::numerator(The(cl_RA)(r)), i*::denominator(The(cl_RA)(r))));
900 if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_RA_ring)) {
901 cl_I s = lcm(::denominator(The(cl_RA)(r)), ::denominator(The(cl_RA)(i)));
902 return numeric(complex(::numerator(The(cl_RA)(r))*(exquo(s,::denominator(The(cl_RA)(r)))),
903 ::numerator(The(cl_RA)(i))*(exquo(s,::denominator(The(cl_RA)(i))))));
907 else if (instanceof(*value, cl_RA_ring)) {
908 return numeric(TheRatio(*value)->numerator);
910 else if (!is_real()) { // complex case, handle Q(i):
911 cl_R r = realpart(*value);
912 cl_R i = imagpart(*value);
913 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
914 return numeric(*this);
915 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
916 return numeric(complex(r*TheRatio(i)->denominator, TheRatio(i)->numerator));
917 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
918 return numeric(complex(TheRatio(r)->numerator, i*TheRatio(r)->denominator));
919 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) {
920 cl_I s = lcm(TheRatio(r)->denominator, TheRatio(i)->denominator);
921 return numeric(complex(TheRatio(r)->numerator*(exquo(s,TheRatio(r)->denominator)),
922 TheRatio(i)->numerator*(exquo(s,TheRatio(i)->denominator))));
925 #endif // def SANE_LINKER
926 // at least one float encountered
927 return numeric(*this);
930 /** Denominator. Computes the denominator of rational numbers, common integer
931 * denominator of complex if real and imaginary part are both rational numbers
932 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
933 numeric numeric::denom(void) const
939 if (instanceof(*value, cl_RA_ring)) {
940 return numeric(::denominator(The(cl_RA)(*value)));
942 if (!is_real()) { // complex case, handle Q(i):
943 cl_R r = realpart(*value);
944 cl_R i = imagpart(*value);
945 if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_I_ring))
947 if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_RA_ring))
948 return numeric(::denominator(The(cl_RA)(i)));
949 if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_I_ring))
950 return numeric(::denominator(The(cl_RA)(r)));
951 if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_RA_ring))
952 return numeric(lcm(::denominator(The(cl_RA)(r)), ::denominator(The(cl_RA)(i))));
955 if (instanceof(*value, cl_RA_ring)) {
956 return numeric(TheRatio(*value)->denominator);
958 if (!is_real()) { // complex case, handle Q(i):
959 cl_R r = realpart(*value);
960 cl_R i = imagpart(*value);
961 if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
963 if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
964 return numeric(TheRatio(i)->denominator);
965 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
966 return numeric(TheRatio(r)->denominator);
967 if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring))
968 return numeric(lcm(TheRatio(r)->denominator, TheRatio(i)->denominator));
970 #endif // def SANE_LINKER
971 // at least one float encountered
975 /** Size in binary notation. For integers, this is the smallest n >= 0 such
976 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
977 * 2^(n-1) <= x < 2^n.
979 * @return number of bits (excluding sign) needed to represent that number
980 * in two's complement if it is an integer, 0 otherwise. */
981 int numeric::int_length(void) const
984 return ::integer_length(The(cl_I)(*value)); // -> CLN
991 // static member variables
996 unsigned numeric::precedence = 30;
1002 const numeric some_numeric;
1003 const type_info & typeid_numeric=typeid(some_numeric);
1004 /** Imaginary unit. This is not a constant but a numeric since we are
1005 * natively handing complex numbers anyways. */
1006 const numeric I = numeric(complex(cl_I(0),cl_I(1)));
1008 /** Exponential function.
1010 * @return arbitrary precision numerical exp(x). */
1011 numeric exp(const numeric & x)
1013 return ::exp(*x.value); // -> CLN
1016 /** Natural logarithm.
1018 * @param z complex number
1019 * @return arbitrary precision numerical log(x).
1020 * @exception overflow_error (logarithmic singularity) */
1021 numeric log(const numeric & z)
1024 throw (std::overflow_error("log(): logarithmic singularity"));
1025 return ::log(*z.value); // -> CLN
1028 /** Numeric sine (trigonometric function).
1030 * @return arbitrary precision numerical sin(x). */
1031 numeric sin(const numeric & x)
1033 return ::sin(*x.value); // -> CLN
1036 /** Numeric cosine (trigonometric function).
1038 * @return arbitrary precision numerical cos(x). */
1039 numeric cos(const numeric & x)
1041 return ::cos(*x.value); // -> CLN
1044 /** Numeric tangent (trigonometric function).
1046 * @return arbitrary precision numerical tan(x). */
1047 numeric tan(const numeric & x)
1049 return ::tan(*x.value); // -> CLN
1052 /** Numeric inverse sine (trigonometric function).
1054 * @return arbitrary precision numerical asin(x). */
1055 numeric asin(const numeric & x)
1057 return ::asin(*x.value); // -> CLN
1060 /** Numeric inverse cosine (trigonometric function).
1062 * @return arbitrary precision numerical acos(x). */
1063 numeric acos(const numeric & x)
1065 return ::acos(*x.value); // -> CLN
1070 * @param z complex number
1072 * @exception overflow_error (logarithmic singularity) */
1073 numeric atan(const numeric & x)
1076 x.real().is_zero() &&
1077 !abs(x.imag()).is_equal(_num1()))
1078 throw (std::overflow_error("atan(): logarithmic singularity"));
1079 return ::atan(*x.value); // -> CLN
1084 * @param x real number
1085 * @param y real number
1086 * @return atan(y/x) */
1087 numeric atan(const numeric & y, const numeric & x)
1089 if (x.is_real() && y.is_real())
1090 return ::atan(realpart(*x.value), realpart(*y.value)); // -> CLN
1092 throw (std::invalid_argument("numeric::atan(): complex argument"));
1095 /** Numeric hyperbolic sine (trigonometric function).
1097 * @return arbitrary precision numerical sinh(x). */
1098 numeric sinh(const numeric & x)
1100 return ::sinh(*x.value); // -> CLN
1103 /** Numeric hyperbolic cosine (trigonometric function).
1105 * @return arbitrary precision numerical cosh(x). */
1106 numeric cosh(const numeric & x)
1108 return ::cosh(*x.value); // -> CLN
1111 /** Numeric hyperbolic tangent (trigonometric function).
1113 * @return arbitrary precision numerical tanh(x). */
1114 numeric tanh(const numeric & x)
1116 return ::tanh(*x.value); // -> CLN
1119 /** Numeric inverse hyperbolic sine (trigonometric function).
1121 * @return arbitrary precision numerical asinh(x). */
1122 numeric asinh(const numeric & x)
1124 return ::asinh(*x.value); // -> CLN
1127 /** Numeric inverse hyperbolic cosine (trigonometric function).
1129 * @return arbitrary precision numerical acosh(x). */
1130 numeric acosh(const numeric & x)
1132 return ::acosh(*x.value); // -> CLN
1135 /** Numeric inverse hyperbolic tangent (trigonometric function).
1137 * @return arbitrary precision numerical atanh(x). */
1138 numeric atanh(const numeric & x)
1140 return ::atanh(*x.value); // -> CLN
1143 /** Numeric evaluation of Riemann's Zeta function. Currently works only for
1144 * integer arguments. */
1145 numeric zeta(const numeric & x)
1147 // A dirty hack to allow for things like zeta(3.0), since CLN currently
1148 // only knows about integer arguments and zeta(3).evalf() automatically
1149 // cascades down to zeta(3.0).evalf(). The trick is to rely on 3.0-3
1150 // being an exact zero for CLN, which can be tested and then we can just
1151 // pass the number casted to an int:
1153 int aux = (int)(::cl_double_approx(realpart(*x.value)));
1154 if (zerop(*x.value-aux))
1155 return ::cl_zeta(aux); // -> CLN
1157 clog << "zeta(" << x
1158 << "): Does anybody know good way to calculate this numerically?"
1163 /** The gamma function.
1164 * This is only a stub! */
1165 numeric gamma(const numeric & x)
1167 clog << "gamma(" << x
1168 << "): Does anybody know good way to calculate this numerically?"
1173 /** The psi function (aka polygamma function).
1174 * This is only a stub! */
1175 numeric psi(const numeric & x)
1178 << "): Does anybody know good way to calculate this numerically?"
1183 /** The psi functions (aka polygamma functions).
1184 * This is only a stub! */
1185 numeric psi(const numeric & n, const numeric & x)
1187 clog << "psi(" << n << "," << x
1188 << "): Does anybody know good way to calculate this numerically?"
1193 /** Factorial combinatorial function.
1195 * @exception range_error (argument must be integer >= 0) */
1196 numeric factorial(const numeric & nn)
1198 if (!nn.is_nonneg_integer())
1199 throw (std::range_error("numeric::factorial(): argument must be integer >= 0"));
1200 return numeric(::factorial(nn.to_int())); // -> CLN
1203 /** The double factorial combinatorial function. (Scarcely used, but still
1204 * useful in cases, like for exact results of Gamma(n+1/2) for instance.)
1206 * @param n integer argument >= -1
1207 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == (-1)!! == 1
1208 * @exception range_error (argument must be integer >= -1) */
1209 numeric doublefactorial(const numeric & nn)
1211 if (nn == numeric(-1)) {
1214 if (!nn.is_nonneg_integer()) {
1215 throw (std::range_error("numeric::doublefactorial(): argument must be integer >= -1"));
1217 return numeric(::doublefactorial(nn.to_int())); // -> CLN
1220 /** The Binomial coefficients. It computes the binomial coefficients. For
1221 * integer n and k and positive n this is the number of ways of choosing k
1222 * objects from n distinct objects. If n is negative, the formula
1223 * binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */
1224 numeric binomial(const numeric & n, const numeric & k)
1226 if (n.is_integer() && k.is_integer()) {
1227 if (n.is_nonneg_integer()) {
1228 if (k.compare(n)!=1 && k.compare(_num0())!=-1)
1229 return numeric(::binomial(n.to_int(),k.to_int())); // -> CLN
1233 return _num_1().power(k)*binomial(k-n-_num1(),k);
1237 // should really be gamma(n+1)/(gamma(r+1)/gamma(n-r+1) or a suitable limit
1238 throw (std::range_error("numeric::binomial(): don´t know how to evaluate that."));
1241 /** Bernoulli number. The nth Bernoulli number is the coefficient of x^n/n!
1242 * in the expansion of the function x/(e^x-1).
1244 * @return the nth Bernoulli number (a rational number).
1245 * @exception range_error (argument must be integer >= 0) */
1246 numeric bernoulli(const numeric & nn)
1248 if (!nn.is_integer() || nn.is_negative())
1249 throw (std::range_error("numeric::bernoulli(): argument must be integer >= 0"));
1252 if (!nn.compare(_num1()))
1253 return numeric(-1,2);
1256 // Until somebody has the Blues and comes up with a much better idea and
1257 // codes it (preferably in CLN) we make this a remembering function which
1258 // computes its results using the formula
1259 // B(nn) == - 1/(nn+1) * sum_{k=0}^{nn-1}(binomial(nn+1,k)*B(k))
1261 static vector<numeric> results;
1262 static int highest_result = -1;
1263 int n = nn.sub(_num2()).div(_num2()).to_int();
1264 if (n <= highest_result)
1266 if (results.capacity() < (unsigned)(n+1))
1267 results.reserve(n+1);
1269 numeric tmp; // used to store the sum
1270 for (int i=highest_result+1; i<=n; ++i) {
1271 // the first two elements:
1272 tmp = numeric(-2*i-1,2);
1273 // accumulate the remaining elements:
1274 for (int j=0; j<i; ++j)
1275 tmp += binomial(numeric(2*i+3),numeric(j*2+2))*results[j];
1276 // divide by -(nn+1) and store result:
1277 results.push_back(-tmp/numeric(2*i+3));
1283 /** Absolute value. */
1284 numeric abs(const numeric & x)
1286 return ::abs(*x.value); // -> CLN
1289 /** Modulus (in positive representation).
1290 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1291 * sign of a or is zero. This is different from Maple's modp, where the sign
1292 * of b is ignored. It is in agreement with Mathematica's Mod.
1294 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1295 * integer, 0 otherwise. */
1296 numeric mod(const numeric & a, const numeric & b)
1298 if (a.is_integer() && b.is_integer())
1299 return ::mod(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1301 return _num0(); // Throw?
1304 /** Modulus (in symmetric representation).
1305 * Equivalent to Maple's mods.
1307 * @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1308 numeric smod(const numeric & a, const numeric & b)
1310 // FIXME: Should this become a member function?
1311 if (a.is_integer() && b.is_integer()) {
1312 cl_I b2 = The(cl_I)(ceiling1(The(cl_I)(*b.value) / 2)) - 1;
1313 return ::mod(The(cl_I)(*a.value) + b2, The(cl_I)(*b.value)) - b2;
1315 return _num0(); // Throw?
1318 /** Numeric integer remainder.
1319 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1320 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1321 * sign of a or is zero.
1323 * @return remainder of a/b if both are integer, 0 otherwise. */
1324 numeric irem(const numeric & a, const numeric & b)
1326 if (a.is_integer() && b.is_integer())
1327 return ::rem(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1329 return _num0(); // Throw?
1332 /** Numeric integer remainder.
1333 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1334 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1335 * and irem(a,b) has the sign of a or is zero.
1337 * @return remainder of a/b and quotient stored in q if both are integer,
1339 numeric irem(const numeric & a, const numeric & b, numeric & q)
1341 if (a.is_integer() && b.is_integer()) { // -> CLN
1342 cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1343 q = rem_quo.quotient;
1344 return rem_quo.remainder;
1348 return _num0(); // Throw?
1352 /** Numeric integer quotient.
1353 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1355 * @return truncated quotient of a/b if both are integer, 0 otherwise. */
1356 numeric iquo(const numeric & a, const numeric & b)
1358 if (a.is_integer() && b.is_integer())
1359 return truncate1(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1361 return _num0(); // Throw?
1364 /** Numeric integer quotient.
1365 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1366 * r == a - iquo(a,b,r)*b.
1368 * @return truncated quotient of a/b and remainder stored in r if both are
1369 * integer, 0 otherwise. */
1370 numeric iquo(const numeric & a, const numeric & b, numeric & r)
1372 if (a.is_integer() && b.is_integer()) { // -> CLN
1373 cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value));
1374 r = rem_quo.remainder;
1375 return rem_quo.quotient;
1378 return _num0(); // Throw?
1382 /** Numeric square root.
1383 * If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4)
1384 * should return integer 2.
1386 * @param z numeric argument
1387 * @return square root of z. Branch cut along negative real axis, the negative
1388 * real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part
1389 * where imag(z)>0. */
1390 numeric sqrt(const numeric & z)
1392 return ::sqrt(*z.value); // -> CLN
1395 /** Integer numeric square root. */
1396 numeric isqrt(const numeric & x)
1398 if (x.is_integer()) {
1400 ::isqrt(The(cl_I)(*x.value), &root); // -> CLN
1403 return _num0(); // Throw?
1406 /** Greatest Common Divisor.
1408 * @return The GCD of two numbers if both are integer, a numerical 1
1409 * if they are not. */
1410 numeric gcd(const numeric & a, const numeric & b)
1412 if (a.is_integer() && b.is_integer())
1413 return ::gcd(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1418 /** Least Common Multiple.
1420 * @return The LCM of two numbers if both are integer, the product of those
1421 * two numbers if they are not. */
1422 numeric lcm(const numeric & a, const numeric & b)
1424 if (a.is_integer() && b.is_integer())
1425 return ::lcm(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN
1427 return *a.value * *b.value;
1432 return numeric(cl_pi(cl_default_float_format)); // -> CLN
1435 ex EulerGammaEvalf(void)
1437 return numeric(cl_eulerconst(cl_default_float_format)); // -> CLN
1440 ex CatalanEvalf(void)
1442 return numeric(cl_catalanconst(cl_default_float_format)); // -> CLN
1445 // It initializes to 17 digits, because in CLN cl_float_format(17) turns out to
1446 // be 61 (<64) while cl_float_format(18)=65. We want to have a cl_LF instead
1447 // of cl_SF, cl_FF or cl_DF but everything else is basically arbitrary.
1448 _numeric_digits::_numeric_digits()
1453 cl_default_float_format = cl_float_format(17);
1456 _numeric_digits& _numeric_digits::operator=(long prec)
1459 cl_default_float_format = cl_float_format(prec);
1463 _numeric_digits::operator long()
1465 return (long)digits;
1468 void _numeric_digits::print(ostream & os) const
1470 debugmsg("_numeric_digits print", LOGLEVEL_PRINT);
1474 ostream& operator<<(ostream& os, const _numeric_digits & e)
1481 // static member variables
1486 bool _numeric_digits::too_late = false;
1488 /** Accuracy in decimal digits. Only object of this type! Can be set using
1489 * assignment from C++ unsigned ints and evaluated like any built-in type. */
1490 _numeric_digits Digits;
1492 #ifndef NO_GINAC_NAMESPACE
1493 } // namespace GiNaC
1494 #endif // ndef NO_GINAC_NAMESPACE