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-2001 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
41 // CLN should pollute the global namespace as little as possible. Hence, we
42 // include most of it here and include only the part needed for properly
43 // declaring cln::cl_number in numeric.h. This can only be safely done in
44 // namespaced versions of CLN, i.e. version > 1.1.0. Also, we only need a
45 // subset of CLN, so we don't include the complete <cln/cln.h> but only the
47 #include <cln/output.h>
48 #include <cln/integer_io.h>
49 #include <cln/integer_ring.h>
50 #include <cln/rational_io.h>
51 #include <cln/rational_ring.h>
52 #include <cln/lfloat_class.h>
53 #include <cln/lfloat_io.h>
54 #include <cln/real_io.h>
55 #include <cln/real_ring.h>
56 #include <cln/complex_io.h>
57 #include <cln/complex_ring.h>
58 #include <cln/numtheory.h>
62 GINAC_IMPLEMENT_REGISTERED_CLASS(numeric, basic)
65 // default ctor, dtor, copy ctor, assignment operator and helpers
68 /** default ctor. Numerically it initializes to an integer zero. */
69 numeric::numeric() : basic(TINFO_numeric)
72 setflag(status_flags::evaluated | status_flags::expanded);
75 void numeric::copy(const numeric &other)
77 inherited::copy(other);
81 DEFAULT_DESTROY(numeric)
89 numeric::numeric(int i) : basic(TINFO_numeric)
91 // Not the whole int-range is available if we don't cast to long
92 // first. This is due to the behaviour of the cl_I-ctor, which
93 // emphasizes efficiency. However, if the integer is small enough,
94 // i.e. satisfies cl_immediate_p(), we save space and dereferences by
95 // using an immediate type:
96 if (cln::cl_immediate_p(i))
99 value = cln::cl_I((long) i);
100 setflag(status_flags::evaluated | status_flags::expanded);
104 numeric::numeric(unsigned int i) : basic(TINFO_numeric)
106 // Not the whole uint-range is available if we don't cast to ulong
107 // first. This is due to the behaviour of the cl_I-ctor, which
108 // emphasizes efficiency. However, if the integer is small enough,
109 // i.e. satisfies cl_immediate_p(), we save space and dereferences by
110 // using an immediate type:
111 if (cln::cl_immediate_p(i))
112 value = cln::cl_I(i);
114 value = cln::cl_I((unsigned long) i);
115 setflag(status_flags::evaluated | status_flags::expanded);
119 numeric::numeric(long i) : basic(TINFO_numeric)
121 value = cln::cl_I(i);
122 setflag(status_flags::evaluated | status_flags::expanded);
126 numeric::numeric(unsigned long i) : basic(TINFO_numeric)
128 value = cln::cl_I(i);
129 setflag(status_flags::evaluated | status_flags::expanded);
132 /** Ctor for rational numerics a/b.
134 * @exception overflow_error (division by zero) */
135 numeric::numeric(long numer, long denom) : basic(TINFO_numeric)
138 throw std::overflow_error("division by zero");
139 value = cln::cl_I(numer) / cln::cl_I(denom);
140 setflag(status_flags::evaluated | status_flags::expanded);
144 numeric::numeric(double d) : basic(TINFO_numeric)
146 // We really want to explicitly use the type cl_LF instead of the
147 // more general cl_F, since that would give us a cl_DF only which
148 // will not be promoted to cl_LF if overflow occurs:
149 value = cln::cl_float(d, cln::default_float_format);
150 setflag(status_flags::evaluated | status_flags::expanded);
154 /** ctor from C-style string. It also accepts complex numbers in GiNaC
155 * notation like "2+5*I". */
156 numeric::numeric(const char *s) : basic(TINFO_numeric)
158 cln::cl_N ctorval = 0;
159 // parse complex numbers (functional but not completely safe, unfortunately
160 // std::string does not understand regexpese):
161 // ss should represent a simple sum like 2+5*I
163 std::string::size_type delim;
165 // make this implementation safe by adding explicit sign
166 if (ss.at(0) != '+' && ss.at(0) != '-' && ss.at(0) != '#')
169 // We use 'E' as exponent marker in the output, but some people insist on
170 // writing 'e' at input, so let's substitute them right at the beginning:
171 while ((delim = ss.find("e"))!=std::string::npos)
172 ss.replace(delim,1,"E");
176 // chop ss into terms from left to right
178 bool imaginary = false;
179 delim = ss.find_first_of(std::string("+-"),1);
180 // Do we have an exponent marker like "31.415E-1"? If so, hop on!
181 if (delim!=std::string::npos && ss.at(delim-1)=='E')
182 delim = ss.find_first_of(std::string("+-"),delim+1);
183 term = ss.substr(0,delim);
184 if (delim!=std::string::npos)
185 ss = ss.substr(delim);
186 // is the term imaginary?
187 if (term.find("I")!=std::string::npos) {
189 term.erase(term.find("I"),1);
191 if (term.find("*")!=std::string::npos)
192 term.erase(term.find("*"),1);
193 // correct for trivial +/-I without explicit factor on I:
198 if (term.find('.')!=std::string::npos || term.find('E')!=std::string::npos) {
199 // CLN's short type cl_SF is not very useful within the GiNaC
200 // framework where we are mainly interested in the arbitrary
201 // precision type cl_LF. Hence we go straight to the construction
202 // of generic floats. In order to create them we have to convert
203 // our own floating point notation used for output and construction
204 // from char * to CLN's generic notation:
205 // 3.14 --> 3.14e0_<Digits>
206 // 31.4E-1 --> 31.4e-1_<Digits>
208 // No exponent marker? Let's add a trivial one.
209 if (term.find("E")==std::string::npos)
212 term = term.replace(term.find("E"),1,"e");
213 // append _<Digits> to term
214 term += "_" + ToString((unsigned)Digits);
215 // construct float using cln::cl_F(const char *) ctor.
217 ctorval = ctorval + cln::complex(cln::cl_I(0),cln::cl_F(term.c_str()));
219 ctorval = ctorval + cln::cl_F(term.c_str());
221 // this is not a floating point number...
223 ctorval = ctorval + cln::complex(cln::cl_I(0),cln::cl_R(term.c_str()));
225 ctorval = ctorval + cln::cl_R(term.c_str());
227 } while (delim != std::string::npos);
229 setflag(status_flags::evaluated | status_flags::expanded);
233 /** Ctor from CLN types. This is for the initiated user or internal use
235 numeric::numeric(const cln::cl_N &z) : basic(TINFO_numeric)
238 setflag(status_flags::evaluated | status_flags::expanded);
245 numeric::numeric(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
247 cln::cl_N ctorval = 0;
249 // Read number as string
251 if (n.find_string("number", str)) {
252 std::istringstream s(str);
253 cln::cl_idecoded_float re, im;
257 case 'R': // Integer-decoded real number
258 s >> re.sign >> re.mantissa >> re.exponent;
259 ctorval = re.sign * re.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), re.exponent);
261 case 'C': // Integer-decoded complex number
262 s >> re.sign >> re.mantissa >> re.exponent;
263 s >> im.sign >> im.mantissa >> im.exponent;
264 ctorval = cln::complex(re.sign * re.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), re.exponent),
265 im.sign * im.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), im.exponent));
267 default: // Ordinary number
274 setflag(status_flags::evaluated | status_flags::expanded);
277 void numeric::archive(archive_node &n) const
279 inherited::archive(n);
281 // Write number as string
282 std::ostringstream s;
283 if (this->is_crational())
284 s << cln::the<cln::cl_N>(value);
286 // Non-rational numbers are written in an integer-decoded format
287 // to preserve the precision
288 if (this->is_real()) {
289 cln::cl_idecoded_float re = cln::integer_decode_float(cln::the<cln::cl_F>(value));
291 s << re.sign << " " << re.mantissa << " " << re.exponent;
293 cln::cl_idecoded_float re = cln::integer_decode_float(cln::the<cln::cl_F>(cln::realpart(cln::the<cln::cl_N>(value))));
294 cln::cl_idecoded_float im = cln::integer_decode_float(cln::the<cln::cl_F>(cln::imagpart(cln::the<cln::cl_N>(value))));
296 s << re.sign << " " << re.mantissa << " " << re.exponent << " ";
297 s << im.sign << " " << im.mantissa << " " << im.exponent;
300 n.add_string("number", s.str());
303 DEFAULT_UNARCHIVE(numeric)
306 // functions overriding virtual functions from base classes
309 /** Helper function to print a real number in a nicer way than is CLN's
310 * default. Instead of printing 42.0L0 this just prints 42.0 to ostream os
311 * and instead of 3.99168L7 it prints 3.99168E7. This is fine in GiNaC as
312 * long as it only uses cl_LF and no other floating point types that we might
313 * want to visibly distinguish from cl_LF.
315 * @see numeric::print() */
316 static void print_real_number(const print_context & c, const cln::cl_R &x)
318 cln::cl_print_flags ourflags;
319 if (cln::instanceof(x, cln::cl_RA_ring)) {
320 // case 1: integer or rational
321 if (cln::instanceof(x, cln::cl_I_ring) ||
322 !is_a<print_latex>(c)) {
323 cln::print_real(c.s, ourflags, x);
324 } else { // rational output in LaTeX context
326 cln::print_real(c.s, ourflags, cln::numerator(cln::the<cln::cl_RA>(x)));
328 cln::print_real(c.s, ourflags, cln::denominator(cln::the<cln::cl_RA>(x)));
333 // make CLN believe this number has default_float_format, so it prints
334 // 'E' as exponent marker instead of 'L':
335 ourflags.default_float_format = cln::float_format(cln::the<cln::cl_F>(x));
336 cln::print_real(c.s, ourflags, x);
340 /** This method adds to the output so it blends more consistently together
341 * with the other routines and produces something compatible to ginsh input.
343 * @see print_real_number() */
344 void numeric::print(const print_context & c, unsigned level) const
346 if (is_a<print_tree>(c)) {
348 c.s << std::string(level, ' ') << cln::the<cln::cl_N>(value)
349 << " (" << class_name() << ")"
350 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
353 } else if (is_a<print_csrc>(c)) {
355 std::ios::fmtflags oldflags = c.s.flags();
356 c.s.setf(std::ios::scientific);
357 if (this->is_rational() && !this->is_integer()) {
358 if (compare(_num0) > 0) {
360 if (is_a<print_csrc_cl_N>(c))
361 c.s << "cln::cl_F(\"" << numer().evalf() << "\")";
363 c.s << numer().to_double();
366 if (is_a<print_csrc_cl_N>(c))
367 c.s << "cln::cl_F(\"" << -numer().evalf() << "\")";
369 c.s << -numer().to_double();
372 if (is_a<print_csrc_cl_N>(c))
373 c.s << "cln::cl_F(\"" << denom().evalf() << "\")";
375 c.s << denom().to_double();
378 if (is_a<print_csrc_cl_N>(c))
379 c.s << "cln::cl_F(\"" << evalf() << "\")";
386 const std::string par_open = is_a<print_latex>(c) ? "{(" : "(";
387 const std::string par_close = is_a<print_latex>(c) ? ")}" : ")";
388 const std::string imag_sym = is_a<print_latex>(c) ? "i" : "I";
389 const std::string mul_sym = is_a<print_latex>(c) ? " " : "*";
390 const cln::cl_R r = cln::realpart(cln::the<cln::cl_N>(value));
391 const cln::cl_R i = cln::imagpart(cln::the<cln::cl_N>(value));
392 if (is_a<print_python_repr>(c))
393 c.s << class_name() << "('";
395 // case 1, real: x or -x
396 if ((precedence() <= level) && (!this->is_nonneg_integer())) {
398 print_real_number(c, r);
401 print_real_number(c, r);
405 // case 2, imaginary: y*I or -y*I
406 if ((precedence() <= level) && (i < 0)) {
408 c.s << par_open+imag_sym+par_close;
411 print_real_number(c, i);
412 c.s << mul_sym+imag_sym+par_close;
419 c.s << "-" << imag_sym;
421 print_real_number(c, i);
422 c.s << mul_sym+imag_sym;
427 // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I
428 if (precedence() <= level)
430 print_real_number(c, r);
435 print_real_number(c, i);
436 c.s << mul_sym+imag_sym;
443 print_real_number(c, i);
444 c.s << mul_sym+imag_sym;
447 if (precedence() <= level)
451 if (is_a<print_python_repr>(c))
456 bool numeric::info(unsigned inf) const
459 case info_flags::numeric:
460 case info_flags::polynomial:
461 case info_flags::rational_function:
463 case info_flags::real:
465 case info_flags::rational:
466 case info_flags::rational_polynomial:
467 return is_rational();
468 case info_flags::crational:
469 case info_flags::crational_polynomial:
470 return is_crational();
471 case info_flags::integer:
472 case info_flags::integer_polynomial:
474 case info_flags::cinteger:
475 case info_flags::cinteger_polynomial:
476 return is_cinteger();
477 case info_flags::positive:
478 return is_positive();
479 case info_flags::negative:
480 return is_negative();
481 case info_flags::nonnegative:
482 return !is_negative();
483 case info_flags::posint:
484 return is_pos_integer();
485 case info_flags::negint:
486 return is_integer() && is_negative();
487 case info_flags::nonnegint:
488 return is_nonneg_integer();
489 case info_flags::even:
491 case info_flags::odd:
493 case info_flags::prime:
495 case info_flags::algebraic:
501 /** Disassemble real part and imaginary part to scan for the occurrence of a
502 * single number. Also handles the imaginary unit. It ignores the sign on
503 * both this and the argument, which may lead to what might appear as funny
504 * results: (2+I).has(-2) -> true. But this is consistent, since we also
505 * would like to have (-2+I).has(2) -> true and we want to think about the
506 * sign as a multiplicative factor. */
507 bool numeric::has(const ex &other) const
509 if (!is_ex_exactly_of_type(other, numeric))
511 const numeric &o = ex_to<numeric>(other);
512 if (this->is_equal(o) || this->is_equal(-o))
514 if (o.imag().is_zero()) // e.g. scan for 3 in -3*I
515 return (this->real().is_equal(o) || this->imag().is_equal(o) ||
516 this->real().is_equal(-o) || this->imag().is_equal(-o));
518 if (o.is_equal(I)) // e.g scan for I in 42*I
519 return !this->is_real();
520 if (o.real().is_zero()) // e.g. scan for 2*I in 2*I+1
521 return (this->real().has(o*I) || this->imag().has(o*I) ||
522 this->real().has(-o*I) || this->imag().has(-o*I));
528 /** Evaluation of numbers doesn't do anything at all. */
529 ex numeric::eval(int level) const
531 // Warning: if this is ever gonna do something, the ex ctors from all kinds
532 // of numbers should be checking for status_flags::evaluated.
537 /** Cast numeric into a floating-point object. For example exact numeric(1) is
538 * returned as a 1.0000000000000000000000 and so on according to how Digits is
539 * currently set. In case the object already was a floating point number the
540 * precision is trimmed to match the currently set default.
542 * @param level ignored, only needed for overriding basic::evalf.
543 * @return an ex-handle to a numeric. */
544 ex numeric::evalf(int level) const
546 // level can safely be discarded for numeric objects.
547 return numeric(cln::cl_float(1.0, cln::default_float_format) *
548 (cln::the<cln::cl_N>(value)));
553 int numeric::compare_same_type(const basic &other) const
555 GINAC_ASSERT(is_exactly_a<numeric>(other));
556 const numeric &o = static_cast<const numeric &>(other);
558 return this->compare(o);
562 bool numeric::is_equal_same_type(const basic &other) const
564 GINAC_ASSERT(is_exactly_a<numeric>(other));
565 const numeric &o = static_cast<const numeric &>(other);
567 return this->is_equal(o);
571 unsigned numeric::calchash(void) const
573 // Use CLN's hashcode. Warning: It depends only on the number's value, not
574 // its type or precision (i.e. a true equivalence relation on numbers). As
575 // a consequence, 3 and 3.0 share the same hashvalue.
576 setflag(status_flags::hash_calculated);
577 return (hashvalue = cln::equal_hashcode(cln::the<cln::cl_N>(value)) | 0x80000000U);
582 // new virtual functions which can be overridden by derived classes
588 // non-virtual functions in this class
593 /** Numerical addition method. Adds argument to *this and returns result as
594 * a numeric object. */
595 const numeric numeric::add(const numeric &other) const
597 // Efficiency shortcut: trap the neutral element by pointer.
600 else if (&other==_num0_p)
603 return numeric(cln::the<cln::cl_N>(value)+cln::the<cln::cl_N>(other.value));
607 /** Numerical subtraction method. Subtracts argument from *this and returns
608 * result as a numeric object. */
609 const numeric numeric::sub(const numeric &other) const
611 return numeric(cln::the<cln::cl_N>(value)-cln::the<cln::cl_N>(other.value));
615 /** Numerical multiplication method. Multiplies *this and argument and returns
616 * result as a numeric object. */
617 const numeric numeric::mul(const numeric &other) const
619 // Efficiency shortcut: trap the neutral element by pointer.
622 else if (&other==_num1_p)
625 return numeric(cln::the<cln::cl_N>(value)*cln::the<cln::cl_N>(other.value));
629 /** Numerical division method. Divides *this by argument and returns result as
632 * @exception overflow_error (division by zero) */
633 const numeric numeric::div(const numeric &other) const
635 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
636 throw std::overflow_error("numeric::div(): division by zero");
637 return numeric(cln::the<cln::cl_N>(value)/cln::the<cln::cl_N>(other.value));
641 /** Numerical exponentiation. Raises *this to the power given as argument and
642 * returns result as a numeric object. */
643 const numeric numeric::power(const numeric &other) const
645 // Efficiency shortcut: trap the neutral exponent by pointer.
649 if (cln::zerop(cln::the<cln::cl_N>(value))) {
650 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
651 throw std::domain_error("numeric::eval(): pow(0,0) is undefined");
652 else if (cln::zerop(cln::realpart(cln::the<cln::cl_N>(other.value))))
653 throw std::domain_error("numeric::eval(): pow(0,I) is undefined");
654 else if (cln::minusp(cln::realpart(cln::the<cln::cl_N>(other.value))))
655 throw std::overflow_error("numeric::eval(): division by zero");
659 return numeric(cln::expt(cln::the<cln::cl_N>(value),cln::the<cln::cl_N>(other.value)));
663 const numeric &numeric::add_dyn(const numeric &other) const
665 // Efficiency shortcut: trap the neutral element by pointer.
668 else if (&other==_num0_p)
671 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)+cln::the<cln::cl_N>(other.value)))->
672 setflag(status_flags::dynallocated));
676 const numeric &numeric::sub_dyn(const numeric &other) const
678 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)-cln::the<cln::cl_N>(other.value)))->
679 setflag(status_flags::dynallocated));
683 const numeric &numeric::mul_dyn(const numeric &other) const
685 // Efficiency shortcut: trap the neutral element by pointer.
688 else if (&other==_num1_p)
691 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)*cln::the<cln::cl_N>(other.value)))->
692 setflag(status_flags::dynallocated));
696 const numeric &numeric::div_dyn(const numeric &other) const
698 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
699 throw std::overflow_error("division by zero");
700 return static_cast<const numeric &>((new numeric(cln::the<cln::cl_N>(value)/cln::the<cln::cl_N>(other.value)))->
701 setflag(status_flags::dynallocated));
705 const numeric &numeric::power_dyn(const numeric &other) const
707 // Efficiency shortcut: trap the neutral exponent by pointer.
711 if (cln::zerop(cln::the<cln::cl_N>(value))) {
712 if (cln::zerop(cln::the<cln::cl_N>(other.value)))
713 throw std::domain_error("numeric::eval(): pow(0,0) is undefined");
714 else if (cln::zerop(cln::realpart(cln::the<cln::cl_N>(other.value))))
715 throw std::domain_error("numeric::eval(): pow(0,I) is undefined");
716 else if (cln::minusp(cln::realpart(cln::the<cln::cl_N>(other.value))))
717 throw std::overflow_error("numeric::eval(): division by zero");
721 return static_cast<const numeric &>((new numeric(cln::expt(cln::the<cln::cl_N>(value),cln::the<cln::cl_N>(other.value))))->
722 setflag(status_flags::dynallocated));
726 const numeric &numeric::operator=(int i)
728 return operator=(numeric(i));
732 const numeric &numeric::operator=(unsigned int i)
734 return operator=(numeric(i));
738 const numeric &numeric::operator=(long i)
740 return operator=(numeric(i));
744 const numeric &numeric::operator=(unsigned long i)
746 return operator=(numeric(i));
750 const numeric &numeric::operator=(double d)
752 return operator=(numeric(d));
756 const numeric &numeric::operator=(const char * s)
758 return operator=(numeric(s));
762 /** Inverse of a number. */
763 const numeric numeric::inverse(void) const
765 if (cln::zerop(cln::the<cln::cl_N>(value)))
766 throw std::overflow_error("numeric::inverse(): division by zero");
767 return numeric(cln::recip(cln::the<cln::cl_N>(value)));
771 /** Return the complex half-plane (left or right) in which the number lies.
772 * csgn(x)==0 for x==0, csgn(x)==1 for Re(x)>0 or Re(x)=0 and Im(x)>0,
773 * csgn(x)==-1 for Re(x)<0 or Re(x)=0 and Im(x)<0.
775 * @see numeric::compare(const numeric &other) */
776 int numeric::csgn(void) const
778 if (cln::zerop(cln::the<cln::cl_N>(value)))
780 cln::cl_R r = cln::realpart(cln::the<cln::cl_N>(value));
781 if (!cln::zerop(r)) {
787 if (cln::plusp(cln::imagpart(cln::the<cln::cl_N>(value))))
795 /** This method establishes a canonical order on all numbers. For complex
796 * numbers this is not possible in a mathematically consistent way but we need
797 * to establish some order and it ought to be fast. So we simply define it
798 * to be compatible with our method csgn.
800 * @return csgn(*this-other)
801 * @see numeric::csgn(void) */
802 int numeric::compare(const numeric &other) const
804 // Comparing two real numbers?
805 if (cln::instanceof(value, cln::cl_R_ring) &&
806 cln::instanceof(other.value, cln::cl_R_ring))
807 // Yes, so just cln::compare them
808 return cln::compare(cln::the<cln::cl_R>(value), cln::the<cln::cl_R>(other.value));
810 // No, first cln::compare real parts...
811 cl_signean real_cmp = cln::compare(cln::realpart(cln::the<cln::cl_N>(value)), cln::realpart(cln::the<cln::cl_N>(other.value)));
814 // ...and then the imaginary parts.
815 return cln::compare(cln::imagpart(cln::the<cln::cl_N>(value)), cln::imagpart(cln::the<cln::cl_N>(other.value)));
820 bool numeric::is_equal(const numeric &other) const
822 return cln::equal(cln::the<cln::cl_N>(value),cln::the<cln::cl_N>(other.value));
826 /** True if object is zero. */
827 bool numeric::is_zero(void) const
829 return cln::zerop(cln::the<cln::cl_N>(value));
833 /** True if object is not complex and greater than zero. */
834 bool numeric::is_positive(void) const
837 return cln::plusp(cln::the<cln::cl_R>(value));
842 /** True if object is not complex and less than zero. */
843 bool numeric::is_negative(void) const
846 return cln::minusp(cln::the<cln::cl_R>(value));
851 /** True if object is a non-complex integer. */
852 bool numeric::is_integer(void) const
854 return cln::instanceof(value, cln::cl_I_ring);
858 /** True if object is an exact integer greater than zero. */
859 bool numeric::is_pos_integer(void) const
861 return (this->is_integer() && cln::plusp(cln::the<cln::cl_I>(value)));
865 /** True if object is an exact integer greater or equal zero. */
866 bool numeric::is_nonneg_integer(void) const
868 return (this->is_integer() && !cln::minusp(cln::the<cln::cl_I>(value)));
872 /** True if object is an exact even integer. */
873 bool numeric::is_even(void) const
875 return (this->is_integer() && cln::evenp(cln::the<cln::cl_I>(value)));
879 /** True if object is an exact odd integer. */
880 bool numeric::is_odd(void) const
882 return (this->is_integer() && cln::oddp(cln::the<cln::cl_I>(value)));
886 /** Probabilistic primality test.
888 * @return true if object is exact integer and prime. */
889 bool numeric::is_prime(void) const
891 return (this->is_integer() && cln::isprobprime(cln::the<cln::cl_I>(value)));
895 /** True if object is an exact rational number, may even be complex
896 * (denominator may be unity). */
897 bool numeric::is_rational(void) const
899 return cln::instanceof(value, cln::cl_RA_ring);
903 /** True if object is a real integer, rational or float (but not complex). */
904 bool numeric::is_real(void) const
906 return cln::instanceof(value, cln::cl_R_ring);
910 bool numeric::operator==(const numeric &other) const
912 return cln::equal(cln::the<cln::cl_N>(value), cln::the<cln::cl_N>(other.value));
916 bool numeric::operator!=(const numeric &other) const
918 return !cln::equal(cln::the<cln::cl_N>(value), cln::the<cln::cl_N>(other.value));
922 /** True if object is element of the domain of integers extended by I, i.e. is
923 * of the form a+b*I, where a and b are integers. */
924 bool numeric::is_cinteger(void) const
926 if (cln::instanceof(value, cln::cl_I_ring))
928 else if (!this->is_real()) { // complex case, handle n+m*I
929 if (cln::instanceof(cln::realpart(cln::the<cln::cl_N>(value)), cln::cl_I_ring) &&
930 cln::instanceof(cln::imagpart(cln::the<cln::cl_N>(value)), cln::cl_I_ring))
937 /** True if object is an exact rational number, may even be complex
938 * (denominator may be unity). */
939 bool numeric::is_crational(void) const
941 if (cln::instanceof(value, cln::cl_RA_ring))
943 else if (!this->is_real()) { // complex case, handle Q(i):
944 if (cln::instanceof(cln::realpart(cln::the<cln::cl_N>(value)), cln::cl_RA_ring) &&
945 cln::instanceof(cln::imagpart(cln::the<cln::cl_N>(value)), cln::cl_RA_ring))
952 /** Numerical comparison: less.
954 * @exception invalid_argument (complex inequality) */
955 bool numeric::operator<(const numeric &other) const
957 if (this->is_real() && other.is_real())
958 return (cln::the<cln::cl_R>(value) < cln::the<cln::cl_R>(other.value));
959 throw std::invalid_argument("numeric::operator<(): complex inequality");
963 /** Numerical comparison: less or equal.
965 * @exception invalid_argument (complex inequality) */
966 bool numeric::operator<=(const numeric &other) const
968 if (this->is_real() && other.is_real())
969 return (cln::the<cln::cl_R>(value) <= cln::the<cln::cl_R>(other.value));
970 throw std::invalid_argument("numeric::operator<=(): complex inequality");
974 /** Numerical comparison: greater.
976 * @exception invalid_argument (complex inequality) */
977 bool numeric::operator>(const numeric &other) const
979 if (this->is_real() && other.is_real())
980 return (cln::the<cln::cl_R>(value) > cln::the<cln::cl_R>(other.value));
981 throw std::invalid_argument("numeric::operator>(): complex inequality");
985 /** Numerical comparison: greater or equal.
987 * @exception invalid_argument (complex inequality) */
988 bool numeric::operator>=(const numeric &other) const
990 if (this->is_real() && other.is_real())
991 return (cln::the<cln::cl_R>(value) >= cln::the<cln::cl_R>(other.value));
992 throw std::invalid_argument("numeric::operator>=(): complex inequality");
996 /** Converts numeric types to machine's int. You should check with
997 * is_integer() if the number is really an integer before calling this method.
998 * You may also consider checking the range first. */
999 int numeric::to_int(void) const
1001 GINAC_ASSERT(this->is_integer());
1002 return cln::cl_I_to_int(cln::the<cln::cl_I>(value));
1006 /** Converts numeric types to machine's long. You should check with
1007 * is_integer() if the number is really an integer before calling this method.
1008 * You may also consider checking the range first. */
1009 long numeric::to_long(void) const
1011 GINAC_ASSERT(this->is_integer());
1012 return cln::cl_I_to_long(cln::the<cln::cl_I>(value));
1016 /** Converts numeric types to machine's double. You should check with is_real()
1017 * if the number is really not complex before calling this method. */
1018 double numeric::to_double(void) const
1020 GINAC_ASSERT(this->is_real());
1021 return cln::double_approx(cln::realpart(cln::the<cln::cl_N>(value)));
1025 /** Returns a new CLN object of type cl_N, representing the value of *this.
1026 * This method may be used when mixing GiNaC and CLN in one project.
1028 cln::cl_N numeric::to_cl_N(void) const
1030 return cln::cl_N(cln::the<cln::cl_N>(value));
1034 /** Real part of a number. */
1035 const numeric numeric::real(void) const
1037 return numeric(cln::realpart(cln::the<cln::cl_N>(value)));
1041 /** Imaginary part of a number. */
1042 const numeric numeric::imag(void) const
1044 return numeric(cln::imagpart(cln::the<cln::cl_N>(value)));
1048 /** Numerator. Computes the numerator of rational numbers, rationalized
1049 * numerator of complex if real and imaginary part are both rational numbers
1050 * (i.e numer(4/3+5/6*I) == 8+5*I), the number carrying the sign in all other
1052 const numeric numeric::numer(void) const
1054 if (this->is_integer())
1055 return numeric(*this);
1057 else if (cln::instanceof(value, cln::cl_RA_ring))
1058 return numeric(cln::numerator(cln::the<cln::cl_RA>(value)));
1060 else if (!this->is_real()) { // complex case, handle Q(i):
1061 const cln::cl_RA r = cln::the<cln::cl_RA>(cln::realpart(cln::the<cln::cl_N>(value)));
1062 const cln::cl_RA i = cln::the<cln::cl_RA>(cln::imagpart(cln::the<cln::cl_N>(value)));
1063 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_I_ring))
1064 return numeric(*this);
1065 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_RA_ring))
1066 return numeric(cln::complex(r*cln::denominator(i), cln::numerator(i)));
1067 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_I_ring))
1068 return numeric(cln::complex(cln::numerator(r), i*cln::denominator(r)));
1069 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_RA_ring)) {
1070 const cln::cl_I s = cln::lcm(cln::denominator(r), cln::denominator(i));
1071 return numeric(cln::complex(cln::numerator(r)*(cln::exquo(s,cln::denominator(r))),
1072 cln::numerator(i)*(cln::exquo(s,cln::denominator(i)))));
1075 // at least one float encountered
1076 return numeric(*this);
1080 /** Denominator. Computes the denominator of rational numbers, common integer
1081 * denominator of complex if real and imaginary part are both rational numbers
1082 * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */
1083 const numeric numeric::denom(void) const
1085 if (this->is_integer())
1088 if (cln::instanceof(value, cln::cl_RA_ring))
1089 return numeric(cln::denominator(cln::the<cln::cl_RA>(value)));
1091 if (!this->is_real()) { // complex case, handle Q(i):
1092 const cln::cl_RA r = cln::the<cln::cl_RA>(cln::realpart(cln::the<cln::cl_N>(value)));
1093 const cln::cl_RA i = cln::the<cln::cl_RA>(cln::imagpart(cln::the<cln::cl_N>(value)));
1094 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_I_ring))
1096 if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_RA_ring))
1097 return numeric(cln::denominator(i));
1098 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_I_ring))
1099 return numeric(cln::denominator(r));
1100 if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_RA_ring))
1101 return numeric(cln::lcm(cln::denominator(r), cln::denominator(i)));
1103 // at least one float encountered
1108 /** Size in binary notation. For integers, this is the smallest n >= 0 such
1109 * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
1110 * 2^(n-1) <= x < 2^n.
1112 * @return number of bits (excluding sign) needed to represent that number
1113 * in two's complement if it is an integer, 0 otherwise. */
1114 int numeric::int_length(void) const
1116 if (this->is_integer())
1117 return cln::integer_length(cln::the<cln::cl_I>(value));
1126 /** Imaginary unit. This is not a constant but a numeric since we are
1127 * natively handing complex numbers anyways, so in each expression containing
1128 * an I it is automatically eval'ed away anyhow. */
1129 const numeric I = numeric(cln::complex(cln::cl_I(0),cln::cl_I(1)));
1132 /** Exponential function.
1134 * @return arbitrary precision numerical exp(x). */
1135 const numeric exp(const numeric &x)
1137 return cln::exp(x.to_cl_N());
1141 /** Natural logarithm.
1143 * @param z complex number
1144 * @return arbitrary precision numerical log(x).
1145 * @exception pole_error("log(): logarithmic pole",0) */
1146 const numeric log(const numeric &z)
1149 throw pole_error("log(): logarithmic pole",0);
1150 return cln::log(z.to_cl_N());
1154 /** Numeric sine (trigonometric function).
1156 * @return arbitrary precision numerical sin(x). */
1157 const numeric sin(const numeric &x)
1159 return cln::sin(x.to_cl_N());
1163 /** Numeric cosine (trigonometric function).
1165 * @return arbitrary precision numerical cos(x). */
1166 const numeric cos(const numeric &x)
1168 return cln::cos(x.to_cl_N());
1172 /** Numeric tangent (trigonometric function).
1174 * @return arbitrary precision numerical tan(x). */
1175 const numeric tan(const numeric &x)
1177 return cln::tan(x.to_cl_N());
1181 /** Numeric inverse sine (trigonometric function).
1183 * @return arbitrary precision numerical asin(x). */
1184 const numeric asin(const numeric &x)
1186 return cln::asin(x.to_cl_N());
1190 /** Numeric inverse cosine (trigonometric function).
1192 * @return arbitrary precision numerical acos(x). */
1193 const numeric acos(const numeric &x)
1195 return cln::acos(x.to_cl_N());
1201 * @param z complex number
1203 * @exception pole_error("atan(): logarithmic pole",0) */
1204 const numeric atan(const numeric &x)
1207 x.real().is_zero() &&
1208 abs(x.imag()).is_equal(_num1))
1209 throw pole_error("atan(): logarithmic pole",0);
1210 return cln::atan(x.to_cl_N());
1216 * @param x real number
1217 * @param y real number
1218 * @return atan(y/x) */
1219 const numeric atan(const numeric &y, const numeric &x)
1221 if (x.is_real() && y.is_real())
1222 return cln::atan(cln::the<cln::cl_R>(x.to_cl_N()),
1223 cln::the<cln::cl_R>(y.to_cl_N()));
1225 throw std::invalid_argument("atan(): complex argument");
1229 /** Numeric hyperbolic sine (trigonometric function).
1231 * @return arbitrary precision numerical sinh(x). */
1232 const numeric sinh(const numeric &x)
1234 return cln::sinh(x.to_cl_N());
1238 /** Numeric hyperbolic cosine (trigonometric function).
1240 * @return arbitrary precision numerical cosh(x). */
1241 const numeric cosh(const numeric &x)
1243 return cln::cosh(x.to_cl_N());
1247 /** Numeric hyperbolic tangent (trigonometric function).
1249 * @return arbitrary precision numerical tanh(x). */
1250 const numeric tanh(const numeric &x)
1252 return cln::tanh(x.to_cl_N());
1256 /** Numeric inverse hyperbolic sine (trigonometric function).
1258 * @return arbitrary precision numerical asinh(x). */
1259 const numeric asinh(const numeric &x)
1261 return cln::asinh(x.to_cl_N());
1265 /** Numeric inverse hyperbolic cosine (trigonometric function).
1267 * @return arbitrary precision numerical acosh(x). */
1268 const numeric acosh(const numeric &x)
1270 return cln::acosh(x.to_cl_N());
1274 /** Numeric inverse hyperbolic tangent (trigonometric function).
1276 * @return arbitrary precision numerical atanh(x). */
1277 const numeric atanh(const numeric &x)
1279 return cln::atanh(x.to_cl_N());
1283 /*static cln::cl_N Li2_series(const ::cl_N &x,
1284 const ::float_format_t &prec)
1286 // Note: argument must be in the unit circle
1287 // This is very inefficient unless we have fast floating point Bernoulli
1288 // numbers implemented!
1289 cln::cl_N c1 = -cln::log(1-x);
1291 // hard-wire the first two Bernoulli numbers
1292 cln::cl_N acc = c1 - cln::square(c1)/4;
1294 cln::cl_F pisq = cln::square(cln::cl_pi(prec)); // pi^2
1295 cln::cl_F piac = cln::cl_float(1, prec); // accumulator: pi^(2*i)
1297 c1 = cln::square(c1);
1301 aug = c2 * (*(bernoulli(numeric(2*i)).clnptr())) / cln::factorial(2*i+1);
1302 // aug = c2 * cln::cl_I(i%2 ? 1 : -1) / cln::cl_I(2*i+1) * cln::cl_zeta(2*i, prec) / piac / (cln::cl_I(1)<<(2*i-1));
1305 } while (acc != acc+aug);
1309 /** Numeric evaluation of Dilogarithm within circle of convergence (unit
1310 * circle) using a power series. */
1311 static cln::cl_N Li2_series(const cln::cl_N &x,
1312 const cln::float_format_t &prec)
1314 // Note: argument must be in the unit circle
1316 cln::cl_N num = cln::complex(cln::cl_float(1, prec), 0);
1321 den = den + i; // 1, 4, 9, 16, ...
1325 } while (acc != acc+aug);
1329 /** Folds Li2's argument inside a small rectangle to enhance convergence. */
1330 static cln::cl_N Li2_projection(const cln::cl_N &x,
1331 const cln::float_format_t &prec)
1333 const cln::cl_R re = cln::realpart(x);
1334 const cln::cl_R im = cln::imagpart(x);
1335 if (re > cln::cl_F(".5"))
1336 // zeta(2) - Li2(1-x) - log(x)*log(1-x)
1338 - Li2_series(1-x, prec)
1339 - cln::log(x)*cln::log(1-x));
1340 if ((re <= 0 && cln::abs(im) > cln::cl_F(".75")) || (re < cln::cl_F("-.5")))
1341 // -log(1-x)^2 / 2 - Li2(x/(x-1))
1342 return(- cln::square(cln::log(1-x))/2
1343 - Li2_series(x/(x-1), prec));
1344 if (re > 0 && cln::abs(im) > cln::cl_LF(".75"))
1345 // Li2(x^2)/2 - Li2(-x)
1346 return(Li2_projection(cln::square(x), prec)/2
1347 - Li2_projection(-x, prec));
1348 return Li2_series(x, prec);
1351 /** Numeric evaluation of Dilogarithm. The domain is the entire complex plane,
1352 * the branch cut lies along the positive real axis, starting at 1 and
1353 * continuous with quadrant IV.
1355 * @return arbitrary precision numerical Li2(x). */
1356 const numeric Li2(const numeric &x)
1361 // what is the desired float format?
1362 // first guess: default format
1363 cln::float_format_t prec = cln::default_float_format;
1364 const cln::cl_N value = x.to_cl_N();
1365 // second guess: the argument's format
1366 if (!x.real().is_rational())
1367 prec = cln::float_format(cln::the<cln::cl_F>(cln::realpart(value)));
1368 else if (!x.imag().is_rational())
1369 prec = cln::float_format(cln::the<cln::cl_F>(cln::imagpart(value)));
1371 if (cln::the<cln::cl_N>(value)==1) // may cause trouble with log(1-x)
1372 return cln::zeta(2, prec);
1374 if (cln::abs(value) > 1)
1375 // -log(-x)^2 / 2 - zeta(2) - Li2(1/x)
1376 return(- cln::square(cln::log(-value))/2
1377 - cln::zeta(2, prec)
1378 - Li2_projection(cln::recip(value), prec));
1380 return Li2_projection(x.to_cl_N(), prec);
1384 /** Numeric evaluation of Riemann's Zeta function. Currently works only for
1385 * integer arguments. */
1386 const numeric zeta(const numeric &x)
1388 // A dirty hack to allow for things like zeta(3.0), since CLN currently
1389 // only knows about integer arguments and zeta(3).evalf() automatically
1390 // cascades down to zeta(3.0).evalf(). The trick is to rely on 3.0-3
1391 // being an exact zero for CLN, which can be tested and then we can just
1392 // pass the number casted to an int:
1394 const int aux = (int)(cln::double_approx(cln::the<cln::cl_R>(x.to_cl_N())));
1395 if (cln::zerop(x.to_cl_N()-aux))
1396 return cln::zeta(aux);
1402 /** The Gamma function.
1403 * This is only a stub! */
1404 const numeric lgamma(const numeric &x)
1408 const numeric tgamma(const numeric &x)
1414 /** The psi function (aka polygamma function).
1415 * This is only a stub! */
1416 const numeric psi(const numeric &x)
1422 /** The psi functions (aka polygamma functions).
1423 * This is only a stub! */
1424 const numeric psi(const numeric &n, const numeric &x)
1430 /** Factorial combinatorial function.
1432 * @param n integer argument >= 0
1433 * @exception range_error (argument must be integer >= 0) */
1434 const numeric factorial(const numeric &n)
1436 if (!n.is_nonneg_integer())
1437 throw std::range_error("numeric::factorial(): argument must be integer >= 0");
1438 return numeric(cln::factorial(n.to_int()));
1442 /** The double factorial combinatorial function. (Scarcely used, but still
1443 * useful in cases, like for exact results of tgamma(n+1/2) for instance.)
1445 * @param n integer argument >= -1
1446 * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == (-1)!! == 1
1447 * @exception range_error (argument must be integer >= -1) */
1448 const numeric doublefactorial(const numeric &n)
1450 if (n.is_equal(_num_1))
1453 if (!n.is_nonneg_integer())
1454 throw std::range_error("numeric::doublefactorial(): argument must be integer >= -1");
1456 return numeric(cln::doublefactorial(n.to_int()));
1460 /** The Binomial coefficients. It computes the binomial coefficients. For
1461 * integer n and k and positive n this is the number of ways of choosing k
1462 * objects from n distinct objects. If n is negative, the formula
1463 * binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */
1464 const numeric binomial(const numeric &n, const numeric &k)
1466 if (n.is_integer() && k.is_integer()) {
1467 if (n.is_nonneg_integer()) {
1468 if (k.compare(n)!=1 && k.compare(_num0)!=-1)
1469 return numeric(cln::binomial(n.to_int(),k.to_int()));
1473 return _num_1.power(k)*binomial(k-n-_num1,k);
1477 // should really be gamma(n+1)/gamma(r+1)/gamma(n-r+1) or a suitable limit
1478 throw std::range_error("numeric::binomial(): don´t know how to evaluate that.");
1482 /** Bernoulli number. The nth Bernoulli number is the coefficient of x^n/n!
1483 * in the expansion of the function x/(e^x-1).
1485 * @return the nth Bernoulli number (a rational number).
1486 * @exception range_error (argument must be integer >= 0) */
1487 const numeric bernoulli(const numeric &nn)
1489 if (!nn.is_integer() || nn.is_negative())
1490 throw std::range_error("numeric::bernoulli(): argument must be integer >= 0");
1494 // The Bernoulli numbers are rational numbers that may be computed using
1497 // B_n = - 1/(n+1) * sum_{k=0}^{n-1}(binomial(n+1,k)*B_k)
1499 // with B(0) = 1. Since the n'th Bernoulli number depends on all the
1500 // previous ones, the computation is necessarily very expensive. There are
1501 // several other ways of computing them, a particularly good one being
1505 // for (unsigned i=0; i<n; i++) {
1506 // c = exquo(c*(i-n),(i+2));
1507 // Bern = Bern + c*s/(i+2);
1508 // s = s + expt_pos(cl_I(i+2),n);
1512 // But if somebody works with the n'th Bernoulli number she is likely to
1513 // also need all previous Bernoulli numbers. So we need a complete remember
1514 // table and above divide and conquer algorithm is not suited to build one
1515 // up. The code below is adapted from Pari's function bernvec().
1517 // (There is an interesting relation with the tangent polynomials described
1518 // in `Concrete Mathematics', which leads to a program twice as fast as our
1519 // implementation below, but it requires storing one such polynomial in
1520 // addition to the remember table. This doubles the memory footprint so
1521 // we don't use it.)
1523 // the special cases not covered by the algorithm below
1524 if (nn.is_equal(_num1))
1529 // store nonvanishing Bernoulli numbers here
1530 static std::vector< cln::cl_RA > results;
1531 static int highest_result = 0;
1532 // algorithm not applicable to B(0), so just store it
1533 if (results.empty())
1534 results.push_back(cln::cl_RA(1));
1536 int n = nn.to_long();
1537 for (int i=highest_result; i<n/2; ++i) {
1543 for (int j=i; j>0; --j) {
1544 B = cln::cl_I(n*m) * (B+results[j]) / (d1*d2);
1550 B = (1 - ((B+1)/(2*i+3))) / (cln::cl_I(1)<<(2*i+2));
1551 results.push_back(B);
1554 return results[n/2];
1558 /** Fibonacci number. The nth Fibonacci number F(n) is defined by the
1559 * recurrence formula F(n)==F(n-1)+F(n-2) with F(0)==0 and F(1)==1.
1561 * @param n an integer
1562 * @return the nth Fibonacci number F(n) (an integer number)
1563 * @exception range_error (argument must be an integer) */
1564 const numeric fibonacci(const numeric &n)
1566 if (!n.is_integer())
1567 throw std::range_error("numeric::fibonacci(): argument must be integer");
1570 // The following addition formula holds:
1572 // F(n+m) = F(m-1)*F(n) + F(m)*F(n+1) for m >= 1, n >= 0.
1574 // (Proof: For fixed m, the LHS and the RHS satisfy the same recurrence
1575 // w.r.t. n, and the initial values (n=0, n=1) agree. Hence all values
1577 // Replace m by m+1:
1578 // F(n+m+1) = F(m)*F(n) + F(m+1)*F(n+1) for m >= 0, n >= 0
1579 // Now put in m = n, to get
1580 // F(2n) = (F(n+1)-F(n))*F(n) + F(n)*F(n+1) = F(n)*(2*F(n+1) - F(n))
1581 // F(2n+1) = F(n)^2 + F(n+1)^2
1583 // F(2n+2) = F(n+1)*(2*F(n) + F(n+1))
1586 if (n.is_negative())
1588 return -fibonacci(-n);
1590 return fibonacci(-n);
1594 cln::cl_I m = cln::the<cln::cl_I>(n.to_cl_N()) >> 1L; // floor(n/2);
1595 for (uintL bit=cln::integer_length(m); bit>0; --bit) {
1596 // Since a squaring is cheaper than a multiplication, better use
1597 // three squarings instead of one multiplication and two squarings.
1598 cln::cl_I u2 = cln::square(u);
1599 cln::cl_I v2 = cln::square(v);
1600 if (cln::logbitp(bit-1, m)) {
1601 v = cln::square(u + v) - u2;
1604 u = v2 - cln::square(v - u);
1609 // Here we don't use the squaring formula because one multiplication
1610 // is cheaper than two squarings.
1611 return u * ((v << 1) - u);
1613 return cln::square(u) + cln::square(v);
1617 /** Absolute value. */
1618 const numeric abs(const numeric& x)
1620 return cln::abs(x.to_cl_N());
1624 /** Modulus (in positive representation).
1625 * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the
1626 * sign of a or is zero. This is different from Maple's modp, where the sign
1627 * of b is ignored. It is in agreement with Mathematica's Mod.
1629 * @return a mod b in the range [0,abs(b)-1] with sign of b if both are
1630 * integer, 0 otherwise. */
1631 const numeric mod(const numeric &a, const numeric &b)
1633 if (a.is_integer() && b.is_integer())
1634 return cln::mod(cln::the<cln::cl_I>(a.to_cl_N()),
1635 cln::the<cln::cl_I>(b.to_cl_N()));
1641 /** Modulus (in symmetric representation).
1642 * Equivalent to Maple's mods.
1644 * @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */
1645 const numeric smod(const numeric &a, const numeric &b)
1647 if (a.is_integer() && b.is_integer()) {
1648 const cln::cl_I b2 = cln::ceiling1(cln::the<cln::cl_I>(b.to_cl_N()) >> 1) - 1;
1649 return cln::mod(cln::the<cln::cl_I>(a.to_cl_N()) + b2,
1650 cln::the<cln::cl_I>(b.to_cl_N())) - b2;
1656 /** Numeric integer remainder.
1657 * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned.
1658 * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the
1659 * sign of a or is zero.
1661 * @return remainder of a/b if both are integer, 0 otherwise. */
1662 const numeric irem(const numeric &a, const numeric &b)
1664 if (a.is_integer() && b.is_integer())
1665 return cln::rem(cln::the<cln::cl_I>(a.to_cl_N()),
1666 cln::the<cln::cl_I>(b.to_cl_N()));
1672 /** Numeric integer remainder.
1673 * Equivalent to Maple's irem(a,b,'q') it obeyes the relation
1674 * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero,
1675 * and irem(a,b) has the sign of a or is zero.
1677 * @return remainder of a/b and quotient stored in q if both are integer,
1679 const numeric irem(const numeric &a, const numeric &b, numeric &q)
1681 if (a.is_integer() && b.is_integer()) {
1682 const cln::cl_I_div_t rem_quo = cln::truncate2(cln::the<cln::cl_I>(a.to_cl_N()),
1683 cln::the<cln::cl_I>(b.to_cl_N()));
1684 q = rem_quo.quotient;
1685 return rem_quo.remainder;
1693 /** Numeric integer quotient.
1694 * Equivalent to Maple's iquo as far as sign conventions are concerned.
1696 * @return truncated quotient of a/b if both are integer, 0 otherwise. */
1697 const numeric iquo(const numeric &a, const numeric &b)
1699 if (a.is_integer() && b.is_integer())
1700 return cln::truncate1(cln::the<cln::cl_I>(a.to_cl_N()),
1701 cln::the<cln::cl_I>(b.to_cl_N()));
1707 /** Numeric integer quotient.
1708 * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation
1709 * r == a - iquo(a,b,r)*b.
1711 * @return truncated quotient of a/b and remainder stored in r if both are
1712 * integer, 0 otherwise. */
1713 const numeric iquo(const numeric &a, const numeric &b, numeric &r)
1715 if (a.is_integer() && b.is_integer()) {
1716 const cln::cl_I_div_t rem_quo = cln::truncate2(cln::the<cln::cl_I>(a.to_cl_N()),
1717 cln::the<cln::cl_I>(b.to_cl_N()));
1718 r = rem_quo.remainder;
1719 return rem_quo.quotient;
1727 /** Greatest Common Divisor.
1729 * @return The GCD of two numbers if both are integer, a numerical 1
1730 * if they are not. */
1731 const numeric gcd(const numeric &a, const numeric &b)
1733 if (a.is_integer() && b.is_integer())
1734 return cln::gcd(cln::the<cln::cl_I>(a.to_cl_N()),
1735 cln::the<cln::cl_I>(b.to_cl_N()));
1741 /** Least Common Multiple.
1743 * @return The LCM of two numbers if both are integer, the product of those
1744 * two numbers if they are not. */
1745 const numeric lcm(const numeric &a, const numeric &b)
1747 if (a.is_integer() && b.is_integer())
1748 return cln::lcm(cln::the<cln::cl_I>(a.to_cl_N()),
1749 cln::the<cln::cl_I>(b.to_cl_N()));
1755 /** Numeric square root.
1756 * If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4)
1757 * should return integer 2.
1759 * @param z numeric argument
1760 * @return square root of z. Branch cut along negative real axis, the negative
1761 * real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part
1762 * where imag(z)>0. */
1763 const numeric sqrt(const numeric &z)
1765 return cln::sqrt(z.to_cl_N());
1769 /** Integer numeric square root. */
1770 const numeric isqrt(const numeric &x)
1772 if (x.is_integer()) {
1774 cln::isqrt(cln::the<cln::cl_I>(x.to_cl_N()), &root);
1781 /** Floating point evaluation of Archimedes' constant Pi. */
1784 return numeric(cln::pi(cln::default_float_format));
1788 /** Floating point evaluation of Euler's constant gamma. */
1791 return numeric(cln::eulerconst(cln::default_float_format));
1795 /** Floating point evaluation of Catalan's constant. */
1796 ex CatalanEvalf(void)
1798 return numeric(cln::catalanconst(cln::default_float_format));
1802 /** _numeric_digits default ctor, checking for singleton invariance. */
1803 _numeric_digits::_numeric_digits()
1806 // It initializes to 17 digits, because in CLN float_format(17) turns out
1807 // to be 61 (<64) while float_format(18)=65. The reason is we want to
1808 // have a cl_LF instead of cl_SF, cl_FF or cl_DF.
1810 throw(std::runtime_error("I told you not to do instantiate me!"));
1812 cln::default_float_format = cln::float_format(17);
1816 /** Assign a native long to global Digits object. */
1817 _numeric_digits& _numeric_digits::operator=(long prec)
1820 cln::default_float_format = cln::float_format(prec);
1825 /** Convert global Digits object to native type long. */
1826 _numeric_digits::operator long()
1828 // BTW, this is approx. unsigned(cln::default_float_format*0.301)-1
1829 return (long)digits;
1833 /** Append global Digits object to ostream. */
1834 void _numeric_digits::print(std::ostream &os) const
1840 std::ostream& operator<<(std::ostream &os, const _numeric_digits &e)
1847 // static member variables
1852 bool _numeric_digits::too_late = false;
1855 /** Accuracy in decimal digits. Only object of this type! Can be set using
1856 * assignment from C++ unsigned ints and evaluated like any built-in type. */
1857 _numeric_digits Digits;
1859 } // namespace GiNaC