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
33 #if defined(HAVE_SSTREAM)
35 #elif defined(HAVE_STRSTREAM)
38 #error Need either sstream or strstream
47 // CLN should not pollute the global namespace, hence we include it here
48 // instead of in some header file where it would propagate to other parts.
49 // Also, we only need a subset of CLN, so we don't include the complete cln.h:
51 #include <cln/cl_output.h>
52 #include <cln/cl_integer_io.h>
53 #include <cln/cl_integer_ring.h>
54 #include <cln/cl_rational_io.h>
55 #include <cln/cl_rational_ring.h>
56 #include <cln/cl_lfloat_class.h>
57 #include <cln/cl_lfloat_io.h>
58 #include <cln/cl_real_io.h>
59 #include <cln/cl_real_ring.h>
60 #include <cln/cl_complex_io.h>
61 #include <cln/cl_complex_ring.h>
62 #include <cln/cl_numtheory.h>
63 #else // def HAVE_CLN_CLN_H
64 #include <cl_output.h>
65 #include <cl_integer_io.h>
66 #include <cl_integer_ring.h>
67 #include <cl_rational_io.h>
68 #include <cl_rational_ring.h>
69 #include <cl_lfloat_class.h>
70 #include <cl_lfloat_io.h>
71 #include <cl_real_io.h>
72 #include <cl_real_ring.h>
73 #include <cl_complex_io.h>
74 #include <cl_complex_ring.h>
75 #include <cl_numtheory.h>
76 #endif // def HAVE_CLN_CLN_H
78 #ifndef NO_NAMESPACE_GINAC
80 #endif // ndef NO_NAMESPACE_GINAC
82 GINAC_IMPLEMENT_REGISTERED_CLASS(numeric, basic)
85 // default constructor, destructor, copy constructor assignment
86 // operator and helpers
91 /** default ctor. Numerically it initializes to an integer zero. */
92 numeric::numeric() : basic(TINFO_numeric)
94 debugmsg("numeric default constructor", LOGLEVEL_CONSTRUCT);
98 setflag(status_flags::evaluated |
99 status_flags::expanded |
100 status_flags::hash_calculated);
105 debugmsg("numeric destructor" ,LOGLEVEL_DESTRUCT);
109 numeric::numeric(const numeric & other)
111 debugmsg("numeric copy constructor", LOGLEVEL_CONSTRUCT);
115 const numeric & numeric::operator=(const numeric & other)
117 debugmsg("numeric operator=", LOGLEVEL_ASSIGNMENT);
118 if (this != &other) {
127 void numeric::copy(const numeric & other)
130 value = new ::cl_N(*other.value);
133 void numeric::destroy(bool call_parent)
136 if (call_parent) basic::destroy(call_parent);
140 // other constructors
145 numeric::numeric(int i) : basic(TINFO_numeric)
147 debugmsg("numeric constructor from int",LOGLEVEL_CONSTRUCT);
148 // Not the whole int-range is available if we don't cast to long
149 // first. This is due to the behaviour of the cl_I-ctor, which
150 // emphasizes efficiency:
151 value = new ::cl_I((long) i);
153 setflag(status_flags::evaluated |
154 status_flags::expanded |
155 status_flags::hash_calculated);
159 numeric::numeric(unsigned int i) : basic(TINFO_numeric)
161 debugmsg("numeric constructor from uint",LOGLEVEL_CONSTRUCT);
162 // Not the whole uint-range is available if we don't cast to ulong
163 // first. This is due to the behaviour of the cl_I-ctor, which
164 // emphasizes efficiency:
165 value = new ::cl_I((unsigned long)i);
167 setflag(status_flags::evaluated |
168 status_flags::expanded |
169 status_flags::hash_calculated);
173 numeric::numeric(long i) : basic(TINFO_numeric)
175 debugmsg("numeric constructor from long",LOGLEVEL_CONSTRUCT);
176 value = new ::cl_I(i);
178 setflag(status_flags::evaluated |
179 status_flags::expanded |
180 status_flags::hash_calculated);
184 numeric::numeric(unsigned long i) : basic(TINFO_numeric)
186 debugmsg("numeric constructor from ulong",LOGLEVEL_CONSTRUCT);
187 value = new ::cl_I(i);
189 setflag(status_flags::evaluated |
190 status_flags::expanded |
191 status_flags::hash_calculated);
194 /** Ctor for rational numerics a/b.
196 * @exception overflow_error (division by zero) */
197 numeric::numeric(long numer, long denom) : basic(TINFO_numeric)
199 debugmsg("numeric constructor from long/long",LOGLEVEL_CONSTRUCT);
201 throw std::overflow_error("division by zero");
202 value = new ::cl_I(numer);
203 *value = *value / ::cl_I(denom);
205 setflag(status_flags::evaluated |
206 status_flags::expanded |
207 status_flags::hash_calculated);
211 numeric::numeric(double d) : basic(TINFO_numeric)
213 debugmsg("numeric constructor from double",LOGLEVEL_CONSTRUCT);
214 // We really want to explicitly use the type cl_LF instead of the
215 // more general cl_F, since that would give us a cl_DF only which
216 // will not be promoted to cl_LF if overflow occurs:
218 *value = cl_float(d, cl_default_float_format);
220 setflag(status_flags::evaluated |
221 status_flags::expanded |
222 status_flags::hash_calculated);
225 /** ctor from C-style string. It also accepts complex numbers in GiNaC
226 * notation like "2+5*I". */
227 numeric::numeric(const char *s) : basic(TINFO_numeric)
229 debugmsg("numeric constructor from string",LOGLEVEL_CONSTRUCT);
230 value = new ::cl_N(0);
231 // parse complex numbers (functional but not completely safe, unfortunately
232 // std::string does not understand regexpese):
233 // ss should represent a simple sum like 2+5*I
235 // make it safe by adding explicit sign
236 if (ss.at(0) != '+' && ss.at(0) != '-' && ss.at(0) != '#')
238 std::string::size_type delim;
240 // chop ss into terms from left to right
242 bool imaginary = false;
243 delim = ss.find_first_of(std::string("+-"),1);
244 // Do we have an exponent marker like "31.415E-1"? If so, hop on!
245 if ((delim != std::string::npos) && (ss.at(delim-1) == 'E'))
246 delim = ss.find_first_of(std::string("+-"),delim+1);
247 term = ss.substr(0,delim);
248 if (delim != std::string::npos)
249 ss = ss.substr(delim);
250 // is the term imaginary?
251 if (term.find("I") != std::string::npos) {
253 term = term.replace(term.find("I"),1,"");
255 if (term.find("*") != std::string::npos)
256 term = term.replace(term.find("*"),1,"");
257 // correct for trivial +/-I without explicit factor on I:
258 if (term.size() == 1)
262 const char *cs = term.c_str();
263 // CLN's short types are not useful within the GiNaC framework, hence
264 // we go straight to the construction of a long float. Simply using
265 // cl_N(s) would require us to use add a CLN exponent mark, otherwise
266 // we would not be save from over-/underflows.
269 *value = *value + ::complex(cl_I(0),::cl_LF(cs));
271 *value = *value + ::cl_LF(cs);
274 *value = *value + ::complex(cl_I(0),::cl_R(cs));
276 *value = *value + ::cl_R(cs);
277 } while(delim != std::string::npos);
279 setflag(status_flags::evaluated |
280 status_flags::expanded |
281 status_flags::hash_calculated);
284 /** Ctor from CLN types. This is for the initiated user or internal use
286 numeric::numeric(const cl_N & z) : basic(TINFO_numeric)
288 debugmsg("numeric constructor from cl_N", LOGLEVEL_CONSTRUCT);
289 value = new ::cl_N(z);
291 setflag(status_flags::evaluated |
292 status_flags::expanded |
293 status_flags::hash_calculated);
300 /** Construct object from archive_node. */
301 numeric::numeric(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
303 debugmsg("numeric constructor from archive_node", LOGLEVEL_CONSTRUCT);
306 // Read number as string
308 if (n.find_string("number", str)) {
310 std::istringstream s(str);
312 std::istrstream s(str.c_str(), str.size() + 1);
314 ::cl_idecoded_float re, im;
318 case 'R': // Integer-decoded real number
319 s >> re.sign >> re.mantissa >> re.exponent;
320 *value = re.sign * re.mantissa * ::expt(cl_float(2.0, cl_default_float_format), re.exponent);
322 case 'C': // Integer-decoded complex number
323 s >> re.sign >> re.mantissa >> re.exponent;
324 s >> im.sign >> im.mantissa >> im.exponent;
325 *value = ::complex(re.sign * re.mantissa * ::expt(cl_float(2.0, cl_default_float_format), re.exponent),
326 im.sign * im.mantissa * ::expt(cl_float(2.0, cl_default_float_format), im.exponent));
328 default: // Ordinary number
335 setflag(status_flags::evaluated |
336 status_flags::expanded |
337 status_flags::hash_calculated);
340 /** Unarchive the object. */
341 ex numeric::unarchive(const archive_node &n, const lst &sym_lst)
343 return (new numeric(n, sym_lst))->setflag(status_flags::dynallocated);
346 /** Archive the object. */
347 void numeric::archive(archive_node &n) const
349 inherited::archive(n);
351 // Write number as string
353 std::ostringstream s;
356 std::ostrstream s(buf, 1024);
358 if (this->is_crational())
361 // Non-rational numbers are written in an integer-decoded format
362 // to preserve the precision
363 if (this->is_real()) {
364 cl_idecoded_float re = integer_decode_float(The(::cl_F)(*value));
366 s << re.sign << " " << re.mantissa << " " << re.exponent;
368 cl_idecoded_float re = integer_decode_float(The(::cl_F)(::realpart(*value)));
369 cl_idecoded_float im = integer_decode_float(The(::cl_F)(::imagpart(*value)));
371 s << re.sign << " " << re.mantissa << " " << re.exponent << " ";
372 s << im.sign << " " << im.mantissa << " " << im.exponent;
376 n.add_string("number", s.str());
379 std::string str(buf);
380 n.add_string("number", str);
385 // functions overriding virtual functions from bases classes
390 basic * numeric::duplicate() const
392 debugmsg("numeric duplicate", LOGLEVEL_DUPLICATE);
393 return new numeric(*this);
397 /** Helper function to print a real number in a nicer way than is CLN's
398 * default. Instead of printing 42.0L0 this just prints 42.0 to ostream os
399 * and instead of 3.99168L7 it prints 3.99168E7. This is fine in GiNaC as
400 * long as it only uses cl_LF and no other floating point types.
402 * @see numeric::print() */
403 static void print_real_number(std::ostream & os, const cl_R & num)
405 cl_print_flags ourflags;
406 if (::instanceof(num, ::cl_RA_ring)) {
407 // case 1: integer or rational, nothing special to do:
408 ::print_real(os, ourflags, num);
411 // make CLN believe this number has default_float_format, so it prints
412 // 'E' as exponent marker instead of 'L':
413 ourflags.default_float_format = ::cl_float_format(The(::cl_F)(num));
414 ::print_real(os, ourflags, num);
419 /** This method adds to the output so it blends more consistently together
420 * with the other routines and produces something compatible to ginsh input.
422 * @see print_real_number() */
423 void numeric::print(std::ostream & os, unsigned upper_precedence) const
425 debugmsg("numeric print", LOGLEVEL_PRINT);
426 if (this->is_real()) {
427 // case 1, real: x or -x
428 if ((precedence<=upper_precedence) && (!this->is_nonneg_integer())) {
430 print_real_number(os, The(::cl_R)(*value));
433 print_real_number(os, The(::cl_R)(*value));
436 // case 2, imaginary: y*I or -y*I
437 if (::realpart(*value) == 0) {
438 if ((precedence<=upper_precedence) && (::imagpart(*value) < 0)) {
439 if (::imagpart(*value) == -1) {
443 print_real_number(os, The(::cl_R)(::imagpart(*value)));
447 if (::imagpart(*value) == 1) {
450 if (::imagpart (*value) == -1) {
453 print_real_number(os, The(::cl_R)(::imagpart(*value)));
459 // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I
460 if (precedence <= upper_precedence)
462 print_real_number(os, The(::cl_R)(::realpart(*value)));
463 if (::imagpart(*value) < 0) {
464 if (::imagpart(*value) == -1) {
467 print_real_number(os, The(::cl_R)(::imagpart(*value)));
471 if (::imagpart(*value) == 1) {
475 print_real_number(os, The(::cl_R)(::imagpart(*value)));
479 if (precedence <= upper_precedence)
486 void numeric::printraw(std::ostream & os) const
488 // The method printraw doesn't do much, it simply uses CLN's operator<<()
489 // for output, which is ugly but reliable. e.g: 2+2i
490 debugmsg("numeric printraw", LOGLEVEL_PRINT);
491 os << "numeric(" << *value << ")";
495 void numeric::printtree(std::ostream & os, unsigned indent) const
497 debugmsg("numeric printtree", LOGLEVEL_PRINT);
498 os << std::string(indent,' ') << *value
500 << "hash=" << hashvalue
501 << " (0x" << std::hex << hashvalue << std::dec << ")"
502 << ", flags=" << flags << std::endl;
506 void numeric::printcsrc(std::ostream & os, unsigned type, unsigned upper_precedence) const
508 debugmsg("numeric print csrc", LOGLEVEL_PRINT);
509 ios::fmtflags oldflags = os.flags();
510 os.setf(ios::scientific);
511 if (this->is_rational() && !this->is_integer()) {
512 if (compare(_num0()) > 0) {
514 if (type == csrc_types::ctype_cl_N)
515 os << "cl_F(\"" << numer().evalf() << "\")";
517 os << numer().to_double();
520 if (type == csrc_types::ctype_cl_N)
521 os << "cl_F(\"" << -numer().evalf() << "\")";
523 os << -numer().to_double();
526 if (type == csrc_types::ctype_cl_N)
527 os << "cl_F(\"" << denom().evalf() << "\")";
529 os << denom().to_double();
532 if (type == csrc_types::ctype_cl_N)
533 os << "cl_F(\"" << evalf() << "\")";
541 bool numeric::info(unsigned inf) const
544 case info_flags::numeric:
545 case info_flags::polynomial:
546 case info_flags::rational_function:
548 case info_flags::real:
550 case info_flags::rational:
551 case info_flags::rational_polynomial:
552 return is_rational();
553 case info_flags::crational:
554 case info_flags::crational_polynomial:
555 return is_crational();
556 case info_flags::integer:
557 case info_flags::integer_polynomial:
559 case info_flags::cinteger:
560 case info_flags::cinteger_polynomial:
561 return is_cinteger();
562 case info_flags::positive:
563 return is_positive();
564 case info_flags::negative:
565 return is_negative();
566 case info_flags::nonnegative:
567 return !is_negative();
568 case info_flags::posint:
569 return is_pos_integer();
570 case info_flags::negint:
571 return is_integer() && is_negative();
572 case info_flags::nonnegint:
573 return is_nonneg_integer();
574 case info_flags::even:
576 case info_flags::odd:
578 case info_flags::prime:
580 case info_flags::algebraic:
586 /** Disassemble real part and imaginary part to scan for the occurrence of a
587 * single number. Also handles the imaginary unit. It ignores the sign on
588 * both this and the argument, which may lead to what might appear as funny
589 * results: (2+I).has(-2) -> true. But this is consistent, since we also
590 * would like to have (-2+I).has(2) -> true and we want to think about the
591 * sign as a multiplicative factor. */
592 bool numeric::has(const ex & other) const
594 if (!is_exactly_of_type(*other.bp, numeric))
596 const numeric & o = static_cast<numeric &>(const_cast<basic &>(*other.bp));
597 if (this->is_equal(o) || this->is_equal(-o))
599 if (o.imag().is_zero()) // e.g. scan for 3 in -3*I
600 return (this->real().is_equal(o) || this->imag().is_equal(o) ||
601 this->real().is_equal(-o) || this->imag().is_equal(-o));
603 if (o.is_equal(I)) // e.g scan for I in 42*I
604 return !this->is_real();
605 if (o.real().is_zero()) // e.g. scan for 2*I in 2*I+1
606 return (this->real().has(o*I) || this->imag().has(o*I) ||
607 this->real().has(-o*I) || this->imag().has(-o*I));
613 /** Evaluation of numbers doesn't do anything at all. */
614 ex numeric::eval(int level) const
616 // Warning: if this is ever gonna do something, the ex ctors from all kinds
617 // of numbers should be checking for status_flags::evaluated.
622 /** Cast numeric into a floating-point object. For example exact numeric(1) is
623 * returned as a 1.0000000000000000000000 and so on according to how Digits is
624 * currently set. In case the object already was a floating point number the
625 * precision is trimmed to match the currently set default.
627 * @param level ignored, only needed for overriding basic::evalf.
628 * @return an ex-handle to a numeric. */
629 ex numeric::evalf(int level) const
631 // level can safely be discarded for numeric objects.
632 return numeric(::cl_float(1.0, ::cl_default_float_format) * (*value)); // -> CLN
637 /** Implementation of ex::diff() for a numeric. It always returns 0.
640 ex numeric::derivative(const symbol & s) const
646 int numeric::compare_same_type(const basic & other) const
648 GINAC_ASSERT(is_exactly_of_type(other, numeric));
649 const numeric & o = static_cast<numeric &>(const_cast<basic &>(other));
651 if (*value == *o.value) {
659 bool numeric::is_equal_same_type(const basic & other) const
661 GINAC_ASSERT(is_exactly_of_type(other,numeric));
662 const numeric *o = static_cast<const numeric *>(&other);
664 return this->is_equal(*o);
668 unsigned numeric::calchash(void) const
670 // Use CLN's hashcode. Warning: It depends only on the number's value, not
671 // its type or precision (i.e. a true equivalence relation on numbers). As
672 // a consequence, 3 and 3.0 share the same hashvalue.
673 return (hashvalue = cl_equal_hashcode(*value) | 0x80000000U);
678 // new virtual functions which can be overridden by derived classes
684 // non-virtual functions in this class
689 /** Numerical addition method. Adds argument to *this and returns result as
690 * a new numeric object. */
691 numeric numeric::add(const numeric & other) const
693 return numeric((*value)+(*other.value));
696 /** Numerical subtraction method. Subtracts argument from *this and returns
697 * result as a new numeric object. */
698 numeric numeric::sub(const numeric & other) const
700 return numeric((*value)-(*other.value));
703 /** Numerical multiplication method. Multiplies *this and argument and returns
704 * result as a new numeric object. */
705 numeric numeric::mul(const numeric & other) const
707 static const numeric * _num1p=&_num1();
710 } else if (&other==_num1p) {
713 return numeric((*value)*(*other.value));
716 /** Numerical division method. Divides *this by argument and returns result as
717 * a new numeric object.
719 * @exception overflow_error (division by zero) */
720 numeric numeric::div(const numeric & other) const
722 if (::zerop(*other.value))
723 throw std::overflow_error("numeric::div(): division by zero");
724 return numeric((*value)/(*other.value));
727 numeric numeric::power(const numeric & other) const
729 static const numeric * _num1p = &_num1();
732 if (::zerop(*value)) {
733 if (::zerop(*other.value))
734 throw std::domain_error("numeric::eval(): pow(0,0) is undefined");
735 else if (::zerop(::realpart(*other.value)))
736 throw std::domain_error("numeric::eval(): pow(0,I) is undefined");
737 else if (::minusp(::realpart(*other.value)))
738 throw std::overflow_error("numeric::eval(): division by zero");
742 return numeric(::expt(*value,*other.value));
745 /** Inverse of a number. */
746 numeric numeric::inverse(void) const
749 throw std::overflow_error("numeric::inverse(): division by zero");
750 return numeric(::recip(*value)); // -> CLN
753 const numeric & numeric::add_dyn(const numeric & other) const
755 return static_cast<const numeric &>((new numeric((*value)+(*other.value)))->
756 setflag(status_flags::dynallocated));
759 const numeric & numeric::sub_dyn(const numeric & other) const
761 return static_cast<const numeric &>((new numeric((*value)-(*other.value)))->
762 setflag(status_flags::dynallocated));
765 const numeric & numeric::mul_dyn(const numeric & other) const
767 static const numeric * _num1p=&_num1();
770 } else if (&other==_num1p) {
773 return static_cast<const numeric &>((new numeric((*value)*(*other.value)))->
774 setflag(status_flags::dynallocated));
777 const numeric & numeric::div_dyn(const numeric & other) const
779 if (::zerop(*other.value))
780 throw std::overflow_error("division by zero");
781 return static_cast<const numeric &>((new numeric((*value)/(*other.value)))->
782 setflag(status_flags::dynallocated));
785 const numeric & numeric::power_dyn(const numeric & other) const
787 static const numeric * _num1p=&_num1();
790 if (::zerop(*value)) {
791 if (::zerop(*other.value))
792 throw std::domain_error("numeric::eval(): pow(0,0) is undefined");
793 else if (::zerop(::realpart(*other.value)))
794 throw std::domain_error("numeric::eval(): pow(0,I) is undefined");
795 else if (::minusp(::realpart(*other.value)))
796 throw std::overflow_error("numeric::eval(): division by zero");
800 return static_cast<const numeric &>((new numeric(::expt(*value,*other.value)))->
801 setflag(status_flags::dynallocated));
804 const numeric & numeric::operator=(int i)
806 return operator=(numeric(i));
809 const numeric & numeric::operator=(unsigned int i)
811 return operator=(numeric(i));
814 const numeric & numeric::operator=(long i)
816 return operator=(numeric(i));
819 const numeric & numeric::operator=(unsigned long i)
821 return operator=(numeric(i));
824 const numeric & numeric::operator=(double d)
826 return operator=(numeric(d));
829 const numeric & numeric::operator=(const char * s)
831 return operator=(numeric(s));
834 /** Return the complex half-plane (left or right) in which the number lies.
835 * csgn(x)==0 for x==0, csgn(x)==1 for Re(x)>0 or Re(x)=0 and Im(x)>0,
836 * csgn(x)==-1 for Re(x)<0 or Re(x)=0 and Im(x)<0.
838 * @see numeric::compare(const numeric & other) */
839 int numeric::csgn(void) const
843 if (!::zerop(::realpart(*value))) {
844 if (::plusp(::realpart(*value)))
849 if (::plusp(::imagpart(*value)))
856 /** This method establishes a canonical order on all numbers. For complex
857 * numbers this is not possible in a mathematically consistent way but we need
858 * to establish some order and it ought to be fast. So we simply define it
859 * to be compatible with our method csgn.
861 * @return csgn(*this-other)
862 * @see numeric::csgn(void) */
863 int numeric::compare(const numeric & other) const
865 // Comparing two real numbers?
866 if (this->is_real() && other.is_real())
867 // Yes, just compare them
868 return ::cl_compare(The(::cl_R)(*value), The(::cl_R)(*other.value));
870 // No, first compare real parts
871 cl_signean real_cmp = ::cl_compare(::realpart(*value), ::realpart(*other.value));
875 return ::cl_compare(::imagpart(*value), ::imagpart(*other.value));
879 bool numeric::is_equal(const numeric & other) const
881 return (*value == *other.value);
884 /** True if object is zero. */
885 bool numeric::is_zero(void) const
887 return ::zerop(*value); // -> CLN
890 /** True if object is not complex and greater than zero. */
891 bool numeric::is_positive(void) const
894 return ::plusp(The(::cl_R)(*value)); // -> CLN
898 /** True if object is not complex and less than zero. */
899 bool numeric::is_negative(void) const
902 return ::minusp(The(::cl_R)(*value)); // -> CLN
906 /** True if object is a non-complex integer. */
907 bool numeric::is_integer(void) const
909 return ::instanceof(*value, ::cl_I_ring); // -> CLN
912 /** True if object is an exact integer greater than zero. */
913 bool numeric::is_pos_integer(void) const
915 return (this->is_integer() && ::plusp(The(::cl_I)(*value))); // -> CLN
918 /** True if object is an exact integer greater or equal zero. */
919 bool numeric::is_nonneg_integer(void) const
921 return (this->is_integer() && !::minusp(The(::cl_I)(*value))); // -> CLN
924 /** True if object is an exact even integer. */
925 bool numeric::is_even(void) const
927 return (this->is_integer() && ::evenp(The(::cl_I)(*value))); // -> CLN
930 /** True if object is an exact odd integer. */
931 bool numeric::is_odd(void) const
933 return (this->is_integer() && ::oddp(The(::cl_I)(*value))); // -> CLN
936 /** Probabilistic primality test.
938 * @return true if object is exact integer and prime. */
939 bool numeric::is_prime(void) const
941 return (this->is_integer() && ::isprobprime(The(::cl_I)(*value))); // -> CLN
944 /** True if object is an exact rational number, may even be complex
945 * (denominator may be unity). */
946 bool numeric::is_rational(void) const
948 return ::instanceof(*value, ::cl_RA_ring); // -> CLN
951 /** True if object is a real integer, rational or float (but not complex). */
952 bool numeric::is_real(void) const
954 return ::instanceof(*value, ::cl_R_ring); // -> CLN
957 bool numeric::operator==(const numeric & other) const
959 return (*value == *other.value); // -> CLN
962 bool numeric::operator!=(const numeric & other) const
964 return (*value != *other.value); // -> CLN
967 /** True if object is element of the domain of integers extended by I, i.e. is
968 * of the form a+b*I, where a and b are integers. */
969 bool numeric::is_cinteger(void) const
971 if (::instanceof(*value, ::cl_I_ring))
973 else if (!this->is_real()) { // complex case, handle n+m*I
974 if (::instanceof(::realpart(*value), ::cl_I_ring) &&
975 ::instanceof(::imagpart(*value), ::cl_I_ring))
981 /** True if object is an exact rational number, may even be complex
982 * (denominator may be unity). */
983 bool numeric::is_crational(void) const
985 if (::instanceof(*value, ::cl_RA_ring))
987 else if (!this->is_real()) { // complex case, handle Q(i):
988 if (::instanceof(::realpart(*value), ::cl_RA_ring) &&
989 ::instanceof(::imagpart(*value), ::cl_RA_ring))
995 /** Numerical comparison: less.
997 * @exception invalid_argument (complex inequality) */
998 bool numeric::operator<(const numeric & other) const
1000 if (this->is_real() && other.is_real())
1001 return (The(::cl_R)(*value) < The(::cl_R)(*other.value)); // -> CLN
1002 throw std::invalid_argument("numeric::operator<(): complex inequality");
1005 /** Numerical comparison: less or equal.
1007 * @exception invalid_argument (complex inequality) */
1008 bool numeric::operator<=(const numeric & other) const
1010 if (this->is_real() && other.is_real())
1011 return (The(::cl_R)(*value) <= The(::cl_R)(*other.value)); // -> CLN
1012 throw std::invalid_argument("numeric::operator<=(): complex inequality");
1013 return false; // make compiler shut up
1016 /** Numerical comparison: greater.
1018 * @exception invalid_argument (complex inequality) */
1019 bool numeric::operator>(const numeric & other) const
1021 if (this->is_real() && other.is_real())
1022 return (The(::cl_R)(*value) > The(::cl_R)(*other.value)); // -> CLN
1023 throw std::invalid_argument("numeric::operator>(): complex inequality");
1026 /** Numerical comparison: greater or equal.
1028 * @exception invalid_argument (complex inequality) */
1029 bool numeric::operator>=(const numeric & other) const
1031 if (this->is_real() && other.is_real())
1032 return (The(::cl_R)(*value) >= The(::cl_R)(*other.value)); // -> CLN
1033 throw std::invalid_argument("numeric::operator>=(): complex inequality");
1036 /** Converts numeric types to machine's int. You should check with
1037 * is_integer() if the number is really an integer before calling this method.
1038 * You may also consider checking the range first. */
1039 int numeric::to_int(void) const
1041 GINAC_ASSERT(this->is_integer());
1042 return ::cl_I_to_int(The(::cl_I)(*value)); // -> CLN
1045 /** Converts numeric types to machine's long. You should check with
1046 * is_integer() if the number is really an integer before calling this method.
1047 * You may also consider checking the range first. */
1048 long numeric::to_long(void) const
1050 GINAC_ASSERT(this->is_integer());
1051 return ::cl_I_to_long(The(::cl_I)(*value)); // -> CLN
1054 /** Converts numeric types to machine's double. You should check with is_real()
1055 * if the number is really not complex before calling this method. */
1056 double numeric::to_double(void) const
1058 GINAC_ASSERT(this->is_real());
1059 return ::cl_double_approx(::realpart(*value)); // -> CLN
1062 /** Real part of a number. */
1063 const numeric numeric::real(void) const
1065 return numeric(::realpart(*value)); // -> CLN
1068 /** Imaginary part of a number. */
1069 const numeric numeric::imag(void) const
1071 return numeric(::imagpart(*value)); // -> CLN
1075 /** Numerator. Computes the numerator of rational numbers, rationalized
1076 * numerator of complex if real and imaginary part are both rational numbers
1077 * (i.e numer(4/3+5/6*I) == 8+5*I), the number carrying the sign in all other
1079 const numeric numeric::numer(void) const
1081 if (this->is_integer())
1082 return numeric(*this);
1084 else if (::instanceof(*value, ::cl_RA_ring))
1085 return numeric(::numerator(The(::cl_RA)(*value)));
1087 else if (!this->is_real()) { // complex case, handle Q(i):
1088 cl_R r = ::realpart(*value);
1089 cl_R i = ::imagpart(*value);
1090 if (::instanceof(r, ::cl_I_ring) && ::instanceof(i, ::cl_I_ring))
1091 return numeric(*this);
1092 if (::instanceof(r, ::cl_I_ring) && ::instanceof(i, ::cl_RA_ring))
1093 return numeric(::complex(r*::denominator(The(::cl_RA)(i)), ::numerator(The(::cl_RA)(i))));
1094 if (::instanceof(r, ::cl_RA_ring) && ::instanceof(i, ::cl_I_ring))
1095 return numeric(::complex(::numerator(The(::cl_RA)(r)), i*::denominator(The(::cl_RA)(r))));
1096 if (::instanceof(r, ::cl_RA_ring) && ::instanceof(i, ::cl_RA_ring)) {
1097 cl_I s = ::lcm(::denominator(The(::cl_RA)(r)), ::denominator(The(::cl_RA)(i)));
1098 return numeric(::complex(::numerator(The(::cl_RA)(r))*(exquo(s,::denominator(The(::cl_RA)(r)))),
1099 ::numerator(The(::cl_RA)(i))*(exquo(s,::denominator(The(::cl_RA)(i))))));
1102 // at least one float encountered
1103 return numeric(*this);
1106 /** Denominator. Computes the denominator of rational numbers, common integer
1107 * denominator of complex if real and imaginary part are both rational numbers
1108 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
1109 const numeric numeric::denom(void) const
1111 if (this->is_integer())
1114 if (instanceof(*value, ::cl_RA_ring))
1115 return numeric(::denominator(The(::cl_RA)(*value)));
1117 if (!this->is_real()) { // complex case, handle Q(i):
1118 cl_R r = ::realpart(*value);
1119 cl_R i = ::imagpart(*value);
1120 if (::instanceof(r, ::cl_I_ring) && ::instanceof(i, ::cl_I_ring))
1122 if (::instanceof(r, ::cl_I_ring) && ::instanceof(i, ::cl_RA_ring))
1123 return numeric(::denominator(The(::cl_RA)(i)));
1124 if (::instanceof(r, ::cl_RA_ring) && ::instanceof(i, ::cl_I_ring))
1125 return numeric(::denominator(The(::cl_RA)(r)));
1126 if (::instanceof(r, ::cl_RA_ring) && ::instanceof(i, ::cl_RA_ring))
1127 return numeric(::lcm(::denominator(The(::cl_RA)(r)), ::denominator(The(::cl_RA)(i))));
1129 // at least one float encountered
1133 /** Size in binary notation. For integers, this is the smallest n >= 0 such
1134 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
1135 * 2^(n-1) <= x < 2^n.
1137 * @return number of bits (excluding sign) needed to represent that number
1138 * in two's complement if it is an integer, 0 otherwise. */
1139 int numeric::int_length(void) const
1141 if (this->is_integer())
1142 return ::integer_length(The(::cl_I)(*value)); // -> CLN
1149 // static member variables
1154 unsigned numeric::precedence = 30;
1160 const numeric some_numeric;
1161 const std::type_info & typeid_numeric = typeid(some_numeric);
1162 /** Imaginary unit. This is not a constant but a numeric since we are
1163 * natively handing complex numbers anyways. */
1164 const numeric I = numeric(::complex(cl_I(0),cl_I(1)));
1167 /** Exponential function.
1169 * @return arbitrary precision numerical exp(x). */
1170 const numeric exp(const numeric & x)
1172 return ::exp(*x.value); // -> CLN
1176 /** Natural logarithm.
1178 * @param z complex number
1179 * @return arbitrary precision numerical log(x).
1180 * @exception pole_error("log(): logarithmic pole",0) */
1181 const numeric log(const numeric & z)
1184 throw pole_error("log(): logarithmic pole",0);
1185 return ::log(*z.value); // -> CLN
1189 /** Numeric sine (trigonometric function).
1191 * @return arbitrary precision numerical sin(x). */
1192 const numeric sin(const numeric & x)
1194 return ::sin(*x.value); // -> CLN
1198 /** Numeric cosine (trigonometric function).
1200 * @return arbitrary precision numerical cos(x). */
1201 const numeric cos(const numeric & x)
1203 return ::cos(*x.value); // -> CLN
1207 /** Numeric tangent (trigonometric function).
1209 * @return arbitrary precision numerical tan(x). */
1210 const numeric tan(const numeric & x)
1212 return ::tan(*x.value); // -> CLN
1216 /** Numeric inverse sine (trigonometric function).
1218 * @return arbitrary precision numerical asin(x). */
1219 const numeric asin(const numeric & x)
1221 return ::asin(*x.value); // -> CLN
1225 /** Numeric inverse cosine (trigonometric function).
1227 * @return arbitrary precision numerical acos(x). */
1228 const numeric acos(const numeric & x)
1230 return ::acos(*x.value); // -> CLN
1236 * @param z complex number
1238 * @exception pole_error("atan(): logarithmic pole",0) */
1239 const numeric atan(const numeric & x)
1242 x.real().is_zero() &&
1243 abs(x.imag()).is_equal(_num1()))
1244 throw pole_error("atan(): logarithmic pole",0);
1245 return ::atan(*x.value); // -> CLN
1251 * @param x real number
1252 * @param y real number
1253 * @return atan(y/x) */
1254 const numeric atan(const numeric & y, const numeric & x)
1256 if (x.is_real() && y.is_real())
1257 return ::atan(::realpart(*x.value), ::realpart(*y.value)); // -> CLN
1259 throw std::invalid_argument("atan(): complex argument");
1263 /** Numeric hyperbolic sine (trigonometric function).
1265 * @return arbitrary precision numerical sinh(x). */
1266 const numeric sinh(const numeric & x)
1268 return ::sinh(*x.value); // -> CLN
1272 /** Numeric hyperbolic cosine (trigonometric function).
1274 * @return arbitrary precision numerical cosh(x). */
1275 const numeric cosh(const numeric & x)
1277 return ::cosh(*x.value); // -> CLN
1281 /** Numeric hyperbolic tangent (trigonometric function).
1283 * @return arbitrary precision numerical tanh(x). */
1284 const numeric tanh(const numeric & x)
1286 return ::tanh(*x.value); // -> CLN
1290 /** Numeric inverse hyperbolic sine (trigonometric function).
1292 * @return arbitrary precision numerical asinh(x). */
1293 const numeric asinh(const numeric & x)
1295 return ::asinh(*x.value); // -> CLN
1299 /** Numeric inverse hyperbolic cosine (trigonometric function).
1301 * @return arbitrary precision numerical acosh(x). */
1302 const numeric acosh(const numeric & x)
1304 return ::acosh(*x.value); // -> CLN
1308 /** Numeric inverse hyperbolic tangent (trigonometric function).
1310 * @return arbitrary precision numerical atanh(x). */
1311 const numeric atanh(const numeric & x)
1313 return ::atanh(*x.value); // -> CLN
1317 /*static ::cl_N Li2_series(const ::cl_N & x,
1318 const ::cl_float_format_t & prec)
1320 // Note: argument must be in the unit circle
1321 // This is very inefficient unless we have fast floating point Bernoulli
1322 // numbers implemented!
1323 ::cl_N c1 = -::log(1-x);
1325 // hard-wire the first two Bernoulli numbers
1326 ::cl_N acc = c1 - ::square(c1)/4;
1328 ::cl_F pisq = ::square(::cl_pi(prec)); // pi^2
1329 ::cl_F piac = ::cl_float(1, prec); // accumulator: pi^(2*i)
1335 aug = c2 * (*(bernoulli(numeric(2*i)).clnptr())) / ::factorial(2*i+1);
1336 // aug = c2 * ::cl_I(i%2 ? 1 : -1) / ::cl_I(2*i+1) * ::cl_zeta(2*i, prec) / piac / (::cl_I(1)<<(2*i-1));
1339 } while (acc != acc+aug);
1343 /** Numeric evaluation of Dilogarithm within circle of convergence (unit
1344 * circle) using a power series. */
1345 static ::cl_N Li2_series(const ::cl_N & x,
1346 const ::cl_float_format_t & prec)
1348 // Note: argument must be in the unit circle
1350 ::cl_N num = ::complex(::cl_float(1, prec), 0);
1355 den = den + i; // 1, 4, 9, 16, ...
1359 } while (acc != acc+aug);
1363 /** Folds Li2's argument inside a small rectangle to enhance convergence. */
1364 static ::cl_N Li2_projection(const ::cl_N & x,
1365 const ::cl_float_format_t & prec)
1367 const ::cl_R re = ::realpart(x);
1368 const ::cl_R im = ::imagpart(x);
1369 if (re > ::cl_F(".5"))
1370 // zeta(2) - Li2(1-x) - log(x)*log(1-x)
1372 - Li2_series(1-x, prec)
1373 - ::log(x)*::log(1-x));
1374 if ((re <= 0 && ::abs(im) > ::cl_F(".75")) || (re < ::cl_F("-.5")))
1375 // -log(1-x)^2 / 2 - Li2(x/(x-1))
1376 return(- ::square(::log(1-x))/2
1377 - Li2_series(x/(x-1), prec));
1378 if (re > 0 && ::abs(im) > ::cl_LF(".75"))
1379 // Li2(x^2)/2 - Li2(-x)
1380 return(Li2_projection(::square(x), prec)/2
1381 - Li2_projection(-x, prec));
1382 return Li2_series(x, prec);
1385 /** Numeric evaluation of Dilogarithm. The domain is the entire complex plane,
1386 * the branch cut lies along the positive real axis, starting at 1 and
1387 * continuous with quadrant IV.
1389 * @return arbitrary precision numerical Li2(x). */
1390 const numeric Li2(const numeric & x)
1392 if (::zerop(*x.value))
1395 // what is the desired float format?
1396 // first guess: default format
1397 ::cl_float_format_t prec = ::cl_default_float_format;
1398 // second guess: the argument's format
1399 if (!::instanceof(::realpart(*x.value),cl_RA_ring))
1400 prec = ::cl_float_format(The(::cl_F)(::realpart(*x.value)));
1401 else if (!::instanceof(::imagpart(*x.value),cl_RA_ring))
1402 prec = ::cl_float_format(The(::cl_F)(::imagpart(*x.value)));
1404 if (*x.value==1) // may cause trouble with log(1-x)
1405 return ::cl_zeta(2, prec);
1407 if (::abs(*x.value) > 1)
1408 // -log(-x)^2 / 2 - zeta(2) - Li2(1/x)
1409 return(- ::square(::log(-*x.value))/2
1410 - ::cl_zeta(2, prec)
1411 - Li2_projection(::recip(*x.value), prec));
1413 return Li2_projection(*x.value, prec);
1417 /** Numeric evaluation of Riemann's Zeta function. Currently works only for
1418 * integer arguments. */
1419 const numeric zeta(const numeric & x)
1421 // A dirty hack to allow for things like zeta(3.0), since CLN currently
1422 // only knows about integer arguments and zeta(3).evalf() automatically
1423 // cascades down to zeta(3.0).evalf(). The trick is to rely on 3.0-3
1424 // being an exact zero for CLN, which can be tested and then we can just
1425 // pass the number casted to an int:
1427 int aux = (int)(::cl_double_approx(::realpart(*x.value)));
1428 if (::zerop(*x.value-aux))
1429 return ::cl_zeta(aux); // -> CLN
1431 std::clog << "zeta(" << x
1432 << "): Does anybody know good way to calculate this numerically?"
1438 /** The Gamma function.
1439 * This is only a stub! */
1440 const numeric lgamma(const numeric & x)
1442 std::clog << "lgamma(" << x
1443 << "): Does anybody know good way to calculate this numerically?"
1447 const numeric tgamma(const numeric & x)
1449 std::clog << "tgamma(" << x
1450 << "): Does anybody know good way to calculate this numerically?"
1456 /** The psi function (aka polygamma function).
1457 * This is only a stub! */
1458 const numeric psi(const numeric & x)
1460 std::clog << "psi(" << x
1461 << "): Does anybody know good way to calculate this numerically?"
1467 /** The psi functions (aka polygamma functions).
1468 * This is only a stub! */
1469 const numeric psi(const numeric & n, const numeric & x)
1471 std::clog << "psi(" << n << "," << x
1472 << "): Does anybody know good way to calculate this numerically?"
1478 /** Factorial combinatorial function.
1480 * @param n integer argument >= 0
1481 * @exception range_error (argument must be integer >= 0) */
1482 const numeric factorial(const numeric & n)
1484 if (!n.is_nonneg_integer())
1485 throw std::range_error("numeric::factorial(): argument must be integer >= 0");
1486 return numeric(::factorial(n.to_int())); // -> CLN
1490 /** The double factorial combinatorial function. (Scarcely used, but still
1491 * useful in cases, like for exact results of tgamma(n+1/2) for instance.)
1493 * @param n integer argument >= -1
1494 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == (-1)!! == 1
1495 * @exception range_error (argument must be integer >= -1) */
1496 const numeric doublefactorial(const numeric & n)
1498 if (n == numeric(-1)) {
1501 if (!n.is_nonneg_integer()) {
1502 throw std::range_error("numeric::doublefactorial(): argument must be integer >= -1");
1504 return numeric(::doublefactorial(n.to_int())); // -> CLN
1508 /** The Binomial coefficients. It computes the binomial coefficients. For
1509 * integer n and k and positive n this is the number of ways of choosing k
1510 * objects from n distinct objects. If n is negative, the formula
1511 * binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */
1512 const numeric binomial(const numeric & n, const numeric & k)
1514 if (n.is_integer() && k.is_integer()) {
1515 if (n.is_nonneg_integer()) {
1516 if (k.compare(n)!=1 && k.compare(_num0())!=-1)
1517 return numeric(::binomial(n.to_int(),k.to_int())); // -> CLN
1521 return _num_1().power(k)*binomial(k-n-_num1(),k);
1525 // should really be gamma(n+1)/gamma(r+1)/gamma(n-r+1) or a suitable limit
1526 throw std::range_error("numeric::binomial(): don´t know how to evaluate that.");
1530 /** Bernoulli number. The nth Bernoulli number is the coefficient of x^n/n!
1531 * in the expansion of the function x/(e^x-1).
1533 * @return the nth Bernoulli number (a rational number).
1534 * @exception range_error (argument must be integer >= 0) */
1535 const numeric bernoulli(const numeric & nn)
1537 if (!nn.is_integer() || nn.is_negative())
1538 throw std::range_error("numeric::bernoulli(): argument must be integer >= 0");
1542 // The Bernoulli numbers are rational numbers that may be computed using
1545 // B_n = - 1/(n+1) * sum_{k=0}^{n-1}(binomial(n+1,k)*B_k)
1547 // with B(0) = 1. Since the n'th Bernoulli number depends on all the
1548 // previous ones, the computation is necessarily very expensive. There are
1549 // several other ways of computing them, a particularly good one being
1553 // for (unsigned i=0; i<n; i++) {
1554 // c = exquo(c*(i-n),(i+2));
1555 // Bern = Bern + c*s/(i+2);
1556 // s = s + expt_pos(cl_I(i+2),n);
1560 // But if somebody works with the n'th Bernoulli number she is likely to
1561 // also need all previous Bernoulli numbers. So we need a complete remember
1562 // table and above divide and conquer algorithm is not suited to build one
1563 // up. The code below is adapted from Pari's function bernvec().
1565 // (There is an interesting relation with the tangent polynomials described
1566 // in `Concrete Mathematics', which leads to a program twice as fast as our
1567 // implementation below, but it requires storing one such polynomial in
1568 // addition to the remember table. This doubles the memory footprint so
1569 // we don't use it.)
1571 // the special cases not covered by the algorithm below
1572 if (nn.is_equal(_num1()))
1577 // store nonvanishing Bernoulli numbers here
1578 static std::vector< ::cl_RA > results;
1579 static int highest_result = 0;
1580 // algorithm not applicable to B(0), so just store it
1581 if (results.size()==0)
1582 results.push_back(::cl_RA(1));
1584 int n = nn.to_long();
1585 for (int i=highest_result; i<n/2; ++i) {
1591 for (int j=i; j>0; --j) {
1592 B = ::cl_I(n*m) * (B+results[j]) / (d1*d2);
1598 B = (1 - ((B+1)/(2*i+3))) / (::cl_I(1)<<(2*i+2));
1599 results.push_back(B);
1602 return results[n/2];
1606 /** Fibonacci number. The nth Fibonacci number F(n) is defined by the
1607 * recurrence formula F(n)==F(n-1)+F(n-2) with F(0)==0 and F(1)==1.
1609 * @param n an integer
1610 * @return the nth Fibonacci number F(n) (an integer number)
1611 * @exception range_error (argument must be an integer) */
1612 const numeric fibonacci(const numeric & n)
1614 if (!n.is_integer())
1615 throw std::range_error("numeric::fibonacci(): argument must be integer");
1618 // This is based on an implementation that can be found in CLN's example
1619 // directory. There, it is done recursively, which may be more elegant
1620 // than our non-recursive implementation that has to resort to some bit-
1621 // fiddling. This is, however, a matter of taste.
1622 // The following addition formula holds:
1624 // F(n+m) = F(m-1)*F(n) + F(m)*F(n+1) for m >= 1, n >= 0.
1626 // (Proof: For fixed m, the LHS and the RHS satisfy the same recurrence
1627 // w.r.t. n, and the initial values (n=0, n=1) agree. Hence all values
1629 // Replace m by m+1:
1630 // F(n+m+1) = F(m)*F(n) + F(m+1)*F(n+1) for m >= 0, n >= 0
1631 // Now put in m = n, to get
1632 // F(2n) = (F(n+1)-F(n))*F(n) + F(n)*F(n+1) = F(n)*(2*F(n+1) - F(n))
1633 // F(2n+1) = F(n)^2 + F(n+1)^2
1635 // F(2n+2) = F(n+1)*(2*F(n) + F(n+1))
1638 if (n.is_negative())
1640 return -fibonacci(-n);
1642 return fibonacci(-n);
1646 ::cl_I m = The(::cl_I)(*n.value) >> 1L; // floor(n/2);
1647 for (uintL bit=::integer_length(m); bit>0; --bit) {
1648 // Since a squaring is cheaper than a multiplication, better use
1649 // three squarings instead of one multiplication and two squarings.
1650 ::cl_I u2 = ::square(u);
1651 ::cl_I v2 = ::square(v);
1652 if (::logbitp(bit-1, m)) {
1653 v = ::square(u + v) - u2;
1656 u = v2 - ::square(v - u);
1661 // Here we don't use the squaring formula because one multiplication
1662 // is cheaper than two squarings.
1663 return u * ((v << 1) - u);
1665 return ::square(u) + ::square(v);
1669 /** Absolute value. */
1670 numeric abs(const numeric & x)
1672 return ::abs(*x.value); // -> CLN
1676 /** Modulus (in positive representation).
1677 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1678 * sign of a or is zero. This is different from Maple's modp, where the sign
1679 * of b is ignored. It is in agreement with Mathematica's Mod.
1681 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1682 * integer, 0 otherwise. */
1683 numeric mod(const numeric & a, const numeric & b)
1685 if (a.is_integer() && b.is_integer())
1686 return ::mod(The(::cl_I)(*a.value), The(::cl_I)(*b.value)); // -> CLN
1688 return _num0(); // Throw?
1692 /** Modulus (in symmetric representation).
1693 * Equivalent to Maple's mods.
1695 * @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1696 numeric smod(const numeric & a, const numeric & b)
1698 if (a.is_integer() && b.is_integer()) {
1699 cl_I b2 = The(::cl_I)(ceiling1(The(::cl_I)(*b.value) >> 1)) - 1;
1700 return ::mod(The(::cl_I)(*a.value) + b2, The(::cl_I)(*b.value)) - b2;
1702 return _num0(); // Throw?
1706 /** Numeric integer remainder.
1707 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1708 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1709 * sign of a or is zero.
1711 * @return remainder of a/b if both are integer, 0 otherwise. */
1712 numeric irem(const numeric & a, const numeric & b)
1714 if (a.is_integer() && b.is_integer())
1715 return ::rem(The(::cl_I)(*a.value), The(::cl_I)(*b.value)); // -> CLN
1717 return _num0(); // Throw?
1721 /** Numeric integer remainder.
1722 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1723 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1724 * and irem(a,b) has the sign of a or is zero.
1726 * @return remainder of a/b and quotient stored in q if both are integer,
1728 numeric irem(const numeric & a, const numeric & b, numeric & q)
1730 if (a.is_integer() && b.is_integer()) { // -> CLN
1731 cl_I_div_t rem_quo = truncate2(The(::cl_I)(*a.value), The(::cl_I)(*b.value));
1732 q = rem_quo.quotient;
1733 return rem_quo.remainder;
1736 return _num0(); // Throw?
1741 /** Numeric integer quotient.
1742 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1744 * @return truncated quotient of a/b if both are integer, 0 otherwise. */
1745 numeric iquo(const numeric & a, const numeric & b)
1747 if (a.is_integer() && b.is_integer())
1748 return truncate1(The(::cl_I)(*a.value), The(::cl_I)(*b.value)); // -> CLN
1750 return _num0(); // Throw?
1754 /** Numeric integer quotient.
1755 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1756 * r == a - iquo(a,b,r)*b.
1758 * @return truncated quotient of a/b and remainder stored in r if both are
1759 * integer, 0 otherwise. */
1760 numeric iquo(const numeric & a, const numeric & b, numeric & r)
1762 if (a.is_integer() && b.is_integer()) { // -> CLN
1763 cl_I_div_t rem_quo = truncate2(The(::cl_I)(*a.value), The(::cl_I)(*b.value));
1764 r = rem_quo.remainder;
1765 return rem_quo.quotient;
1768 return _num0(); // Throw?
1773 /** Numeric square root.
1774 * If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4)
1775 * should return integer 2.
1777 * @param z numeric argument
1778 * @return square root of z. Branch cut along negative real axis, the negative
1779 * real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part
1780 * where imag(z)>0. */
1781 numeric sqrt(const numeric & z)
1783 return ::sqrt(*z.value); // -> CLN
1787 /** Integer numeric square root. */
1788 numeric isqrt(const numeric & x)
1790 if (x.is_integer()) {
1792 ::isqrt(The(::cl_I)(*x.value), &root); // -> CLN
1795 return _num0(); // Throw?
1799 /** Greatest Common Divisor.
1801 * @return The GCD of two numbers if both are integer, a numerical 1
1802 * if they are not. */
1803 numeric gcd(const numeric & a, const numeric & b)
1805 if (a.is_integer() && b.is_integer())
1806 return ::gcd(The(::cl_I)(*a.value), The(::cl_I)(*b.value)); // -> CLN
1812 /** Least Common Multiple.
1814 * @return The LCM of two numbers if both are integer, the product of those
1815 * two numbers if they are not. */
1816 numeric lcm(const numeric & a, const numeric & b)
1818 if (a.is_integer() && b.is_integer())
1819 return ::lcm(The(::cl_I)(*a.value), The(::cl_I)(*b.value)); // -> CLN
1821 return *a.value * *b.value;
1825 /** Floating point evaluation of Archimedes' constant Pi. */
1828 return numeric(::cl_pi(cl_default_float_format)); // -> CLN
1832 /** Floating point evaluation of Euler's constant gamma. */
1835 return numeric(::cl_eulerconst(cl_default_float_format)); // -> CLN
1839 /** Floating point evaluation of Catalan's constant. */
1840 ex CatalanEvalf(void)
1842 return numeric(::cl_catalanconst(cl_default_float_format)); // -> CLN
1846 // It initializes to 17 digits, because in CLN cl_float_format(17) turns out to
1847 // be 61 (<64) while cl_float_format(18)=65. We want to have a cl_LF instead
1848 // of cl_SF, cl_FF or cl_DF but everything else is basically arbitrary.
1849 _numeric_digits::_numeric_digits()
1854 cl_default_float_format = ::cl_float_format(17);
1858 _numeric_digits& _numeric_digits::operator=(long prec)
1861 cl_default_float_format = ::cl_float_format(prec);
1866 _numeric_digits::operator long()
1868 return (long)digits;
1872 void _numeric_digits::print(std::ostream & os) const
1874 debugmsg("_numeric_digits print", LOGLEVEL_PRINT);
1879 std::ostream& operator<<(std::ostream& os, const _numeric_digits & e)
1886 // static member variables
1891 bool _numeric_digits::too_late = false;
1894 /** Accuracy in decimal digits. Only object of this type! Can be set using
1895 * assignment from C++ unsigned ints and evaluated like any built-in type. */
1896 _numeric_digits Digits;
1898 #ifndef NO_NAMESPACE_GINAC
1899 } // namespace GiNaC
1900 #endif // ndef NO_NAMESPACE_GINAC