From 8a50a86abe6af017d8df84361366b1500b45d0ca Mon Sep 17 00:00:00 2001 From: Jens Vollinga Date: Thu, 27 Apr 2006 15:42:41 +0000 Subject: [PATCH] * _function suffix only for cmath functions and conjugate(). * fixed printing defaults for functions. * removed functions "numerical (const numeric& x)". For the internally used abs, factorial and binomial functions static members of the respective classes have been added. --- check/check_numeric.cpp | 126 ++ ginac/function.cpp | 74 +- ginac/function.h | 11 +- ginac/inifcns.cpp | 187 ++- ginac/inifcns.h | 75 +- ginac/inifcns_exp.cpp | 171 ++- ginac/inifcns_exp.h | 38 +- ginac/inifcns_polylog.cpp | 62 +- ginac/inifcns_polylog.h | 2 +- ginac/inifcns_trig.cpp | 234 ++-- ginac/inifcns_trig.h | 36 +- ginac/integral.cpp | 2 +- ginac/matrix.cpp | 5 +- ginac/normal.cpp | 14 +- ginac/numeric.cpp | 2454 ++++++++++++++++++++++--------------- ginac/numeric.h | 436 ++++--- ginac/power.cpp | 11 +- ginac/pseries.cpp | 36 +- ginac/symbol.cpp | 2 +- ginac/symmetry.cpp | 2 +- 20 files changed, 2271 insertions(+), 1707 deletions(-) create mode 100644 check/check_numeric.cpp diff --git a/check/check_numeric.cpp b/check/check_numeric.cpp new file mode 100644 index 00000000..9649d6d3 --- /dev/null +++ b/check/check_numeric.cpp @@ -0,0 +1,126 @@ +/** @file check_numeric.cpp + * + * These exams creates some numbers and check the result of several boolean + * tests on these numbers like is_integer() etc... */ + +/* + * GiNaC Copyright (C) 1999-2005 Johannes Gutenberg University Mainz, Germany + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "checks.h" + +/* Simple and maybe somewhat pointless consistency tests of assorted tests and + * conversions. */ +static unsigned check_numeric1() +{ + unsigned result = 0; + bool errorflag = false; + int re_q, im_q; + + // Check some numerator and denominator calculations: + for (int rep=0; rep<200; ++rep) { + do { re_q = rand(); } while (re_q == 0); + do { im_q = rand(); } while (im_q == 0); + numeric r(rand()-RAND_MAX/2, re_q); + numeric i(rand()-RAND_MAX/2, im_q); + numeric z = r + I*i; + numeric p = numer(z); + numeric q = denom(z); + numeric res = p/q; + if (res != z) { + clog << z << " erroneously transformed into " + << p << "/" << q << " by numer() and denom()" << endl; + errorflag = true; + } + } + if (errorflag) + ++result; + + return result; +} + +static unsigned check_numeric2() +{ + unsigned result = 0; + bool errorflag = false; + int i_num, i_den; + + // Check non-nested radicals (n/d)^(m/n) in ex wrapper class: + for (int i=0; i<200; ++i) { + for (int j=2; j<13; ++j) { + // construct an exponent 1/j... + numeric nm(1,j); + nm += numeric(int(20.0*rand()/(RAND_MAX+1.0))-10); + // ...a numerator... + do { + i_num = rand(); + } while (i_num<=0); + numeric num(i_num); + // ...and a denominator. + do { + i_den = (rand())/100; + } while (i_den<=0); + numeric den(i_den); + // construct the radicals: + ex radical = pow(ex(num)/ex(den),ex(nm)); + numeric floating = pow(num/den,nm); + // test the result: + if (is_a(radical)) { + // This is very improbable with decent random numbers but it + // still can happen, so we better check if it is correct: + if (pow(radical,inverse(nm))==num/den) { + // Aha! We drew some lucky numbers. Nothing to see here... + } else { + clog << "(" << num << "/" << den << ")^(" << nm + << ") should have been a product, instead it's " + << radical << endl; + errorflag = true; + } + } + numeric ratio = abs_function::eval_numeric(ex_to(evalf(radical))/floating); + if (ratio>1.0001 && ratio<0.9999) { + clog << "(" << num << "/" << den << ")^(" << nm + << ") erroneously evaluated to " << radical; + errorflag = true; + } + } + } + if (errorflag) + ++result; + + return result; +} + +unsigned check_numeric() +{ + unsigned result = 0; + + cout << "checking consistency of numeric types" << flush; + clog << "---------consistency of numeric types:" << endl; + + result += check_numeric1(); cout << '.' << flush; + result += check_numeric2(); cout << '.' << flush; + + if (!result) { + cout << " passed " << endl; + clog << "(no output)" << endl; + } else { + cout << " failed " << endl; + } + + return result; +} diff --git a/ginac/function.cpp b/ginac/function.cpp index 6a322db0..ecbb0110 100644 --- a/ginac/function.cpp +++ b/ginac/function.cpp @@ -32,7 +32,10 @@ namespace GiNaC { -GINAC_IMPLEMENT_REGISTERED_CLASS(function, exprseq) +GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(function, exprseq, + print_func(&function::do_print). + print_func(&function::do_print_latex). + print_func(&function::do_print_tree)) function::function(const archive_node& n, lst& sym_lst) : inherited(n, sym_lst) { @@ -147,12 +150,6 @@ ex function::power_law(const ex& exp) const ex function::expand(unsigned options) const { return setflag(status_flags::expanded); -//TODO?? -// // Only expand arguments when asked to do so -// if (options & expand_options::expand_function_args) -// return inherited::expand(options); -// else -// return (options == 0) ? setflag(status_flags::expanded) : *this; } bool function::info(unsigned inf) const @@ -164,33 +161,44 @@ bool function::info(unsigned inf) const } } -void function::print(const print_context& c, unsigned level) const -{ - const std::vector& pdt = get_class_info().options.get_print_dispatch_table(); - unsigned id = c.get_class_info().options.get_id(); - if (id >= pdt.size() || !(pdt[id].is_valid())) { - if (is_a(c)) { - c.s << std::string(level, ' ') << class_name() - << " @" << this - << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec - << ", nops=" << nops() - << std::endl; - unsigned delta_indent = static_cast(c).delta_indent; - for (size_t i=0; i(c)) { - c.s << "\\mbox{" << class_name() << "}"; - inherited::do_print(c,level); - } else { - std::string classname(class_name()); - c.s << classname.erase(classname.find("_function",0),9); - inherited::do_print(c,level); - } - } else { - pdt[id](*this, c, level); +void function::do_print(const print_context& c, unsigned level) const +{ + std::string classname(class_name()); + c.s << classname; + inherited::do_print(c,level); +} + +void function::do_print_cmath(const print_context& c, unsigned level) const +{ + std::string classname(class_name()); + c.s << classname.erase(classname.find("_function",0),9); + inherited::do_print(c, level); +} + +void function::do_print_cmath_latex(const print_context& c, unsigned level) const +{ + c.s << "\\"; + do_print_cmath(c, level); +} + +void function::do_print_latex(const print_context& c, unsigned level) const +{ + c.s << "\\mbox{" << class_name() << "}"; + inherited::do_print(c, level); +} + +void function::do_print_tree(const print_context& c, unsigned level) const +{ + c.s << std::string(level, ' ') << class_name() + << " @" << this + << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec + << ", nops=" << nops() + << std::endl; + unsigned delta_indent = static_cast(c).delta_indent; + for (size_t i=0; i #include #include @@ -45,8 +46,10 @@ namespace GiNaC { ////////// GINAC_IMPLEMENT_FUNCTION_OPT(abs_function, + print_func(&function::do_print_cmath). print_func(&abs_function::do_print_csrc_float). - print_func(&abs_function::do_print_latex)) + print_func(&abs_function::do_print_latex). + print_func(&function::do_print_tree)) ex abs_function::conjugate() const { @@ -57,7 +60,7 @@ ex abs_function::eval(int level) const { const ex& arg = seq[0]; if (is_exactly_a(arg)) - return abs(ex_to(arg)); + return eval_numeric(ex_to(arg)); else return this->hold(); } @@ -66,7 +69,7 @@ ex abs_function::evalf(int level) const { const ex& arg = seq[0]; if (is_exactly_a(arg)) { - return abs(ex_to(arg)); + return eval_numeric(ex_to(arg)); } return this->hold(); @@ -81,6 +84,11 @@ ex abs_function::power_law(const ex& exp) const return power(abs(arg), exp).hold(); } +numeric abs_function::eval_numeric(const numeric& x) +{ + return cln::abs(x.to_cl_N()); +} + void abs_function::do_print_csrc_float(const print_context& c, unsigned level) const { c.s << "fabs("; seq[0].print(c); c.s << ")"; @@ -96,7 +104,9 @@ void abs_function::do_print_latex(const print_context& c, unsigned level) const ////////// GINAC_IMPLEMENT_FUNCTION_OPT(conjugate_function, - print_func(&conjugate_function::do_print_latex)) + print_func(&function::do_print_cmath). + print_func(&conjugate_function::do_print_latex). + print_func(&function::do_print_tree)) ex conjugate_function::conjugate() const { @@ -120,26 +130,30 @@ ex conjugate_function::evalf(int level) const void conjugate_function::do_print_latex(const print_context& c, unsigned level) const { const ex& arg = seq[0]; - c.s << "\\bar{"; arg.print(c); c.s << "}"; + if (is_exactly_a(arg)) { + c.s << "{" << arg << "^\\ast}"; + } else { + c.s << "{\\left(" << arg << "\\right)}^\\ast}"; + } } ////////// // Complex sign ////////// -GINAC_IMPLEMENT_FUNCTION(csgn_function) +GINAC_IMPLEMENT_FUNCTION(csgn) -ex csgn_function::conjugate() const +ex csgn::conjugate() const { return *this; } -ex csgn_function::eval(int level) const +ex csgn::eval(int level) const { const ex& arg = seq[0]; if (is_exactly_a(arg)) - return csgn(ex_to(arg)); + return ex_to(arg).csgn(); else if (is_exactly_a(arg) && is_exactly_a(arg.op(arg.nops()-1))) { @@ -165,16 +179,16 @@ ex csgn_function::eval(int level) const return this->hold(); } -ex csgn_function::evalf(int level) const +ex csgn::evalf(int level) const { const ex& arg = seq[0]; if (is_exactly_a(arg)) - return csgn(ex_to(arg)); + return ex_to(arg).csgn(); return this->hold(); } -ex csgn_function::power_law(const ex& exp) const +ex csgn::power_law(const ex& exp) const { const ex& arg = seq[0]; if (is_a(exp) && exp.info(info_flags::positive) && ex_to(exp).is_integer()) { @@ -186,7 +200,7 @@ ex csgn_function::power_law(const ex& exp) const return power(*this, exp).hold(); } -ex csgn_function::series(const relational& r, int order, unsigned options) const +ex csgn::series(const relational& r, int order, unsigned options) const { const ex& arg = seq[0]; const ex arg_pt = arg.subs(r, subs_options::no_pattern); @@ -204,19 +218,19 @@ ex csgn_function::series(const relational& r, int order, unsigned options) const // Step function ////////// -GINAC_IMPLEMENT_FUNCTION(step_function) +GINAC_IMPLEMENT_FUNCTION(step) -ex step_function::conjugate() const +ex step::conjugate() const { return *this; } -ex step_function::eval(int level) const +ex step::eval(int level) const { const ex& arg = seq[0]; if (is_exactly_a(arg)) - return step(ex_to(arg)); + return ex_to(arg).step(); else if (is_exactly_a(arg) && is_exactly_a(arg.op(arg.nops()-1))) { @@ -242,16 +256,16 @@ ex step_function::eval(int level) const return this->hold(); } -ex step_function::evalf(int level) const +ex step::evalf(int level) const { const ex& arg = seq[0]; if (is_exactly_a(arg)) - return step(ex_to(arg)); + return ex_to(arg).step(); return this->hold(); } -ex step_function::series(const relational& rel, int order, unsigned options) const +ex step::series(const relational& rel, int order, unsigned options) const { const ex& arg = seq[0]; const ex arg_pt = arg.subs(rel, subs_options::no_pattern); @@ -269,30 +283,37 @@ ex step_function::series(const relational& rel, int order, unsigned options) con // factorial ////////// -GINAC_IMPLEMENT_FUNCTION_OPT(factorial_function, - print_func(&factorial_function::do_print_dflt_latex). - print_func(&factorial_function::do_print_dflt_latex)) +GINAC_IMPLEMENT_FUNCTION_OPT(factorial, + print_func(&factorial::do_print_dflt_latex). + print_func(&factorial::do_print_dflt_latex)) -ex factorial_function::conjugate() const +ex factorial::conjugate() const { return *this; } -ex factorial_function::eval(int level) const +ex factorial::eval(int level) const { const ex& x = seq[0]; if (is_exactly_a(x)) - return factorial(ex_to(x)); + return eval_numeric(ex_to(x)); else return this->hold(); } -ex factorial_function::evalf(int level) const +ex factorial::evalf(int level) const { return this->hold(); } -void factorial_function::do_print_dflt_latex(const print_context& c, unsigned level) const +numeric factorial::eval_numeric(const numeric& x) +{ + if (!x.is_nonneg_integer()) + throw std::range_error("numeric::factorial(): argument must be integer >= 0"); + return numeric(cln::factorial(x.to_int())); +} + +void factorial::do_print_dflt_latex(const print_context& c, unsigned level) const { const ex& x = seq[0]; if (is_exactly_a(x) || is_exactly_a(x) || is_exactly_a(x)) { @@ -306,17 +327,57 @@ void factorial_function::do_print_dflt_latex(const print_context& c, unsigned le // binomial ////////// -GINAC_IMPLEMENT_FUNCTION(binomial_function) +GINAC_IMPLEMENT_FUNCTION_OPT(binomial, + print_func(&binomial::do_print_latex)) // At the moment the numeric evaluation of a binomail function always // gives a real number, but if this would be implemented using the gamma // function, also complex conjugation should be changed (or rather, deleted). -ex binomial_function::conjugate() const +ex binomial::conjugate() const { return *this; } -ex binomial_function::sym(const ex& x, const numeric& y) const +ex binomial::eval(int level) const +{ + const ex& x = seq[0]; + const ex& y = seq[1]; + if (is_exactly_a(y)) { + if (is_exactly_a(x) && ex_to(x).is_integer()) + return eval_numeric(ex_to(x), ex_to(y)); + else + return sym(x, ex_to(y)); + } else + return this->hold(); +} + +ex binomial::evalf(int level) const +{ + return this->hold(); +} + +/** The Binomial coefficients. It computes the binomial coefficients. For + * integer n and k and positive n this is the number of ways of choosing k + * objects from n distinct objects. If n is negative, the formula + * binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */ +numeric binomial::eval_numeric(const numeric& n, const numeric& k) +{ + if (n.is_integer() && k.is_integer()) { + if (n.is_nonneg_integer()) { + if (k.compare(n)!=1 && k.compare(*_num0_p)!=-1) + return numeric(cln::binomial(n.to_int(),k.to_int())); + else + return *_num0_p; + } else { + return _num_1_p->power(k)*eval_numeric(k-n-(*_num1_p),k); + } + } + + // should really be gamma(n+1)/gamma(k+1)/gamma(n-k+1) or a suitable limit + throw std::range_error("binomial::eval_numeric(): don't know how to evaluate that."); +} + +ex binomial::sym(const ex& x, const numeric& y) const { if (y.is_integer()) { if (y.is_nonneg_integer()) { @@ -334,42 +395,29 @@ ex binomial_function::sym(const ex& x, const numeric& y) const return this->hold(); } -ex binomial_function::eval(int level) const -{ - const ex& x = seq[0]; - const ex& y = seq[1]; - if (is_exactly_a(y)) { - if (is_exactly_a(x) && ex_to(x).is_integer()) - return binomial(ex_to(x), ex_to(y)); - else - return sym(x, ex_to(y)); - } else - return this->hold(); -} - -ex binomial_function::evalf(int level) const +void binomial::do_print_latex(const print_context& c, unsigned level) const { - return this->hold(); + c.s << "{ {" << seq[0] << "} \\choose {" << seq[1] << "} }"; } ////////// // Order term function (for truncated power series) ////////// -GINAC_IMPLEMENT_FUNCTION_OPT(Order_function, - print_func(&Order_function::do_print_latex)) +GINAC_IMPLEMENT_FUNCTION_OPT(Order, + print_func(&Order::do_print_latex)) -ex Order_function::conjugate() const +ex Order::conjugate() const { return *this; } -ex Order_function::derivative(const symbol& s) const +ex Order::derivative(const symbol& s) const { return Order(seq[0].diff(s)); } -ex Order_function::eval(int level) const +ex Order::eval(int level) const { const ex& x = op(0); if (is_exactly_a(x)) { @@ -387,7 +435,7 @@ ex Order_function::eval(int level) const return this->hold(); } -ex Order_function::series(const relational& r, int order, unsigned options) const +ex Order::series(const relational& r, int order, unsigned options) const { const ex& x = op(0); // Just wrap the function into a pseries object @@ -398,23 +446,24 @@ ex Order_function::series(const relational& r, int order, unsigned options) cons return pseries(r, new_seq); } -void Order_function::do_print_latex(const print_context& c, unsigned level) const +void Order::do_print_latex(const print_context& c, unsigned level) const { c.s << "\\mathcal{O}"; - inherited::do_print(c,level); + exprseq::do_print(c,level); } ////////// // Abstract derivative of functions ////////// -GINAC_IMPLEMENT_FUNCTION_OPT(function_derivative_function, - print_func(&function_derivative_function::do_print_dflt). - print_func(&function_derivative_function::do_print_tree)) +GINAC_IMPLEMENT_FUNCTION_OPT(function_derivative, + print_func(&function_derivative::do_print_dflt). + print_func(&function_derivative::do_print_latex). + print_func(&function_derivative::do_print_tree)) /** Implementation of ex::diff() for derivatives. It applies the chain rule. * @see ex::diff */ -ex function_derivative_function::derivative(const symbol& s) const +ex function_derivative::derivative(const symbol& s) const { GINAC_ASSERT(seq[0].size() == 2); GINAC_ASSERT(is_a(seq[0])); @@ -434,11 +483,11 @@ ex function_derivative_function::derivative(const symbol& s) const return result; } -ex function_derivative_function::eval(int level) const +ex function_derivative::eval(int level) const { if (level > 1) { // first evaluate children, then we will end up here again - return function_derivative_function(evalchildren(level)); + return function_derivative(evalchildren(level)); } const ex& params = seq[0]; @@ -454,7 +503,7 @@ ex function_derivative_function::eval(int level) const return this->hold(); } -void function_derivative_function::do_print_dflt(const print_context& c, unsigned level) const +void function_derivative::do_print_dflt(const print_context& c, unsigned level) const { c.s << "D["; const lst& params = ex_to(seq[0]); @@ -466,7 +515,19 @@ void function_derivative_function::do_print_dflt(const print_context& c, unsigne c.s << *i << "](" << seq[1] << ")"; } -void function_derivative_function::do_print_tree(const print_tree& c, unsigned level) const +void function_derivative::do_print_latex(const print_context& c, unsigned level) const +{ + c.s << "\\mbox{D}["; + const lst& params = ex_to(seq[0]); + lst::const_iterator i = params.begin(), end = params.end(); + --end; + while (i != end) { + c.s << *i++ << ","; + } + c.s << *i << "](" << seq[1] << ")"; +} + +void function_derivative::do_print_tree(const print_tree& c, unsigned level) const { c.s << std::string(level, ' ') << class_name() << " " << ex_to(seq[1]).class_name() << " @" << this diff --git a/ginac/inifcns.h b/ginac/inifcns.h index 1f6761b7..c7c85ac9 100644 --- a/ginac/inifcns.h +++ b/ginac/inifcns.h @@ -1,6 +1,6 @@ /** @file inifcns.h * - * Interface to GiNaC's initially known functions. */ + * Interface to GiNaC's initially known basic functions. */ /* * GiNaC Copyright (C) 1999-2006 Johannes Gutenberg University Mainz, Germany @@ -38,6 +38,8 @@ public: virtual ex eval(int level = 0) const; virtual ex evalf(int level = 0) const; virtual ex power_law(const ex& exp) const; +public: + static numeric eval_numeric(const numeric& x); protected: void do_print_csrc_float(const print_context& c, unsigned level) const; void do_print_latex(const print_context& c, unsigned level) const; @@ -48,24 +50,35 @@ inline abs_function abs(double x1) { return abs_function(x1); } inline abs_function abs(float x1) { return abs_function(x1); } /** Complex conjugate. */ -GINAC_FUNCTION_1P(conjugate, - GINAC_FUNCTION_conjugate - GINAC_FUNCTION_eval - GINAC_FUNCTION_evalf - GINAC_FUNCTION_print_latex) +class conjugate_function : public function +{ + GINAC_DECLARE_FUNCTION_1P(conjugate_function) +public: + virtual ex conjugate() const; + virtual ex eval(int level = 0) const; + virtual ex evalf(int level = 0) const; +protected: + void do_print_latex(const print_context& c, unsigned level) const; +}; + +template inline conjugate_function conjugate(const T1& x1) { return conjugate_function(x1); } /** Complex sign. */ -GINAC_FUNCTION_1P(csgn, - GINAC_FUNCTION_conjugate - GINAC_FUNCTION_eval - GINAC_FUNCTION_evalf - GINAC_FUNCTION_power_law - GINAC_FUNCTION_series) +class csgn : public function +{ + GINAC_DECLARE_FUNCTION_1P(csgn) +public: + virtual ex conjugate() const; + virtual ex eval(int level = 0) const; + virtual ex evalf(int level = 0) const; + virtual ex power_law(const ex& exp) const; + virtual ex series(const relational& r, int order, unsigned options = 0) const; +}; /** Step function. */ -class step_function : public function +class step : public function { - GINAC_DECLARE_FUNCTION_1P(step_function) + GINAC_DECLARE_FUNCTION_1P(step) public: virtual ex conjugate() const; virtual ex eval(int level = 0) const; @@ -73,40 +86,40 @@ public: virtual ex series(const relational& r, int order, unsigned options = 0) const; }; -template inline step_function step(const T1& x1) { return step_function(x1); } - /** Factorial function. */ -class factorial_function : public function +class factorial : public function { - GINAC_DECLARE_FUNCTION_1P(factorial_function) + GINAC_DECLARE_FUNCTION_1P(factorial) public: virtual ex conjugate() const; virtual ex eval(int level = 0) const; virtual ex evalf(int level = 0) const; +public: + static numeric eval_numeric(const numeric& x); protected: void do_print_dflt_latex(const print_context& c, unsigned level) const; }; -template inline factorial_function factorial(const T1& x1) { return factorial_function(x1); } - /** Binomial function. */ -class binomial_function : public function +class binomial : public function { - GINAC_DECLARE_FUNCTION_2P(binomial_function) + GINAC_DECLARE_FUNCTION_2P(binomial) public: virtual ex conjugate() const; virtual ex eval(int level = 0) const; virtual ex evalf(int level = 0) const; +public: + static numeric eval_numeric(const numeric& n, const numeric& k); protected: ex sym(const ex& x, const numeric& y) const; +protected: + void do_print_latex(const print_context& c, unsigned level) const; }; -template inline binomial_function binomial(const T1& x1, const T2& x2) { return binomial_function(x1, x2); } - /** Order term function (for truncated power series). */ -class Order_function : public function +class Order : public function { - GINAC_DECLARE_FUNCTION_1P(Order_function) + GINAC_DECLARE_FUNCTION_1P(Order) public: virtual ex conjugate() const; virtual ex derivative(const symbol& s) const; @@ -116,23 +129,19 @@ protected: void do_print_latex(const print_context& c, unsigned level) const; }; -template inline Order_function Order(const T1& x1) { return Order_function(x1); } - /** Abstract derivative of functions. */ -class function_derivative_function : public function +class function_derivative : public function { - GINAC_DECLARE_FUNCTION_2P(function_derivative_function) + GINAC_DECLARE_FUNCTION_2P(function_derivative) public: virtual ex derivative(const symbol& s) const; virtual ex eval(int level = 0) const; protected: void do_print_dflt(const print_context& c, unsigned level) const; + void do_print_latex(const print_context& c, unsigned level) const; void do_print_tree(const print_tree& c, unsigned level) const; }; -template -inline function_derivative_function function_derivative(const T1& x1, const T2& x2) { return function_derivative_function(x1, x2); } - ex lsolve(const ex& eqns, const ex& symbols, unsigned options = solve_algo::automatic); /** Find a real root of real-valued function f(x) numerically within a given diff --git a/ginac/inifcns_exp.cpp b/ginac/inifcns_exp.cpp index a464400c..3e286d2d 100644 --- a/ginac/inifcns_exp.cpp +++ b/ginac/inifcns_exp.cpp @@ -1,7 +1,6 @@ /** @file inifcns_exp.cpp * - * Implementation of TODO - * functions. */ + * Implementation of GiNaC's initially known exponential and related functions. */ /* * GiNaC Copyright (C) 1999-2006 Johannes Gutenberg University Mainz, Germany @@ -41,15 +40,15 @@ namespace GiNaC { -GINAC_IMPLEMENT_FUNCTION_OPT(eta_function, - print_func(&eta_function::do_print_latex)) +GINAC_IMPLEMENT_FUNCTION_OPT(eta, + print_func(&eta::do_print_latex)) -ex eta_function::conjugate() const +ex eta::conjugate() const { return -eta(seq[0], seq[1]); } -ex eta_function::eval(int level) const +ex eta::eval(int level) const { // Canonicalize argument order according to the symmetry properties exvector v = seq; @@ -80,14 +79,14 @@ ex eta_function::eval(int level) const cut -= 4; if (nxy.is_real() && nxy.is_negative()) cut += 4; - return (I/4)*Pi*((csgn(-imag(nx))+1)*(csgn(-imag(ny))+1)*(csgn(imag(nxy))+1)- - (csgn(imag(nx))+1)*(csgn(imag(ny))+1)*(csgn(-imag(nxy))+1)+cut); + return (I/4)*Pi*(((-imag(nx)).csgn()+1)*((-imag(ny)).csgn()+1)*((imag(nxy)).csgn()+1)- + ((imag(nx)).csgn()+1)*((imag(ny)).csgn()+1)*((-imag(nxy)).csgn()+1)+cut); } return this->hold(); } -ex eta_function::evalf(int level) const +ex eta::evalf(int level) const { const ex& x = seq[0]; const ex& y = seq[1]; @@ -107,14 +106,14 @@ ex eta_function::evalf(int level) const cut -= 4; if (nxy.is_real() && nxy.is_negative()) cut += 4; - return GiNaC::evalf(I/4*Pi)*((csgn(-imag(nx))+1)*(csgn(-imag(ny))+1)*(csgn(imag(nxy))+1)- - (csgn(imag(nx))+1)*(csgn(imag(ny))+1)*(csgn(-imag(nxy))+1)+cut); + return GiNaC::evalf(I/4*Pi)*(((-imag(nx)).csgn()+1)*((-imag(ny)).csgn()+1)*((imag(nxy)).csgn()+1)- + ((imag(nx)).csgn()+1)*((imag(ny)).csgn()+1)*((-imag(nxy)).csgn()+1)+cut); } return this->hold(); } -ex eta_function::series(const relational& rel, int order, unsigned options) const +ex eta::series(const relational& rel, int order, unsigned options) const { const ex& x = seq[0]; const ex& y = seq[1]; @@ -123,16 +122,16 @@ ex eta_function::series(const relational& rel, int order, unsigned options) cons if ((x_pt.info(info_flags::numeric) && x_pt.info(info_flags::negative)) || (y_pt.info(info_flags::numeric) && y_pt.info(info_flags::negative)) || ((x_pt*y_pt).info(info_flags::numeric) && (x_pt*y_pt).info(info_flags::negative))) - throw (std::domain_error("eta_series(): on discontinuity")); + throw (std::domain_error("eta::series(): on discontinuity")); epvector seq; seq.push_back(expair(eta(x_pt,y_pt), _ex0)); return pseries(rel, seq); } -void eta_function::do_print_latex(const print_context& c, unsigned level) const +void eta::do_print_latex(const print_context& c, unsigned level) const { c.s << "\\eta"; - inherited::do_print(c,level); + exprseq::do_print(c,level); } ////////// @@ -140,8 +139,10 @@ void eta_function::do_print_latex(const print_context& c, unsigned level) const ////////// GINAC_IMPLEMENT_FUNCTION_OPT(exp_function, + print_func(&function::do_print_cmath). print_func(&exp_function::do_print_csrc_float). - print_func(&exp_function::do_print_latex)) + print_func(&exp_function::do_print_latex). + print_func(&function::do_print_tree)) ex exp_function::eval(int level) const { @@ -172,7 +173,7 @@ ex exp_function::eval(int level) const // exp(float) -> float if (x.info(info_flags::numeric) && !x.info(info_flags::crational)) - return exp(ex_to(x)); + return numeric(cln::exp(ex_to(x).to_cl_N())); return this->hold(); } @@ -181,7 +182,7 @@ ex exp_function::evalf(int level) const { const ex& x = seq[0]; if (is_exactly_a(x)) - return exp(ex_to(x)); + return numeric(cln::exp(ex_to(x).to_cl_N())); return this->hold(); } @@ -202,7 +203,7 @@ void exp_function::do_print_csrc_float(const print_context& c, unsigned level) c void exp_function::do_print_latex(const print_context& c, unsigned level) const { c.s << "\\exp"; - inherited::do_print(c,level); + exprseq::do_print(c,level); } ////////// @@ -210,8 +211,10 @@ void exp_function::do_print_latex(const print_context& c, unsigned level) const ////////// GINAC_IMPLEMENT_FUNCTION_OPT(log_function, + print_func(&function::do_print_cmath). print_func(&log_function::do_print_csrc_float). - print_func(&log_function::do_print_latex)) + print_func(&log_function::do_print_latex). + print_func(&function::do_print_tree)) ex log_function::eval(int level) const { @@ -230,7 +233,7 @@ ex log_function::eval(int level) const // log(float) -> float if (!x.info(info_flags::crational)) - return log(ex_to(x)); + return numeric(cln::log(ex_to(x).to_cl_N())); } // log(exp(t)) -> t (if -Pi < t.imag() <= Pi): @@ -247,9 +250,13 @@ ex log_function::eval(int level) const ex log_function::evalf(int level) const { const ex& x = seq[0]; - if (is_exactly_a(x)) - return log(ex_to(x)); - + if (is_exactly_a(x)) { + const numeric& xn = ex_to(x); + if (xn.is_zero()) + throw pole_error("log(): logarithmic pole",0); + return numeric(cln::log(xn.to_cl_N())); + } + return this->hold(); } @@ -358,22 +365,22 @@ void log_function::do_print_csrc_float(const print_context& c, unsigned level) c void log_function::do_print_latex(const print_context& c, unsigned level) const { c.s << "\\log"; - inherited::do_print(c,level); + exprseq::do_print(c,level); } ////////// // Logarithm of Gamma function ////////// -GINAC_IMPLEMENT_FUNCTION_OPT(lgamma_function, - print_func(&lgamma_function::do_print_latex)) +GINAC_IMPLEMENT_FUNCTION_OPT(lgamma, + print_func(&lgamma::do_print_latex)) /** Evaluation of lgamma(x), the natural logarithm of the Gamma function. * Knows about integer arguments and that's it. Somebody ought to provide * some good numerical evaluation some day... * * @exception GiNaC::pole_error("lgamma_eval(): logarithmic pole",0) */ -ex lgamma_function::eval(int level) const +ex lgamma::eval(int level) const { const ex& x = seq[0]; if (x.info(info_flags::numeric)) { @@ -391,19 +398,12 @@ ex lgamma_function::eval(int level) const return this->hold(); } -ex lgamma_function::evalf(int level) const +ex lgamma::evalf(int level) const { - const ex& x = seq[0]; - if (is_exactly_a(x)) { - try { - return lgamma(ex_to(x)); - } catch (const dunno& e) { } - } - return this->hold(); } -ex lgamma_function::pderivative(unsigned deriv_param) const +ex lgamma::pderivative(unsigned deriv_param) const { const ex& x = seq[0]; GINAC_ASSERT(deriv_param==0); @@ -412,7 +412,7 @@ ex lgamma_function::pderivative(unsigned deriv_param) const return psi(x); } -ex lgamma_function::series(const relational& rel, int order, unsigned options) const +ex lgamma::series(const relational& rel, int order, unsigned options) const { const ex& arg = seq[0]; // method: @@ -434,25 +434,25 @@ ex lgamma_function::series(const relational& rel, int order, unsigned options) c return (lgamma(arg+m+_ex1)-recur).series(rel, order, options); } -void lgamma_function::do_print_latex(const print_context& c, unsigned level) const +void lgamma::do_print_latex(const print_context& c, unsigned level) const { c.s << "\\log \\Gamma"; - inherited::do_print(c,level); + exprseq::do_print(c,level); } ////////// // true Gamma function ////////// -GINAC_IMPLEMENT_FUNCTION_OPT(tgamma_function, - print_func(&tgamma_function::do_print_latex)) +GINAC_IMPLEMENT_FUNCTION_OPT(tgamma, + print_func(&tgamma::do_print_latex)) /** Evaluation of tgamma(x), the true Gamma function. Knows about integer * arguments, half-integer arguments and that's it. Somebody ought to provide * some good numerical evaluation some day... * * @exception pole_error("tgamma_eval(): simple pole",0) */ -ex tgamma_function::eval(int level) const +ex tgamma::eval(int level) const { const ex& x = seq[0]; if (x.info(info_flags::numeric)) { @@ -461,7 +461,7 @@ ex tgamma_function::eval(int level) const if (two_x.is_even()) { // tgamma(n) -> (n-1)! for postitive n if (two_x.is_positive()) { - return factorial(ex_to(x).sub(*_num1_p)); + return factorial::eval_numeric(ex_to(x).sub(*_num1_p)); } else { throw (pole_error("tgamma_eval(): simple pole",1)); } @@ -476,7 +476,7 @@ ex tgamma_function::eval(int level) const } else { // trap negative x==(-n+1/2) // tgamma(-n+1/2) -> Pi^(1/2)*(-2)^n/(1*3*..*(2*n-1)) - const numeric n = abs(ex_to(x).sub(*_num1_2_p)); + const numeric n = abs_function::eval_numeric(ex_to(x).sub(*_num1_2_p)); return (pow(*_num_2_p, n).div(doublefactorial(n.mul(*_num2_p).sub(*_num1_p))))*sqrt(Pi); } } @@ -486,19 +486,12 @@ ex tgamma_function::eval(int level) const return this->hold(); } -ex tgamma_function::evalf(int level) const +ex tgamma::evalf(int level) const { - const ex& x = seq[0]; - if (is_exactly_a(x)) { - try { - return tgamma(ex_to(x)); - } catch (const dunno &e) { } - } - return this->hold(); } -ex tgamma_function::pderivative(unsigned deriv_param) const +ex tgamma::pderivative(unsigned deriv_param) const { const ex& x = seq[0]; GINAC_ASSERT(deriv_param==0); @@ -507,7 +500,7 @@ ex tgamma_function::pderivative(unsigned deriv_param) const return psi(x)*tgamma(x); } -ex tgamma_function::series(const relational& rel, int order, unsigned options) const +ex tgamma::series(const relational& rel, int order, unsigned options) const { const ex& arg = seq[0]; // method: @@ -530,20 +523,20 @@ ex tgamma_function::series(const relational& rel, int order, unsigned options) c return (tgamma(arg+m+_ex1)/ser_denom).series(rel, order, options); } -void tgamma_function::do_print_latex(const print_context& c, unsigned level) const +void tgamma::do_print_latex(const print_context& c, unsigned level) const { c.s << "\\Gamma"; - inherited::do_print(c,level); + exprseq::do_print(c,level); } ////////// // beta-function ////////// -GINAC_IMPLEMENT_FUNCTION_OPT(beta_function, - print_func(&beta_function::do_print_latex)) +GINAC_IMPLEMENT_FUNCTION_OPT(beta, + print_func(&beta::do_print_latex)) -ex beta_function::eval(int level) const +ex beta::eval(int level) const { // Canonicalize argument order according to the symmetry properties exvector v = seq; @@ -595,20 +588,12 @@ ex beta_function::eval(int level) const return this->hold(); } -ex beta_function::evalf(int level) const +ex beta::evalf(int level) const { - const ex& x = seq[0]; - const ex& y = seq[1]; - if (is_exactly_a(x) && is_exactly_a(y)) { - try { - return tgamma(ex_to(x))*tgamma(ex_to(y))/tgamma(ex_to(x+y)); - } catch (const dunno &e) { } - } - return this->hold(); } -ex beta_function::pderivative(unsigned deriv_param) const +ex beta::pderivative(unsigned deriv_param) const { const ex& x = seq[0]; @@ -625,7 +610,7 @@ ex beta_function::pderivative(unsigned deriv_param) const return retval; } -ex beta_function::series(const relational& rel, int order, unsigned options) const +ex beta::series(const relational& rel, int order, unsigned options) const { const ex& arg1 = seq[0]; const ex& arg2 = seq[1]; @@ -660,22 +645,22 @@ ex beta_function::series(const relational& rel, int order, unsigned options) con return (arg1_ser*arg2_ser/arg1arg2_ser).series(rel, order, options).expand(); } -void beta_function::do_print_latex(const print_context& c, unsigned level) const +void beta::do_print_latex(const print_context& c, unsigned level) const { c.s << "\\mbox{B}"; - inherited::do_print(c,level); + exprseq::do_print(c,level); } ////////// // Psi-function (aka digamma-function) ////////// -GINAC_IMPLEMENT_FUNCTION_OPT(psi1_function, - print_func(&psi1_function::do_print_latex)) +GINAC_IMPLEMENT_FUNCTION_OPT(psi1, + print_func(&psi1::do_print_latex)) /** Evaluation of digamma-function psi(x). * Somebody ought to provide some good numerical evaluation some day... */ -ex psi1_function::eval(int level) const +ex psi1::eval(int level) const { const ex& x = seq[0]; if (x.info(info_flags::numeric)) { @@ -719,7 +704,7 @@ ex psi1_function::eval(int level) const return this->hold(); } -ex psi1_function::evalf(int level) const +ex psi1::evalf(int level) const { const ex& x = seq[0]; if (is_exactly_a(x)) { @@ -731,7 +716,7 @@ ex psi1_function::evalf(int level) const return this->hold(); } -ex psi1_function::pderivative(unsigned deriv_param) const +ex psi1::pderivative(unsigned deriv_param) const { const ex& x = seq[0]; GINAC_ASSERT(deriv_param==0); @@ -740,7 +725,7 @@ ex psi1_function::pderivative(unsigned deriv_param) const return psi(_ex1, x); } -ex psi1_function::series(const relational& rel, int order, unsigned options) const +ex psi1::series(const relational& rel, int order, unsigned options) const { const ex& arg = seq[0]; // method: @@ -762,22 +747,22 @@ ex psi1_function::series(const relational& rel, int order, unsigned options) con return (psi(arg+m+_ex1)-recur).series(rel, order, options); } -void psi1_function::do_print_latex(const print_context& c, unsigned level) const +void psi1::do_print_latex(const print_context& c, unsigned level) const { c.s << "\\psi"; - inherited::do_print(c,level); + exprseq::do_print(c,level); } ////////// // Psi-functions (aka polygamma-functions) psi(0,x)==psi(x) ////////// -GINAC_IMPLEMENT_FUNCTION_OPT(psi2_function, - print_func(&psi2_function::do_print_latex)) +GINAC_IMPLEMENT_FUNCTION_OPT(psi2, + print_func(&psi2::do_print_latex)) /** Evaluation of polygamma-function psi(n,x). * Somebody ought to provide some good numerical evaluation some day... */ -ex psi2_function::eval(int eval) const +ex psi2::eval(int eval) const { const ex& n = seq[0]; const ex& x = seq[1]; @@ -795,7 +780,7 @@ ex psi2_function::eval(int eval) const // integer case if (nx.is_equal(*_num1_p)) // use psi(n,1) == (-)^(n+1) * n! * zeta(n+1) - return pow(*_num_1_p,nn+(*_num1_p))*factorial(nn)*zeta_function(nn+(*_num1_p)); + return pow(*_num_1_p,nn+(*_num1_p))*factorial::eval_numeric(nn)*zeta_function(nn+(*_num1_p)); if (nx.is_positive()) { // use the recurrence relation // psi(n,m) == psi(n,m+1) - (-)^n * n! / m^(n+1) @@ -805,7 +790,7 @@ ex psi2_function::eval(int eval) const numeric recur = 0; for (numeric p = 1; phold(); } -ex psi2_function::evalf(int eval) const +ex psi2::evalf(int eval) const { const ex& n = seq[0]; const ex& x = seq[1]; @@ -855,7 +840,7 @@ ex psi2_function::evalf(int eval) const return this->hold(); } -ex psi2_function::pderivative(unsigned deriv_param) const +ex psi2::pderivative(unsigned deriv_param) const { const ex& n = seq[0]; const ex& x = seq[1]; @@ -869,7 +854,7 @@ ex psi2_function::pderivative(unsigned deriv_param) const return psi(n+_ex1, x); } -ex psi2_function::series(const relational& rel, int order, unsigned options) const +ex psi2::series(const relational& rel, int order, unsigned options) const { const ex& n = seq[0]; const ex& arg = seq[1]; @@ -894,10 +879,10 @@ ex psi2_function::series(const relational& rel, int order, unsigned options) con return (psi(n, arg+m+_ex1)-recur).series(rel, order, options); } -void psi2_function::do_print_latex(const print_context& c, unsigned level) const +void psi2::do_print_latex(const print_context& c, unsigned level) const { c.s << "\\psi"; - inherited::do_print(c,level); + exprseq::do_print(c,level); } } // namespace GiNaC diff --git a/ginac/inifcns_exp.h b/ginac/inifcns_exp.h index b52646d8..c9ce3725 100644 --- a/ginac/inifcns_exp.h +++ b/ginac/inifcns_exp.h @@ -1,6 +1,6 @@ /** @file inifcns_exp.h * - * Interface to GiNaC's TODO */ + * Interface to GiNaC's initially known exponential and related functions. */ /* * GiNaC Copyright (C) 1999-2006 Johannes Gutenberg University Mainz, Germany @@ -35,9 +35,9 @@ namespace GiNaC { // This function is closely related to the unwinding number K, sometimes found // in modern literature: K(z) == (z-log(exp(z)))/(2*Pi*I). ////////// -class eta_function : public function +class eta : public function { - GINAC_DECLARE_FUNCTION_2P(eta_function) + GINAC_DECLARE_FUNCTION_2P(eta) public: virtual ex conjugate() const; virtual ex eval(int level = 0) const; @@ -47,8 +47,6 @@ protected: void do_print_latex(const print_context& c, unsigned level) const; }; -template inline eta_function eta(const T1& x1, const T2& x2) { return eta_function(x1, x2); } - /** Exponential function. */ class exp_function : public function { @@ -85,9 +83,9 @@ inline log_function log(double x1) { return log_function(x1); } inline log_function log(float x1) { return log_function(x1); } /** Log-Gamma-function. */ -class lgamma_function : public function +class lgamma : public function { - GINAC_DECLARE_FUNCTION_1P(lgamma_function) + GINAC_DECLARE_FUNCTION_1P(lgamma) public: virtual ex eval(int level = 0) const; virtual ex evalf(int level = 0) const; @@ -97,12 +95,10 @@ protected: void do_print_latex(const print_context& c, unsigned level) const; }; -template inline lgamma_function lgamma(const T1& x1) { return lgamma_function(x1); } - /** Gamma-function. */ -class tgamma_function : public function +class tgamma : public function { - GINAC_DECLARE_FUNCTION_1P(tgamma_function) + GINAC_DECLARE_FUNCTION_1P(tgamma) public: virtual ex eval(int level = 0) const; virtual ex evalf(int level = 0) const; @@ -112,12 +108,10 @@ protected: void do_print_latex(const print_context& c, unsigned level) const; }; -template inline tgamma_function tgamma(const T1& x1) { return tgamma_function(x1); } - /** Beta-function. */ -class beta_function : public function +class beta : public function { - GINAC_DECLARE_FUNCTION_2P(beta_function) + GINAC_DECLARE_FUNCTION_2P(beta) public: virtual ex eval(int level = 0) const; virtual ex evalf(int level = 0) const; @@ -127,12 +121,10 @@ protected: void do_print_latex(const print_context& c, unsigned level) const; }; -template inline beta_function beta(const T1& x1, const T2& x2) { return beta_function(x1, x2); } - /** Psi-function (aka digamma-function). */ -class psi1_function : public function +class psi1 : public function { - GINAC_DECLARE_FUNCTION_1P(psi1_function) + GINAC_DECLARE_FUNCTION_1P(psi1) public: virtual ex eval(int level = 0) const; virtual ex evalf(int level = 0) const; @@ -142,12 +134,12 @@ protected: void do_print_latex(const print_context& c, unsigned level) const; }; -template inline psi1_function psi(const T1& x1) { return psi1_function(x1); } +template inline psi1 psi(const T1& x1) { return psi1(x1); } /** Derivatives of Psi-function (aka polygamma-functions). */ -class psi2_function : public function +class psi2 : public function { - GINAC_DECLARE_FUNCTION_2P(psi2_function) + GINAC_DECLARE_FUNCTION_2P(psi2) public: virtual ex eval(int level = 0) const; virtual ex evalf(int level = 0) const; @@ -157,7 +149,7 @@ protected: void do_print_latex(const print_context& c, unsigned level) const; }; -template inline psi2_function psi(const T1& x1, const T2& x2) { return psi2_function(x1, x2); } +template inline psi2 psi(const T1& x1, const T2& x2) { return psi2(x1, x2); } } // namespace GiNaC diff --git a/ginac/inifcns_polylog.cpp b/ginac/inifcns_polylog.cpp index 1fe9cd2f..c3cddc35 100644 --- a/ginac/inifcns_polylog.cpp +++ b/ginac/inifcns_polylog.cpp @@ -1,6 +1,6 @@ /** @file inifcns_polylog.cpp * - * Implementation of some special functions that have a representation as nested sums. TODO + * Implementation of GiNaC's initially known polylogarithmic functions. * * The functions are: * classical polylogarithm Li(n,x) @@ -71,7 +71,6 @@ #include #include - #include "inifcns.h" #include "inifcns_exp.h" #include "add.h" @@ -401,7 +400,7 @@ numeric Lin_numeric(int n, const numeric& x) // [Kol] (2.22) return -(1-cln::expt(cln::cl_I(2),1-n)) * cln::zeta(n); } - if (abs(x.real()) < 0.4 && abs(abs(x)-1) < 0.01) { + if (abs_function::eval_numeric(x.real()) < 0.4 && abs_function::eval_numeric(abs_function::eval_numeric(x)-1) < 0.01) { cln::cl_N x_ = ex_to(x).to_cl_N(); cln::cl_N result = -cln::expt(cln::log(x_), n-1) * cln::log(1-x_) / cln::factorial(n-1); for (int j=0; j G({1};y)^k / k! if (all_ones && a.size() > 1) { - return pow(G_eval1(a.front(),scale), count_ones) / factorial(count_ones); + return pow(G_eval1(a.front(),scale), count_ones) / factorial::eval_numeric(count_ones); } // G({0,...,0};y) -> log(y)^k / k! if (all_zero) { - return pow(log(gsyms[std::abs(scale)]), a.size()) / factorial(a.size()); + return pow(log(gsyms[std::abs(scale)]), a.size()) / factorial::eval_numeric(a.size()); } // no special cases anymore -> convert it into Li @@ -1178,7 +1177,10 @@ ex mLi_numeric(const lst& m, const lst& x) // ////////////////////////////////////////////////////////////////////// -GINAC_IMPLEMENT_FUNCTION(G_function) +GINAC_IMPLEMENT_FUNCTION_OPT(G_function, + print_func(&function::do_print_cmath). + print_func(&function::do_print_cmath_latex). + print_func(&function::do_print_tree)) ex G_function::eval(int level) const { @@ -1213,7 +1215,7 @@ ex G_function::eval(int level) const s.append(+1); } if (all_zero) { - return pow(log(y), x.nops()) / factorial(x.nops()); + return pow(log(y), x.nops()) / factorial::eval_numeric(x.nops()); } if (!y.info(info_flags::crational)) { crational = false; @@ -1264,7 +1266,7 @@ ex G_function::eval(int level) const } } if (all_zero) { - return pow(log(y), x.nops()) / factorial(x.nops()); + return pow(log(y), x.nops()) / factorial::eval_numeric(x.nops()); } if (!y.info(info_flags::crational)) { crational = false; @@ -1304,7 +1306,7 @@ ex G_function::evalf(int level) const s.append(+1); } if (all_zero) { - return pow(log(y), x.nops()) / factorial(x.nops()); + return pow(log(y), x.nops()) / factorial::eval_numeric(x.nops()); } return G_numeric(x, s, y); } else { @@ -1345,7 +1347,7 @@ ex G_function::evalf(int level) const } } if (all_zero) { - return pow(log(y), x.nops()) / factorial(x.nops()); + return pow(log(y), x.nops()) / factorial::eval_numeric(x.nops()); } return G_numeric(x, sn, y); } @@ -1360,7 +1362,9 @@ ex G_function::evalf(int level) const ////////////////////////////////////////////////////////////////////// GINAC_IMPLEMENT_FUNCTION_OPT(Li_function, - print_func(&Li_function::do_print_latex)) + print_func(&function::do_print_cmath). + print_func(&Li_function::do_print_latex). + print_func(&function::do_print_tree)) ex Li_function::eval(int level) const { @@ -1552,7 +1556,7 @@ ex Li_function::series(const relational& rel, int order, unsigned options) const // method: // This is the branch cut: assemble the primitive series manually // and then add the corresponding complex step function. - const symbol &s = ex_to(rel.lhs()); + const symbol& s = ex_to(rel.lhs()); const ex point = rel.rhs(); const symbol foo; epvector seq; @@ -2001,7 +2005,9 @@ numeric S_num(int n, int p, const numeric& x) ////////////////////////////////////////////////////////////////////// GINAC_IMPLEMENT_FUNCTION_OPT(S_function, - print_func(&S_function::do_print_latex)) + print_func(&function::do_print_cmath). + print_func(&S_function::do_print_latex). + print_func(&function::do_print_tree)) ex S_function::eval(int level) const { @@ -2301,7 +2307,7 @@ struct map_trafo_H_reduce_trailing_zeros : public map_function it++; } if (it == parameter.end()) { - return pow(log(arg),parameter.nops()) / factorial(parameter.nops()); + return pow(log(arg),parameter.nops()) / factorial::eval_numeric(parameter.nops()); } // @@ -2731,7 +2737,7 @@ struct map_trafo_H_1overx : public map_function if (allthesame) { map_trafo_H_mult unify; return unify((pow(H(lst(-1),1/arg).hold() - H(lst(0),1/arg).hold(), parameter.nops()) - / factorial(parameter.nops())).expand()); + / factorial::eval_numeric(parameter.nops())).expand()); } } else { for (int i=1; i& m, const cln::cl_N& x) ////////////////////////////////////////////////////////////////////// GINAC_IMPLEMENT_FUNCTION_OPT(H_function, - print_func(&H_function::do_print_latex)) + print_func(&function::do_print_cmath). + print_func(&H_function::do_print_latex). + print_func(&function::do_print_tree)) ex H_function::eval(int level) const { @@ -3071,10 +3079,10 @@ ex H_function::eval(int level) const if (x == _ex0) { return this->hold(); } - return pow(log(x), m.nops()) / factorial(m.nops()); + return pow(log(x), m.nops()) / factorial::eval_numeric(m.nops()); } else { // all (minus) one - return pow(-pos1*log(1-pos1*x), m.nops()) / factorial(m.nops()); + return pow(-pos1*log(1-pos1*x), m.nops()) / factorial::eval_numeric(m.nops()); } } else if ((step == 1) && (pos1 == _ex0)){ // convertible to S @@ -3662,7 +3670,9 @@ cln::cl_N zeta_do_Hoelder_convolution(const std::vector& m_, const std::vec ////////////////////////////////////////////////////////////////////// GINAC_IMPLEMENT_FUNCTION_OPT(zeta_function, - print_func(&zeta_function::do_print_latex)) + print_func(&function::do_print_cmath). + print_func(&zeta_function::do_print_latex). + print_func(&function::do_print_tree)) ex zeta_function::eval(int level) const { @@ -3690,7 +3700,7 @@ ex zeta_function::eval(int level) const if (y.info(info_flags::odd)) { return this->hold(); } else { - return abs(bernoulli(y)) * pow(Pi, y) * pow(*_num2_p, y-(*_num1_p)) / factorial(y); + return abs_function::eval_numeric(bernoulli(y)) * pow(Pi, y) * pow(*_num2_p, y-(*_num1_p)) / factorial::eval_numeric(y); } } else { if (y.info(info_flags::odd)) { @@ -3931,7 +3941,9 @@ void zeta_function::do_print_latex(const print_context& c, unsigned level) const ////////// GINAC_IMPLEMENT_FUNCTION_OPT(zetaderiv_function, - print_func(&zetaderiv_function::do_print_latex)) + print_func(&function::do_print_cmath). + print_func(&zetaderiv_function::do_print_latex). + print_func(&function::do_print_tree)) ex zetaderiv_function::eval(int level) const { diff --git a/ginac/inifcns_polylog.h b/ginac/inifcns_polylog.h index 2569a7a1..bcc84565 100644 --- a/ginac/inifcns_polylog.h +++ b/ginac/inifcns_polylog.h @@ -1,6 +1,6 @@ /** @file inifcns_polylog.h * - * Interface to GiNaC's TODO */ + * Interface to GiNaC's initially known polylogarithmic functions. */ /* * GiNaC Copyright (C) 1999-2006 Johannes Gutenberg University Mainz, Germany diff --git a/ginac/inifcns_trig.cpp b/ginac/inifcns_trig.cpp index 82dbf7e9..36572385 100644 --- a/ginac/inifcns_trig.cpp +++ b/ginac/inifcns_trig.cpp @@ -34,6 +34,7 @@ #include "pseries.h" #include "utils.h" +#include #include #include @@ -44,7 +45,9 @@ namespace GiNaC { //////////////////////////////////////////////////////////////////////////////// GINAC_IMPLEMENT_FUNCTION_OPT(sin_function, - print_func(&sin_function::do_print_latex)) + print_func(&function::do_print_cmath). + print_func(&function::do_print_cmath_latex). + print_func(&function::do_print_tree)) ex sin_function::eval(int level) const { @@ -97,7 +100,7 @@ ex sin_function::eval(int level) const // sin(float) -> float if (x.info(info_flags::numeric) && !x.info(info_flags::crational)) - return sin(ex_to(x)); + return numeric(cln::sin(ex_to(x).to_cl_N())); // sin() is odd if (x.info(info_flags::negative)) @@ -110,8 +113,8 @@ ex sin_function::evalf(int level) const { const ex& x = seq[0]; if (is_exactly_a(x)) - return sin(ex_to(x)); - + return numeric(cln::sin(ex_to(x).to_cl_N())); + return this->hold(); } @@ -122,18 +125,14 @@ ex sin_function::pderivative(unsigned deriv_param) const return cos(seq[0]); } -void sin_function::do_print_latex(const print_context& c, unsigned level) const -{ - c.s << "\\sin"; - inherited::do_print(c,level); -} - ////////// // cosine (trigonometric function) ////////// GINAC_IMPLEMENT_FUNCTION_OPT(cos_function, - print_func(&cos_function::do_print_latex)) + print_func(&function::do_print_cmath). + print_func(&function::do_print_cmath_latex). + print_func(&function::do_print_tree)) ex cos_function::eval(int level) const { @@ -185,7 +184,7 @@ ex cos_function::eval(int level) const // cos(float) -> float if (x.info(info_flags::numeric) && !x.info(info_flags::crational)) - return cos(ex_to(x)); + return numeric(cln::cos(ex_to(x).to_cl_N())); // cos() is even if (x.info(info_flags::negative)) @@ -198,7 +197,7 @@ ex cos_function::evalf(int level) const { const ex& x = seq[0]; if (is_exactly_a(x)) - return cos(ex_to(x)); + return numeric(cln::cos(ex_to(x).to_cl_N())); return this->hold(); } @@ -211,18 +210,14 @@ ex cos_function::pderivative(unsigned deriv_param) const return -sin(seq[0]); } -void cos_function::do_print_latex(const print_context& c, unsigned level) const -{ - c.s << "\\cos"; - inherited::do_print(c,level); -} - ////////// // tangent (trigonometric function) ////////// GINAC_IMPLEMENT_FUNCTION_OPT(tan_function, - print_func(&tan_function::do_print_latex)) + print_func(&function::do_print_cmath). + print_func(&function::do_print_cmath_latex). + print_func(&function::do_print_tree)) ex tan_function::eval(int level) const { @@ -272,7 +267,7 @@ ex tan_function::eval(int level) const // tan(float) -> float if (x.info(info_flags::numeric) && !x.info(info_flags::crational)) { - return tan(ex_to(x)); + return numeric(cln::tan(ex_to(x).to_cl_N())); } // tan() is odd @@ -287,7 +282,7 @@ ex tan_function::evalf(int level) const { const ex& x = seq[0]; if (is_exactly_a(x)) - return tan(ex_to(x)); + return numeric(cln::tan(ex_to(x).to_cl_N())); return this->hold(); } @@ -315,18 +310,14 @@ ex tan_function::series(const relational& rel, int order, unsigned options) cons return (sin(x)/cos(x)).series(rel, order, options); } -void tan_function::do_print_latex(const print_context& c, unsigned level) const -{ - c.s << "\\tan"; - inherited::do_print(c,level); -} - ////////// // inverse sine (arc sine) ////////// GINAC_IMPLEMENT_FUNCTION_OPT(asin_function, - print_func(&asin_function::do_print_latex)) + print_func(&function::do_print_cmath). + print_func(&asin_function::do_print_latex). + print_func(&function::do_print_tree)) ex asin_function::eval(int level) const { @@ -356,7 +347,7 @@ ex asin_function::eval(int level) const // asin(float) -> float if (!x.info(info_flags::crational)) - return asin(ex_to(x)); + return numeric(cln::asin(ex_to(x).to_cl_N())); // asin() is odd if (x.info(info_flags::negative)) @@ -370,7 +361,7 @@ ex asin_function::evalf(int level) const { const ex& x = seq[0]; if (is_exactly_a(x)) - return asin(ex_to(x)); + return numeric(cln::asin(ex_to(x).to_cl_N())); return this->hold(); } @@ -387,7 +378,7 @@ ex asin_function::pderivative(unsigned deriv_param) const void asin_function::do_print_latex(const print_context& c, unsigned level) const { c.s << "\\arcsin"; - inherited::do_print(c,level); + exprseq::do_print(c,level); } ////////// @@ -395,7 +386,9 @@ void asin_function::do_print_latex(const print_context& c, unsigned level) const ////////// GINAC_IMPLEMENT_FUNCTION_OPT(acos_function, - print_func(&acos_function::do_print_latex)) + print_func(&function::do_print_cmath). + print_func(&acos_function::do_print_latex). + print_func(&function::do_print_tree)) ex acos_function::eval(int level) const { @@ -425,7 +418,7 @@ ex acos_function::eval(int level) const // acos(float) -> float if (!x.info(info_flags::crational)) - return acos(ex_to(x)); + return numeric(cln::acos(ex_to(x).to_cl_N())); // acos(-x) -> Pi-acos(x) if (x.info(info_flags::negative)) @@ -439,7 +432,7 @@ ex acos_function::evalf(int level) const { const ex& x = seq[0]; if (is_exactly_a(x)) - return acos(ex_to(x)); + return numeric(cln::acos(ex_to(x).to_cl_N())); return this->hold(); } @@ -456,7 +449,7 @@ ex acos_function::pderivative(unsigned deriv_param) const void acos_function::do_print_latex(const print_context& c, unsigned level) const { c.s << "\\arccos"; - inherited::do_print(c,level); + exprseq::do_print(c,level); } ////////// @@ -464,7 +457,9 @@ void acos_function::do_print_latex(const print_context& c, unsigned level) const ////////// GINAC_IMPLEMENT_FUNCTION_OPT(atan_function, - print_func(&atan_function::do_print_latex)) + print_func(&function::do_print_cmath). + print_func(&atan_function::do_print_latex). + print_func(&function::do_print_tree)) ex atan_function::eval(int level) const { @@ -489,7 +484,7 @@ ex atan_function::eval(int level) const // atan(float) -> float if (!x.info(info_flags::crational)) - return atan(ex_to(x)); + return evalf(level); // atan() is odd if (x.info(info_flags::negative)) @@ -501,9 +496,13 @@ ex atan_function::eval(int level) const ex atan_function::evalf(int level) const { - const ex& x = seq[0]; - if (is_exactly_a(x)) - return atan(ex_to(x)); + const ex& x_ = seq[0]; + if (is_exactly_a(x_)) { + const numeric& x = ex_to(x_); + if (!x.is_real() && x.real().is_zero() && abs(x.imag()).is_equal(*_num1_p)) + throw pole_error("atan(): logarithmic pole", 0); + return numeric(cln::atan(ex_to(x).to_cl_N())); + } return this->hold(); } @@ -561,7 +560,7 @@ ex atan_function::series(const relational& rel, int order, unsigned options) con void atan_function::do_print_latex(const print_context& c, unsigned level) const { c.s << "\\arctan"; - inherited::do_print(c,level); + exprseq::do_print(c,level); } ////////// @@ -569,7 +568,9 @@ void atan_function::do_print_latex(const print_context& c, unsigned level) const ////////// GINAC_IMPLEMENT_FUNCTION_OPT(atan2_function, - print_func(&atan2_function::do_print_latex)) + print_func(&function::do_print_cmath). + print_func(&atan2_function::do_print_latex). + print_func(&function::do_print_tree)) ex atan2_function::eval(int level) const { @@ -628,7 +629,7 @@ ex atan2_function::eval(int level) const // atan(float, float) -> float if (!y.info(info_flags::crational) && !x.info(info_flags::crational)) - return atan(ex_to(y), ex_to(x)); + return evalf(level); // atan(real, real) -> atan(y/x) +/- Pi if (y.info(info_flags::real) && x.info(info_flags::real)) { @@ -646,11 +647,17 @@ ex atan2_function::eval(int level) const ex atan2_function::evalf(int level) const { - const ex& y = seq[0]; - const ex& x = seq[1]; - if (is_exactly_a(y) && is_exactly_a(x)) - return atan(ex_to(y), ex_to(x)); - + const ex& y_ = seq[0]; + const ex& x_ = seq[1]; + if (is_exactly_a(y_) && is_exactly_a(x_)) { + const numeric& y = ex_to(y_); + const numeric& x = ex_to(x_); + if (x.is_real() && y.is_real()) + return numeric(cln::atan(cln::the(x.to_cl_N()), cln::the(y.to_cl_N()))); + else + throw std::invalid_argument("atan(): complex argument"); + } + return this->hold(); } @@ -671,7 +678,7 @@ ex atan2_function::pderivative(unsigned deriv_param) const void atan2_function::do_print_latex(const print_context& c, unsigned level) const { c.s << "\\arctan_2"; - inherited::do_print(c,level); + exprseq::do_print(c,level); } ////////// @@ -679,7 +686,9 @@ void atan2_function::do_print_latex(const print_context& c, unsigned level) cons ////////// GINAC_IMPLEMENT_FUNCTION_OPT(sinh_function, - print_func(&sinh_function::do_print_latex)) + print_func(&function::do_print_cmath). + print_func(&function::do_print_cmath_latex). + print_func(&function::do_print_tree)) ex sinh_function::eval(int level) const { @@ -693,7 +702,7 @@ ex sinh_function::eval(int level) const // sinh(float) -> float if (!x.info(info_flags::crational)) - return sinh(ex_to(x)); + return numeric(cln::sinh(ex_to(x).to_cl_N())); // sinh() is odd if (x.info(info_flags::negative)) @@ -704,15 +713,16 @@ ex sinh_function::eval(int level) const ex_to(x/Pi).real().is_zero()) // sinh(I*x) -> I*sin(x) return I*sin(x/I); - const ex& t = x.op(0); - if (is_exactly_a(x)) { + if (is_exactly_a(x)) { // sinh(asinh(x)) -> x - return t; - } else if (is_exactly_a(x)) { + return x.op(0); + } else if (is_exactly_a(x)) { // sinh(acosh(x)) -> sqrt(x-1) * sqrt(x+1) + const ex& t = x.op(0); return sqrt(t-_ex1)*sqrt(t+_ex1); - } else if (is_exactly_a(x)) { + } else if (is_exactly_a(x)) { // sinh(atanh(x)) -> x/sqrt(1-x^2) + const ex& t = x.op(0); return t*power::power(_ex1-power::power(t,_ex2),_ex_1_2); } @@ -723,7 +733,7 @@ ex sinh_function::evalf(int level) const { const ex& x = seq[0]; if (is_exactly_a(x)) - return sinh(ex_to(x)); + return numeric(cln::sinh(ex_to(x).to_cl_N())); return this->hold(); } @@ -737,18 +747,14 @@ ex sinh_function::pderivative(unsigned deriv_param) const return cosh(x); } -void sinh_function::do_print_latex(const print_context& c, unsigned level) const -{ - c.s << "\\arcsin"; - inherited::do_print(c,level); -} - ////////// // hyperbolic cosine (trigonometric function) ////////// GINAC_IMPLEMENT_FUNCTION_OPT(cosh_function, - print_func(&cosh_function::do_print_latex)) + print_func(&function::do_print_cmath). + print_func(&function::do_print_cmath_latex). + print_func(&function::do_print_tree)) ex cosh_function::eval(int level) const { @@ -762,7 +768,7 @@ ex cosh_function::eval(int level) const // cosh(float) -> float if (!x.info(info_flags::crational)) - return cosh(ex_to(x)); + return numeric(cln::cosh(ex_to(x).to_cl_N())); // cosh() is even if (x.info(info_flags::negative)) @@ -773,13 +779,13 @@ ex cosh_function::eval(int level) const ex_to(x/Pi).real().is_zero()) // cosh(I*x) -> cos(x) return cos(x/I); - if (is_exactly_a(x)) { + if (is_exactly_a(x)) { // cosh(acosh(x)) -> x return x.op(0); - } else if (is_exactly_a(x)) { + } else if (is_exactly_a(x)) { // cosh(asinh(x)) -> sqrt(1+x^2) return sqrt(_ex1+power::power(x.op(0),_ex2)); - } else if (is_exactly_a(x)) { + } else if (is_exactly_a(x)) { // cosh(atanh(x)) -> 1/sqrt(1-x^2) return power::power(_ex1-power::power(x.op(0),_ex2),_ex_1_2); } @@ -792,7 +798,7 @@ ex cosh_function::evalf(int level) const const ex& x = seq[0]; if (is_exactly_a(x)) - return cosh(ex_to(x)); + return numeric(cln::cosh(ex_to(x).to_cl_N())); return this->hold(); } @@ -806,18 +812,14 @@ ex cosh_function::pderivative(unsigned deriv_param) const return sinh(x); } -void cosh_function::do_print_latex(const print_context& c, unsigned level) const -{ - c.s << "\\arccos"; - inherited::do_print(c,level); -} - ////////// // hyperbolic tangent (trigonometric function) ////////// GINAC_IMPLEMENT_FUNCTION_OPT(tanh_function, - print_func(&tanh_function::do_print_latex)) + print_func(&function::do_print_cmath). + print_func(&function::do_print_cmath_latex). + print_func(&function::do_print_tree)) ex tanh_function::eval(int level) const { @@ -831,7 +833,7 @@ ex tanh_function::eval(int level) const // tanh(float) -> float if (!x.info(info_flags::crational)) - return tanh(ex_to(x)); + return numeric(cln::tanh(ex_to(x).to_cl_N())); // tanh() is odd if (x.info(info_flags::negative)) @@ -842,14 +844,14 @@ ex tanh_function::eval(int level) const ex_to(x/Pi).real().is_zero()) // tanh(I*x) -> I*tan(x); return I*tan(x/I); - if (is_exactly_a(x)) { + if (is_exactly_a(x)) { // tanh(atanh(x)) -> x return x.op(0); - } else if (is_exactly_a(x)) { + } else if (is_exactly_a(x)) { // tanh(asinh(x)) -> x/sqrt(1+x^2) const ex& t = x.op(0); return t*power::power(_ex1+power::power(t,_ex2),_ex_1_2); - } else if (is_exactly_a(x)) { + } else if (is_exactly_a(x)) { // tanh(acosh(x)) -> sqrt(x-1)*sqrt(x+1)/x const ex& t = x.op(0); return sqrt(t-_ex1)*sqrt(t+_ex1)*power::power(t,_ex_1); @@ -862,7 +864,7 @@ ex tanh_function::evalf(int level) const { const ex& x = seq[0]; if (is_exactly_a(x)) - return tanh(ex_to(x)); + return numeric(cln::tanh(ex_to(x).to_cl_N())); return this->hold(); } @@ -890,20 +892,14 @@ ex tanh_function::series(const relational& rel, int order, unsigned options) con return (sinh(x)/cosh(x)).series(rel, order, options); } -void tanh_function::do_print_latex(const print_context& c, unsigned level) const -{ - c.s << "\\arctan"; - inherited::do_print(c,level); -} - ////////// // inverse hyperbolic sine (trigonometric function) ////////// -GINAC_IMPLEMENT_FUNCTION_OPT(asinh_function, - print_func(&asinh_function::do_print_latex)) +GINAC_IMPLEMENT_FUNCTION_OPT(asinh, + print_func(&asinh::do_print_latex)) -ex asinh_function::eval(int level) const +ex asinh::eval(int level) const { const ex& x = seq[0]; @@ -915,7 +911,7 @@ ex asinh_function::eval(int level) const // asinh(float) -> float if (!x.info(info_flags::crational)) - return asinh(ex_to(x)); + return numeric(cln::asinh(ex_to(x).to_cl_N())); // asinh() is odd if (x.info(info_flags::negative)) @@ -925,17 +921,17 @@ ex asinh_function::eval(int level) const return this->hold(); } -ex asinh_function::evalf(int level) const +ex asinh::evalf(int level) const { const ex& x = seq[0]; if (is_exactly_a(x)) - return asinh(ex_to(x)); + return numeric(cln::asinh(ex_to(x).to_cl_N())); return this->hold(); } -ex asinh_function::pderivative(unsigned deriv_param) const +ex asinh::pderivative(unsigned deriv_param) const { const ex& x = seq[0]; @@ -945,20 +941,20 @@ ex asinh_function::pderivative(unsigned deriv_param) const return power::power(_ex1+power::power(x,_ex2),_ex_1_2); } -void asinh_function::do_print_latex(const print_context& c, unsigned level) const +void asinh::do_print_latex(const print_context& c, unsigned level) const { - c.s << "\\arcsinh"; - inherited::do_print(c,level); + c.s << "\\mbox{arcsinh}"; + exprseq::do_print(c,level); } ////////// // inverse hyperbolic cosine (trigonometric function) ////////// -GINAC_IMPLEMENT_FUNCTION_OPT(acosh_function, - print_func(&acosh_function::do_print_latex)) +GINAC_IMPLEMENT_FUNCTION_OPT(acosh, + print_func(&acosh::do_print_latex)) -ex acosh_function::eval(int level) const +ex acosh::eval(int level) const { const ex& x = seq[0]; @@ -978,7 +974,7 @@ ex acosh_function::eval(int level) const // acosh(float) -> float if (!x.info(info_flags::crational)) - return acosh(ex_to(x)); + return numeric(cln::acosh(ex_to(x).to_cl_N())); // acosh(-x) -> Pi*I-acosh(x) if (x.info(info_flags::negative)) @@ -988,17 +984,17 @@ ex acosh_function::eval(int level) const return this->hold(); } -ex acosh_function::evalf(int level) const +ex acosh::evalf(int level) const { const ex& x = seq[0]; if (is_exactly_a(x)) - return acosh(ex_to(x)); + return numeric(cln::acosh(ex_to(x).to_cl_N())); return this->hold(); } -ex acosh_function::pderivative(unsigned deriv_param) const +ex acosh::pderivative(unsigned deriv_param) const { const ex& x = seq[0]; @@ -1008,20 +1004,20 @@ ex acosh_function::pderivative(unsigned deriv_param) const return power::power(x+_ex_1,_ex_1_2)*power::power(x+_ex1,_ex_1_2); } -void acosh_function::do_print_latex(const print_context& c, unsigned level) const +void acosh::do_print_latex(const print_context& c, unsigned level) const { - c.s << "\\arccosh"; - inherited::do_print(c,level); + c.s << "\\mbox{arccosh}"; + exprseq::do_print(c,level); } ////////// // inverse hyperbolic tangent (trigonometric function) ////////// -GINAC_IMPLEMENT_FUNCTION_OPT(atanh_function, - print_func(&atanh_function::do_print_latex)) +GINAC_IMPLEMENT_FUNCTION_OPT(atanh, + print_func(&atanh::do_print_latex)) -ex atanh_function::eval(int level) const +ex atanh::eval(int level) const { const ex& x = seq[0]; if (x.info(info_flags::numeric)) { @@ -1036,7 +1032,7 @@ ex atanh_function::eval(int level) const // atanh(float) -> float if (!x.info(info_flags::crational)) - return atanh(ex_to(x)); + return numeric(cln::atanh(ex_to(x).to_cl_N())); // atanh() is odd if (x.info(info_flags::negative)) @@ -1046,17 +1042,17 @@ ex atanh_function::eval(int level) const return this->hold(); } -ex atanh_function::evalf(int level) const +ex atanh::evalf(int level) const { const ex& x = seq[0]; if (is_exactly_a(x)) - return atanh(ex_to(x)); + return numeric(cln::atanh(ex_to(x).to_cl_N())); return this->hold(); } -ex atanh_function::pderivative(unsigned deriv_param) const +ex atanh::pderivative(unsigned deriv_param) const { const ex& x = seq[0]; GINAC_ASSERT(deriv_param==0); @@ -1065,7 +1061,7 @@ ex atanh_function::pderivative(unsigned deriv_param) const return power::power(_ex1-power::power(x,_ex2),_ex_1); } -ex atanh_function::series(const relational& rel, int order, unsigned options) const +ex atanh::series(const relational& rel, int order, unsigned options) const { const ex& arg = seq[0]; @@ -1107,10 +1103,10 @@ ex atanh_function::series(const relational& rel, int order, unsigned options) co return basic::series(rel, order, options); } -void atanh_function::do_print_latex(const print_context& c, unsigned level) const +void atanh::do_print_latex(const print_context& c, unsigned level) const { - c.s << "\\arctanh"; - inherited::do_print(c,level); + c.s << "\\mbox{arctanh}"; + exprseq::do_print(c,level); } } // namespace GiNaC diff --git a/ginac/inifcns_trig.h b/ginac/inifcns_trig.h index e5baf10c..01bd0ffb 100644 --- a/ginac/inifcns_trig.h +++ b/ginac/inifcns_trig.h @@ -37,8 +37,6 @@ public: virtual ex eval(int level = 0) const; virtual ex evalf(int level = 0) const; virtual ex pderivative(unsigned diff_param) const; -protected: - void do_print_latex(const print_context& c, unsigned level) const; }; template inline sin_function sin(const T1& x1) { return sin_function(x1); } @@ -54,8 +52,6 @@ public: virtual ex eval(int level = 0) const; virtual ex evalf(int level = 0) const; virtual ex pderivative(unsigned diff_param) const; -protected: - void do_print_latex(const print_context& c, unsigned level) const; }; template inline cos_function cos(const T1& x1) { return cos_function(x1); } @@ -72,8 +68,6 @@ public: virtual ex evalf(int level = 0) const; virtual ex pderivative(unsigned diff_param) const; virtual ex series(const relational & r, int order, unsigned options = 0) const; -protected: - void do_print_latex(const print_context& c, unsigned level) const; }; template inline tan_function tan(const T1& x1) { return tan_function(x1); } @@ -158,8 +152,6 @@ public: virtual ex eval(int level = 0) const; virtual ex evalf(int level = 0) const; virtual ex pderivative(unsigned diff_param) const; -protected: - void do_print_latex(const print_context& c, unsigned level) const; }; template inline sinh_function sinh(const T1& x1) { return sinh_function(x1); } @@ -175,8 +167,6 @@ public: virtual ex eval(int level = 0) const; virtual ex evalf(int level = 0) const; virtual ex pderivative(unsigned diff_param) const; -protected: - void do_print_latex(const print_context& c, unsigned level) const; }; template inline cosh_function cosh(const T1& x1) { return cosh_function(x1); } @@ -193,8 +183,6 @@ public: virtual ex evalf(int level = 0) const; virtual ex pderivative(unsigned diff_param) const; virtual ex series(const relational & r, int order, unsigned options = 0) const; -protected: - void do_print_latex(const print_context& c, unsigned level) const; }; template inline tanh_function tanh(const T1& x1) { return tanh_function(x1); } @@ -203,9 +191,9 @@ inline tanh_function tanh(float x1); /** Inverse hyperbolic Sine (area hyperbolic sine). */ -class asinh_function : public function +class asinh : public function { - GINAC_DECLARE_FUNCTION_1P(asinh_function) + GINAC_DECLARE_FUNCTION_1P(asinh) public: virtual ex eval(int level = 0) const; virtual ex evalf(int level = 0) const; @@ -214,15 +202,11 @@ protected: void do_print_latex(const print_context& c, unsigned level) const; }; -template inline asinh_function asinh(const T1& x1) { return asinh_function(x1); } -inline asinh_function asinh(double x1); -inline asinh_function asinh(float x1); - /** Inverse hyperbolic Cosine (area hyperbolic cosine). */ -class acosh_function : public function +class acosh : public function { - GINAC_DECLARE_FUNCTION_1P(acosh_function) + GINAC_DECLARE_FUNCTION_1P(acosh) public: virtual ex eval(int level = 0) const; virtual ex evalf(int level = 0) const; @@ -231,15 +215,11 @@ protected: void do_print_latex(const print_context& c, unsigned level) const; }; -template inline acosh_function acosh(const T1& x1) { return acosh_function(x1); } -inline acosh_function acosh(double x1); -inline acosh_function acosh(float x1); - /** Inverse hyperbolic Tangent (area hyperbolic tangent). */ -class atanh_function : public function +class atanh : public function { - GINAC_DECLARE_FUNCTION_1P(atanh_function) + GINAC_DECLARE_FUNCTION_1P(atanh) public: virtual ex eval(int level = 0) const; virtual ex evalf(int level = 0) const; @@ -249,10 +229,6 @@ protected: void do_print_latex(const print_context& c, unsigned level) const; }; -template inline atanh_function atanh(const T1& x1) { return atanh_function(x1); } -inline atanh_function atanh(double x1); -inline atanh_function atanh(float x1); - } // namespace GiNaC #endif // ifndef __GINAC_INIFCNS_TRIG_H__ diff --git a/ginac/integral.cpp b/ginac/integral.cpp index 2e81a695..3b0d95d2 100644 --- a/ginac/integral.cpp +++ b/ginac/integral.cpp @@ -297,7 +297,7 @@ ex adaptivesimpson(const ex & x, const ex & a_in, const ex & b_in, const ex & f, ex nu7 = svec[i]; int nu8 = lvec[i]; --i; - if (abs(ex_to(s1+s2-nu7)) <= nu6) + if (abs_function::eval_numeric(ex_to(s1+s2-nu7)) <= nu6) app+=(s1+s2); else { if (nu8>=integral::max_integration_level) diff --git a/ginac/matrix.cpp b/ginac/matrix.cpp index 83b088b6..3a3f38ce 100644 --- a/ginac/matrix.cpp +++ b/ginac/matrix.cpp @@ -34,6 +34,7 @@ #include "lst.h" #include "idx.h" #include "indexed.h" +#include "inifcns.h" #include "add.h" #include "power.h" #include "symbol.h" @@ -1484,11 +1485,11 @@ int matrix::pivot(unsigned ro, unsigned co, bool symbolic) // search largest element in column co beginning at row ro GINAC_ASSERT(is_exactly_a(this->m[k*col+co])); unsigned kmax = k+1; - numeric mmax = abs(ex_to(m[kmax*col+co])); + numeric mmax = abs_function::eval_numeric(ex_to(m[kmax*col+co])); while (kmax(this->m[kmax*col+co])); numeric tmp = ex_to(this->m[kmax*col+co]); - if (abs(tmp) > mmax) { + if (abs_function::eval_numeric(tmp) > mmax) { mmax = tmp; k = kmax; } diff --git a/ginac/normal.cpp b/ginac/normal.cpp index 29d26585..5ea3c196 100644 --- a/ginac/normal.cpp +++ b/ginac/normal.cpp @@ -316,7 +316,7 @@ numeric basic::integer_content() const numeric numeric::integer_content() const { - return abs(*this); + return abs_function::eval_numeric(*this); } numeric add::integer_content() const @@ -348,7 +348,7 @@ numeric mul::integer_content() const } #endif // def DO_GINAC_ASSERT GINAC_ASSERT(is_exactly_a(overall_coeff)); - return abs(ex_to(overall_coeff)); + return abs_function::eval_numeric(ex_to(overall_coeff)); } @@ -960,7 +960,7 @@ void ex::unitcontprim(const ex &x, ex &u, ex &c, ex &p) const if (is_exactly_a(*this)) { if (info(info_flags::negative)) { u = _ex_1; - c = abs(ex_to(*this)); + c = abs_function::eval_numeric(ex_to(*this)); } else { u = _ex1; c = *this; @@ -1093,7 +1093,7 @@ numeric basic::max_coefficient() const numeric numeric::max_coefficient() const { - return abs(*this); + return abs_function::eval_numeric(*this); } numeric add::max_coefficient() const @@ -1101,11 +1101,11 @@ numeric add::max_coefficient() const epvector::const_iterator it = seq.begin(); epvector::const_iterator itend = seq.end(); GINAC_ASSERT(is_exactly_a(overall_coeff)); - numeric cur_max = abs(ex_to(overall_coeff)); + numeric cur_max = abs_function::eval_numeric(ex_to(overall_coeff)); while (it != itend) { numeric a; GINAC_ASSERT(!is_exactly_a(it->rest)); - a = abs(ex_to(it->coeff)); + a = abs_function::eval_numeric(ex_to(it->coeff)); if (a > cur_max) cur_max = a; it++; @@ -1124,7 +1124,7 @@ numeric mul::max_coefficient() const } #endif // def DO_GINAC_ASSERT GINAC_ASSERT(is_exactly_a(overall_coeff)); - return abs(ex_to(overall_coeff)); + return abs_function::eval_numeric(ex_to(overall_coeff)); } diff --git a/ginac/numeric.cpp b/ginac/numeric.cpp index bb2762a2..9eecf9f7 100644 --- a/ginac/numeric.cpp +++ b/ginac/numeric.cpp @@ -7,7 +7,7 @@ * of special functions or implement the interface to the bignum package. */ /* - * GiNaC Copyright (C) 1999 Johannes Gutenberg University Mainz, Germany + * GiNaC Copyright (C) 1999-2006 Johannes Gutenberg University Mainz, Germany * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -21,341 +21,703 @@ * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ +#include "config.h" + #include #include +#include +#include +#include #include "numeric.h" #include "ex.h" -#include "config.h" -#include "debugmsg.h" - -// CLN should not pollute the global namespace, hence we include it here -// instead of in some header file where it would propagate to other parts: -#ifdef HAVE_CLN_CLN_H -#include -#else -#include -#endif +#include "inifcns.h" +#include "operators.h" +#include "archive.h" +#include "tostring.h" +#include "utils.h" + +// CLN should pollute the global namespace as little as possible. Hence, we +// include most of it here and include only the part needed for properly +// declaring cln::cl_number in numeric.h. This can only be safely done in +// namespaced versions of CLN, i.e. version > 1.1.0. Also, we only need a +// subset of CLN, so we don't include the complete but only the +// essential stuff: +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include namespace GiNaC { -// linker has no problems finding text symbols for numerator or denominator -//#define SANE_LINKER +GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(numeric, basic, + print_func(&numeric::do_print). + print_func(&numeric::do_print_latex). + print_func(&numeric::do_print_csrc). + print_func(&numeric::do_print_csrc_cl_N). + print_func(&numeric::do_print_tree). + print_func(&numeric::do_print_python_repr)) ////////// -// default constructor, destructor, copy constructor assignment -// operator and helpers +// default constructor ////////// -// public - /** default ctor. Numerically it initializes to an integer zero. */ -numeric::numeric() : basic(TINFO_numeric) +numeric::numeric() : basic(&numeric::tinfo_static) { - debugmsg("numeric default constructor", LOGLEVEL_CONSTRUCT); - value = new cl_N; - *value=cl_I(0); - calchash(); - setflag(status_flags::evaluated| - status_flags::hash_calculated); + value = cln::cl_I(0); + setflag(status_flags::evaluated | status_flags::expanded); } -numeric::~numeric() +////////// +// other constructors +////////// + +// public + +numeric::numeric(int i) : basic(&numeric::tinfo_static) { - debugmsg("numeric destructor" ,LOGLEVEL_DESTRUCT); - destroy(0); + // Not the whole int-range is available if we don't cast to long + // first. This is due to the behaviour of the cl_I-ctor, which + // emphasizes efficiency. However, if the integer is small enough + // we save space and dereferences by using an immediate type. + // (C.f. ) + if (i < (1L << (cl_value_len-1)) && i >= -(1L << (cl_value_len-1))) + value = cln::cl_I(i); + else + value = cln::cl_I(static_cast(i)); + setflag(status_flags::evaluated | status_flags::expanded); } -numeric::numeric(numeric const & other) + +numeric::numeric(unsigned int i) : basic(&numeric::tinfo_static) { - debugmsg("numeric copy constructor", LOGLEVEL_CONSTRUCT); - copy(other); + // Not the whole uint-range is available if we don't cast to ulong + // first. This is due to the behaviour of the cl_I-ctor, which + // emphasizes efficiency. However, if the integer is small enough + // we save space and dereferences by using an immediate type. + // (C.f. ) + if (i < (1UL << (cl_value_len-1))) + value = cln::cl_I(i); + else + value = cln::cl_I(static_cast(i)); + setflag(status_flags::evaluated | status_flags::expanded); } -numeric const & numeric::operator=(numeric const & other) + +numeric::numeric(long i) : basic(&numeric::tinfo_static) { - debugmsg("numeric operator=", LOGLEVEL_ASSIGNMENT); - if (this != &other) { - destroy(1); - copy(other); - } - return *this; + value = cln::cl_I(i); + setflag(status_flags::evaluated | status_flags::expanded); } -// protected -void numeric::copy(numeric const & other) +numeric::numeric(unsigned long i) : basic(&numeric::tinfo_static) { - basic::copy(other); - value = new cl_N(*other.value); + value = cln::cl_I(i); + setflag(status_flags::evaluated | status_flags::expanded); } -void numeric::destroy(bool call_parent) + +/** Constructor for rational numerics a/b. + * + * @exception overflow_error (division by zero) */ +numeric::numeric(long numer, long denom) : basic(&numeric::tinfo_static) +{ + if (!denom) + throw std::overflow_error("division by zero"); + value = cln::cl_I(numer) / cln::cl_I(denom); + setflag(status_flags::evaluated | status_flags::expanded); +} + + +numeric::numeric(double d) : basic(&numeric::tinfo_static) +{ + // We really want to explicitly use the type cl_LF instead of the + // more general cl_F, since that would give us a cl_DF only which + // will not be promoted to cl_LF if overflow occurs: + value = cln::cl_float(d, cln::default_float_format); + setflag(status_flags::evaluated | status_flags::expanded); +} + + +/** ctor from C-style string. It also accepts complex numbers in GiNaC + * notation like "2+5*I". */ +numeric::numeric(const char *s) : basic(&numeric::tinfo_static) +{ + cln::cl_N ctorval = 0; + // parse complex numbers (functional but not completely safe, unfortunately + // std::string does not understand regexpese): + // ss should represent a simple sum like 2+5*I + std::string ss = s; + std::string::size_type delim; + + // make this implementation safe by adding explicit sign + if (ss.at(0) != '+' && ss.at(0) != '-' && ss.at(0) != '#') + ss = '+' + ss; + + // We use 'E' as exponent marker in the output, but some people insist on + // writing 'e' at input, so let's substitute them right at the beginning: + while ((delim = ss.find("e"))!=std::string::npos) + ss.replace(delim,1,"E"); + + // main parser loop: + do { + // chop ss into terms from left to right + std::string term; + bool imaginary = false; + delim = ss.find_first_of(std::string("+-"),1); + // Do we have an exponent marker like "31.415E-1"? If so, hop on! + if (delim!=std::string::npos && ss.at(delim-1)=='E') + delim = ss.find_first_of(std::string("+-"),delim+1); + term = ss.substr(0,delim); + if (delim!=std::string::npos) + ss = ss.substr(delim); + // is the term imaginary? + if (term.find("I")!=std::string::npos) { + // erase 'I': + term.erase(term.find("I"),1); + // erase '*': + if (term.find("*")!=std::string::npos) + term.erase(term.find("*"),1); + // correct for trivial +/-I without explicit factor on I: + if (term.size()==1) + term += '1'; + imaginary = true; + } + if (term.find('.')!=std::string::npos || term.find('E')!=std::string::npos) { + // CLN's short type cl_SF is not very useful within the GiNaC + // framework where we are mainly interested in the arbitrary + // precision type cl_LF. Hence we go straight to the construction + // of generic floats. In order to create them we have to convert + // our own floating point notation used for output and construction + // from char * to CLN's generic notation: + // 3.14 --> 3.14e0_ + // 31.4E-1 --> 31.4e-1_ + // and s on. + // No exponent marker? Let's add a trivial one. + if (term.find("E")==std::string::npos) + term += "E0"; + // E to lower case + term = term.replace(term.find("E"),1,"e"); + // append _ to term + term += "_" + ToString((unsigned)Digits); + // construct float using cln::cl_F(const char *) ctor. + if (imaginary) + ctorval = ctorval + cln::complex(cln::cl_I(0),cln::cl_F(term.c_str())); + else + ctorval = ctorval + cln::cl_F(term.c_str()); + } else { + // this is not a floating point number... + if (imaginary) + ctorval = ctorval + cln::complex(cln::cl_I(0),cln::cl_R(term.c_str())); + else + ctorval = ctorval + cln::cl_R(term.c_str()); + } + } while (delim != std::string::npos); + value = ctorval; + setflag(status_flags::evaluated | status_flags::expanded); +} + + +/** Ctor from CLN types. This is for the initiated user or internal use + * only. */ +numeric::numeric(const cln::cl_N &z) : basic(&numeric::tinfo_static) { - delete value; - if (call_parent) basic::destroy(call_parent); + value = z; + setflag(status_flags::evaluated | status_flags::expanded); } + ////////// -// other constructors +// archiving ////////// -// public +numeric::numeric(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst) +{ + cln::cl_N ctorval = 0; + + // Read number as string + std::string str; + if (n.find_string("number", str)) { + std::istringstream s(str); + cln::cl_idecoded_float re, im; + char c; + s.get(c); + switch (c) { + case 'R': // Integer-decoded real number + s >> re.sign >> re.mantissa >> re.exponent; + ctorval = re.sign * re.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), re.exponent); + break; + case 'C': // Integer-decoded complex number + s >> re.sign >> re.mantissa >> re.exponent; + s >> im.sign >> im.mantissa >> im.exponent; + ctorval = cln::complex(re.sign * re.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), re.exponent), + im.sign * im.mantissa * cln::expt(cln::cl_float(2.0, cln::default_float_format), im.exponent)); + break; + default: // Ordinary number + s.putback(c); + s >> ctorval; + break; + } + } + value = ctorval; + setflag(status_flags::evaluated | status_flags::expanded); +} + +void numeric::archive(archive_node &n) const +{ + inherited::archive(n); + + // Write number as string + std::ostringstream s; + if (this->is_crational()) + s << value; + else { + // Non-rational numbers are written in an integer-decoded format + // to preserve the precision + if (this->is_real()) { + cln::cl_idecoded_float re = cln::integer_decode_float(cln::the(value)); + s << "R"; + s << re.sign << " " << re.mantissa << " " << re.exponent; + } else { + cln::cl_idecoded_float re = cln::integer_decode_float(cln::the(cln::realpart(cln::the(value)))); + cln::cl_idecoded_float im = cln::integer_decode_float(cln::the(cln::imagpart(cln::the(value)))); + s << "C"; + s << re.sign << " " << re.mantissa << " " << re.exponent << " "; + s << im.sign << " " << im.mantissa << " " << im.exponent; + } + } + n.add_string("number", s.str()); +} + +DEFAULT_UNARCHIVE(numeric) + +////////// +// functions overriding virtual functions from base classes +////////// -numeric::numeric(int i) : basic(TINFO_numeric) +/** Helper function to print a real number in a nicer way than is CLN's + * default. Instead of printing 42.0L0 this just prints 42.0 to ostream os + * and instead of 3.99168L7 it prints 3.99168E7. This is fine in GiNaC as + * long as it only uses cl_LF and no other floating point types that we might + * want to visibly distinguish from cl_LF. + * + * @see numeric::print() */ +static void print_real_number(const print_context & c, const cln::cl_R & x) +{ + cln::cl_print_flags ourflags; + if (cln::instanceof(x, cln::cl_RA_ring)) { + // case 1: integer or rational + if (cln::instanceof(x, cln::cl_I_ring) || + !is_a(c)) { + cln::print_real(c.s, ourflags, x); + } else { // rational output in LaTeX context + if (x < 0) + c.s << "-"; + c.s << "\\frac{"; + cln::print_real(c.s, ourflags, cln::abs(cln::numerator(cln::the(x)))); + c.s << "}{"; + cln::print_real(c.s, ourflags, cln::denominator(cln::the(x))); + c.s << '}'; + } + } else { + // case 2: float + // make CLN believe this number has default_float_format, so it prints + // 'E' as exponent marker instead of 'L': + ourflags.default_float_format = cln::float_format(cln::the(x)); + cln::print_real(c.s, ourflags, x); + } +} + +/** Helper function to print integer number in C++ source format. + * + * @see numeric::print() */ +static void print_integer_csrc(const print_context & c, const cln::cl_I & x) { - debugmsg("numeric constructor from int",LOGLEVEL_CONSTRUCT); - // Not the whole int-range is available if we don't cast to long - // first. This is due to the behaviour of the cl_I-ctor, which - // emphasizes efficiency: - value = new cl_I((long) i); - calchash(); - setflag(status_flags::evaluated| - status_flags::hash_calculated); + // Print small numbers in compact float format, but larger numbers in + // scientific format + const int max_cln_int = 536870911; // 2^29-1 + if (x >= cln::cl_I(-max_cln_int) && x <= cln::cl_I(max_cln_int)) + c.s << cln::cl_I_to_int(x) << ".0"; + else + c.s << cln::double_approx(x); } -numeric::numeric(unsigned int i) : basic(TINFO_numeric) +/** Helper function to print real number in C++ source format. + * + * @see numeric::print() */ +static void print_real_csrc(const print_context & c, const cln::cl_R & x) { - debugmsg("numeric constructor from uint",LOGLEVEL_CONSTRUCT); - // Not the whole uint-range is available if we don't cast to ulong - // first. This is due to the behaviour of the cl_I-ctor, which - // emphasizes efficiency: - value = new cl_I((unsigned long)i); - calchash(); - setflag(status_flags::evaluated| - status_flags::hash_calculated); + if (cln::instanceof(x, cln::cl_I_ring)) { + + // Integer number + print_integer_csrc(c, cln::the(x)); + + } else if (cln::instanceof(x, cln::cl_RA_ring)) { + + // Rational number + const cln::cl_I numer = cln::numerator(cln::the(x)); + const cln::cl_I denom = cln::denominator(cln::the(x)); + if (cln::plusp(x) > 0) { + c.s << "("; + print_integer_csrc(c, numer); + } else { + c.s << "-("; + print_integer_csrc(c, -numer); + } + c.s << "/"; + print_integer_csrc(c, denom); + c.s << ")"; + + } else { + + // Anything else + c.s << cln::double_approx(x); + } } -numeric::numeric(long i) : basic(TINFO_numeric) -{ - debugmsg("numeric constructor from long",LOGLEVEL_CONSTRUCT); - value = new cl_I(i); - calchash(); - setflag(status_flags::evaluated| - status_flags::hash_calculated); +/** Helper function to print real number in C++ source format using cl_N types. + * + * @see numeric::print() */ +static void print_real_cl_N(const print_context & c, const cln::cl_R & x) +{ + if (cln::instanceof(x, cln::cl_I_ring)) { + + // Integer number + c.s << "cln::cl_I(\""; + print_real_number(c, x); + c.s << "\")"; + + } else if (cln::instanceof(x, cln::cl_RA_ring)) { + + // Rational number + cln::cl_print_flags ourflags; + c.s << "cln::cl_RA(\""; + cln::print_rational(c.s, ourflags, cln::the(x)); + c.s << "\")"; + + } else { + + // Anything else + c.s << "cln::cl_F(\""; + print_real_number(c, cln::cl_float(1.0, cln::default_float_format) * x); + c.s << "_" << Digits << "\")"; + } +} + +void numeric::print_numeric(const print_context & c, const char *par_open, const char *par_close, const char *imag_sym, const char *mul_sym, unsigned level) const +{ + const cln::cl_R r = cln::realpart(value); + const cln::cl_R i = cln::imagpart(value); + + if (cln::zerop(i)) { + + // case 1, real: x or -x + if ((precedence() <= level) && (!this->is_nonneg_integer())) { + c.s << par_open; + print_real_number(c, r); + c.s << par_close; + } else { + print_real_number(c, r); + } + + } else { + if (cln::zerop(r)) { + + // case 2, imaginary: y*I or -y*I + if (i == 1) + c.s << imag_sym; + else { + if (precedence()<=level) + c.s << par_open; + if (i == -1) + c.s << "-" << imag_sym; + else { + print_real_number(c, i); + c.s << mul_sym << imag_sym; + } + if (precedence()<=level) + c.s << par_close; + } + + } else { + + // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I + if (precedence() <= level) + c.s << par_open; + print_real_number(c, r); + if (i < 0) { + if (i == -1) { + c.s << "-" << imag_sym; + } else { + print_real_number(c, i); + c.s << mul_sym << imag_sym; + } + } else { + if (i == 1) { + c.s << "+" << imag_sym; + } else { + c.s << "+"; + print_real_number(c, i); + c.s << mul_sym << imag_sym; + } + } + if (precedence() <= level) + c.s << par_close; + } + } } -numeric::numeric(unsigned long i) : basic(TINFO_numeric) +void numeric::do_print(const print_context & c, unsigned level) const { - debugmsg("numeric constructor from ulong",LOGLEVEL_CONSTRUCT); - value = new cl_I(i); - calchash(); - setflag(status_flags::evaluated| - status_flags::hash_calculated); + print_numeric(c, "(", ")", "I", "*", level); } -/** Ctor for rational numerics a/b. - * - * @exception overflow_error (division by zero) */ -numeric::numeric(long numer, long denom) : basic(TINFO_numeric) -{ - debugmsg("numeric constructor from long/long",LOGLEVEL_CONSTRUCT); - if (!denom) - throw (std::overflow_error("division by zero")); - value = new cl_I(numer); - *value = *value / cl_I(denom); - calchash(); - setflag(status_flags::evaluated| - status_flags::hash_calculated); -} - -numeric::numeric(double d) : basic(TINFO_numeric) -{ - debugmsg("numeric constructor from double",LOGLEVEL_CONSTRUCT); - // We really want to explicitly use the type cl_LF instead of the - // more general cl_F, since that would give us a cl_DF only which - // will not be promoted to cl_LF if overflow occurs: - value = new cl_N; - *value = cl_float(d, cl_default_float_format); - calchash(); - setflag(status_flags::evaluated| - status_flags::hash_calculated); -} - -numeric::numeric(char const *s) : basic(TINFO_numeric) -{ // MISSING: treatment of complex and ints and rationals. - debugmsg("numeric constructor from string",LOGLEVEL_CONSTRUCT); - if (strchr(s, '.')) - value = new cl_LF(s); - else - value = new cl_I(s); - calchash(); - setflag(status_flags::evaluated| - status_flags::hash_calculated); +void numeric::do_print_latex(const print_latex & c, unsigned level) const +{ + print_numeric(c, "{(", ")}", "i", " ", level); } -/** Ctor from CLN types. This is for the initiated user or internal use - * only. */ -numeric::numeric(cl_N const & z) : basic(TINFO_numeric) +void numeric::do_print_csrc(const print_csrc & c, unsigned level) const { - debugmsg("numeric constructor from cl_N", LOGLEVEL_CONSTRUCT); - value = new cl_N(z); - calchash(); - setflag(status_flags::evaluated| - status_flags::hash_calculated); + std::ios::fmtflags oldflags = c.s.flags(); + c.s.setf(std::ios::scientific); + int oldprec = c.s.precision(); + + // Set precision + if (is_a(c)) + c.s.precision(std::numeric_limits::digits10 + 1); + else + c.s.precision(std::numeric_limits::digits10 + 1); + + if (this->is_real()) { + + // Real number + print_real_csrc(c, cln::the(value)); + + } else { + + // Complex number + c.s << "std::complex<"; + if (is_a(c)) + c.s << "double>("; + else + c.s << "float>("; + + print_real_csrc(c, cln::realpart(value)); + c.s << ","; + print_real_csrc(c, cln::imagpart(value)); + c.s << ")"; + } + + c.s.flags(oldflags); + c.s.precision(oldprec); } -////////// -// functions overriding virtual functions from bases classes -////////// +void numeric::do_print_csrc_cl_N(const print_csrc_cl_N & c, unsigned level) const +{ + if (this->is_real()) { -// public + // Real number + print_real_cl_N(c, cln::the(value)); + + } else { + + // Complex number + c.s << "cln::complex("; + print_real_cl_N(c, cln::realpart(value)); + c.s << ","; + print_real_cl_N(c, cln::imagpart(value)); + c.s << ")"; + } +} + +void numeric::do_print_tree(const print_tree & c, unsigned level) const +{ + c.s << std::string(level, ' ') << value + << " (" << class_name() << ")" << " @" << this + << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec + << std::endl; +} -basic * numeric::duplicate() const -{ - debugmsg("numeric duplicate", LOGLEVEL_DUPLICATE); - return new numeric(*this); -} - -// The method printraw doesn't do much, it simply uses CLN's operator<<() for -// output, which is ugly but reliable. Examples: -// 2+2i -void numeric::printraw(ostream & os) const -{ - debugmsg("numeric printraw", LOGLEVEL_PRINT); - os << "numeric(" << *value << ")"; -} - -// The method print adds to the output so it blends more consistently together -// with the other routines and produces something compatible to Maple input. -void numeric::print(ostream & os, unsigned upper_precedence) const -{ - debugmsg("numeric print", LOGLEVEL_PRINT); - if (is_real()) { - // case 1, real: x or -x - if ((precedence<=upper_precedence) && (!is_pos_integer())) { - os << "(" << *value << ")"; - } else { - os << *value; - } - } else { - // case 2, imaginary: y*I or -y*I - if (realpart(*value) == 0) { - if ((precedence<=upper_precedence) && (imagpart(*value) < 0)) { - if (imagpart(*value) == -1) { - os << "(-I)"; - } else { - os << "(" << imagpart(*value) << "*I)"; - } - } else { - if (imagpart(*value) == 1) { - os << "I"; - } else { - if (imagpart (*value) == -1) { - os << "-I"; - } else { - os << imagpart(*value) << "*I"; - } - } - } - } else { - // case 3, complex: x+y*I or x-y*I or -x+y*I or -x-y*I - if (precedence <= upper_precedence) os << "("; - os << realpart(*value); - if (imagpart(*value) < 0) { - if (imagpart(*value) == -1) { - os << "-I"; - } else { - os << imagpart(*value) << "*I"; - } - } else { - if (imagpart(*value) == 1) { - os << "+I"; - } else { - os << "+" << imagpart(*value) << "*I"; - } - } - if (precedence <= upper_precedence) os << ")"; - } - } +void numeric::do_print_python_repr(const print_python_repr & c, unsigned level) const +{ + c.s << class_name() << "('"; + print_numeric(c, "(", ")", "I", "*", level); + c.s << "')"; } bool numeric::info(unsigned inf) const { - switch (inf) { - case info_flags::numeric: - case info_flags::polynomial: - case info_flags::rational_function: - return true; - case info_flags::real: - return is_real(); - case info_flags::rational: - case info_flags::rational_polynomial: - return is_rational(); - case info_flags::integer: - case info_flags::integer_polynomial: - return is_integer(); - case info_flags::positive: - return is_positive(); - case info_flags::negative: - return is_negative(); - case info_flags::nonnegative: - return compare(numZERO())>=0; - case info_flags::posint: - return is_pos_integer(); - case info_flags::negint: - return is_integer() && (compare(numZERO())<0); - case info_flags::nonnegint: - return is_nonneg_integer(); - case info_flags::even: - return is_even(); - case info_flags::odd: - return is_odd(); - case info_flags::prime: - return is_prime(); - } - return false; + switch (inf) { + case info_flags::numeric: + case info_flags::polynomial: + case info_flags::rational_function: + return true; + case info_flags::real: + return is_real(); + case info_flags::rational: + case info_flags::rational_polynomial: + return is_rational(); + case info_flags::crational: + case info_flags::crational_polynomial: + return is_crational(); + case info_flags::integer: + case info_flags::integer_polynomial: + return is_integer(); + case info_flags::cinteger: + case info_flags::cinteger_polynomial: + return is_cinteger(); + case info_flags::positive: + return is_positive(); + case info_flags::negative: + return is_negative(); + case info_flags::nonnegative: + return !is_negative(); + case info_flags::posint: + return is_pos_integer(); + case info_flags::negint: + return is_integer() && is_negative(); + case info_flags::nonnegint: + return is_nonneg_integer(); + case info_flags::even: + return is_even(); + case info_flags::odd: + return is_odd(); + case info_flags::prime: + return is_prime(); + case info_flags::algebraic: + return !is_real(); + } + return false; +} + +bool numeric::is_polynomial(const ex & var) const +{ + return true; +} + +int numeric::degree(const ex & s) const +{ + return 0; +} + +int numeric::ldegree(const ex & s) const +{ + return 0; +} + +ex numeric::coeff(const ex & s, int n) const +{ + return n==0 ? *this : _ex0; +} + +/** Disassemble real part and imaginary part to scan for the occurrence of a + * single number. Also handles the imaginary unit. It ignores the sign on + * both this and the argument, which may lead to what might appear as funny + * results: (2+I).has(-2) -> true. But this is consistent, since we also + * would like to have (-2+I).has(2) -> true and we want to think about the + * sign as a multiplicative factor. */ +bool numeric::has(const ex &other, unsigned options) const +{ + if (!is_exactly_a(other)) + return false; + const numeric &o = ex_to(other); + if (this->is_equal(o) || this->is_equal(-o)) + return true; + if (o.imag().is_zero()) { // e.g. scan for 3 in -3*I + if (!this->real().is_equal(*_num0_p)) + if (this->real().is_equal(o) || this->real().is_equal(-o)) + return true; + if (!this->imag().is_equal(*_num0_p)) + if (this->imag().is_equal(o) || this->imag().is_equal(-o)) + return true; + return false; + } + else { + if (o.is_equal(I)) // e.g scan for I in 42*I + return !this->is_real(); + if (o.real().is_zero()) // e.g. scan for 2*I in 2*I+1 + if (!this->imag().is_equal(*_num0_p)) + if (this->imag().is_equal(o*I) || this->imag().is_equal(-o*I)) + return true; + } + return false; +} + + +/** Evaluation of numbers doesn't do anything at all. */ +ex numeric::eval(int level) const +{ + // Warning: if this is ever gonna do something, the ex ctors from all kinds + // of numbers should be checking for status_flags::evaluated. + return this->hold(); } + /** Cast numeric into a floating-point object. For example exact numeric(1) is * returned as a 1.0000000000000000000000 and so on according to how Digits is - * currently set. + * currently set. In case the object already was a floating point number the + * precision is trimmed to match the currently set default. * - * @param level ignored, but needed for overriding basic::evalf. - * @return an ex-handle to a numeric. */ + * @param level ignored, only needed for overriding basic::evalf. + * @return an ex-handle to a numeric. */ ex numeric::evalf(int level) const { - // level can safely be discarded for numeric objects. - return numeric(cl_float(1.0, cl_default_float_format) * (*value)); // -> CLN + // level can safely be discarded for numeric objects. + return numeric(cln::cl_float(1.0, cln::default_float_format) * value); } -// protected - -int numeric::compare_same_type(basic const & other) const +ex numeric::conjugate() const { - GINAC_ASSERT(is_exactly_of_type(other, numeric)); - numeric const & o = static_cast(const_cast(other)); + if (is_real()) { + return *this; + } + return numeric(cln::conjugate(this->value)); +} - if (*value == *o.value) { - return 0; - } +// protected - return compare(o); +int numeric::compare_same_type(const basic &other) const +{ + GINAC_ASSERT(is_exactly_a(other)); + const numeric &o = static_cast(other); + + return this->compare(o); } -bool numeric::is_equal_same_type(basic const & other) const + +bool numeric::is_equal_same_type(const basic &other) const { - GINAC_ASSERT(is_exactly_of_type(other,numeric)); - numeric const *o = static_cast(&other); - - return is_equal(*o); + GINAC_ASSERT(is_exactly_a(other)); + const numeric &o = static_cast(other); + + return this->is_equal(o); } -/* -unsigned numeric::calchash(void) const + +unsigned numeric::calchash() const { - double d=to_double(); - int s=d>0 ? 1 : -1; - d=fabs(d); - if (d>0x07FF0000) { - d=0x07FF0000; - } - return 0x88000000U+s*unsigned(d/0x07FF0000); + // Base computation of hashvalue on CLN's hashcode. Note: That depends + // only on the number's value, not its type or precision (i.e. a true + // equivalence relation on numbers). As a consequence, 3 and 3.0 share + // the same hashvalue. That shouldn't really matter, though. + setflag(status_flags::hash_calculated); + hashvalue = golden_ratio_hash(cln::equal_hashcode(value)); + return hashvalue; } -*/ ////////// @@ -371,871 +733,874 @@ unsigned numeric::calchash(void) const // public /** Numerical addition method. Adds argument to *this and returns result as - * a new numeric object. */ -numeric numeric::add(numeric const & other) const + * a numeric object. */ +const numeric numeric::add(const numeric &other) const { - return numeric((*value)+(*other.value)); + return numeric(value + other.value); } + /** Numerical subtraction method. Subtracts argument from *this and returns - * result as a new numeric object. */ -numeric numeric::sub(numeric const & other) const + * result as a numeric object. */ +const numeric numeric::sub(const numeric &other) const { - return numeric((*value)-(*other.value)); + return numeric(value - other.value); } + /** Numerical multiplication method. Multiplies *this and argument and returns - * result as a new numeric object. */ -numeric numeric::mul(numeric const & other) const + * result as a numeric object. */ +const numeric numeric::mul(const numeric &other) const { - static const numeric * numONEp=&numONE(); - if (this==numONEp) { - return other; - } else if (&other==numONEp) { - return *this; - } - return numeric((*value)*(*other.value)); + return numeric(value * other.value); } + /** Numerical division method. Divides *this by argument and returns result as - * a new numeric object. + * a numeric object. * * @exception overflow_error (division by zero) */ -numeric numeric::div(numeric const & other) const +const numeric numeric::div(const numeric &other) const { - if (zerop(*other.value)) - throw (std::overflow_error("division by zero")); - return numeric((*value)/(*other.value)); + if (cln::zerop(other.value)) + throw std::overflow_error("numeric::div(): division by zero"); + return numeric(value / other.value); } -numeric numeric::power(numeric const & other) const + +/** Numerical exponentiation. Raises *this to the power given as argument and + * returns result as a numeric object. */ +const numeric numeric::power(const numeric &other) const { - static const numeric * numONEp=&numONE(); - if (&other==numONEp) { - return *this; - } - if (zerop(*value) && other.is_real() && minusp(realpart(*other.value))) - throw (std::overflow_error("division by zero")); - return numeric(expt(*value,*other.value)); + // Shortcut for efficiency and numeric stability (as in 1.0 exponent): + // trap the neutral exponent. + if (&other==_num1_p || cln::equal(other.value,_num1_p->value)) + return *this; + + if (cln::zerop(value)) { + if (cln::zerop(other.value)) + throw std::domain_error("numeric::eval(): pow(0,0) is undefined"); + else if (cln::zerop(cln::realpart(other.value))) + throw std::domain_error("numeric::eval(): pow(0,I) is undefined"); + else if (cln::minusp(cln::realpart(other.value))) + throw std::overflow_error("numeric::eval(): division by zero"); + else + return *_num0_p; + } + return numeric(cln::expt(value, other.value)); } -/** Inverse of a number. */ -numeric numeric::inverse(void) const + + +/** Numerical addition method. Adds argument to *this and returns result as + * a numeric object on the heap. Use internally only for direct wrapping into + * an ex object, where the result would end up on the heap anyways. */ +const numeric &numeric::add_dyn(const numeric &other) const { - return numeric(recip(*value)); // -> CLN + // Efficiency shortcut: trap the neutral element by pointer. This hack + // is supposed to keep the number of distinct numeric objects low. + if (this==_num0_p) + return other; + else if (&other==_num0_p) + return *this; + + return static_cast((new numeric(value + other.value))-> + setflag(status_flags::dynallocated)); } -numeric const & numeric::add_dyn(numeric const & other) const + +/** Numerical subtraction method. Subtracts argument from *this and returns + * result as a numeric object on the heap. Use internally only for direct + * wrapping into an ex object, where the result would end up on the heap + * anyways. */ +const numeric &numeric::sub_dyn(const numeric &other) const { - return static_cast((new numeric((*value)+(*other.value)))-> - setflag(status_flags::dynallocated)); + // Efficiency shortcut: trap the neutral exponent (first by pointer). This + // hack is supposed to keep the number of distinct numeric objects low. + if (&other==_num0_p || cln::zerop(other.value)) + return *this; + + return static_cast((new numeric(value - other.value))-> + setflag(status_flags::dynallocated)); } -numeric const & numeric::sub_dyn(numeric const & other) const + +/** Numerical multiplication method. Multiplies *this and argument and returns + * result as a numeric object on the heap. Use internally only for direct + * wrapping into an ex object, where the result would end up on the heap + * anyways. */ +const numeric &numeric::mul_dyn(const numeric &other) const { - return static_cast((new numeric((*value)-(*other.value)))-> - setflag(status_flags::dynallocated)); + // Efficiency shortcut: trap the neutral element by pointer. This hack + // is supposed to keep the number of distinct numeric objects low. + if (this==_num1_p) + return other; + else if (&other==_num1_p) + return *this; + + return static_cast((new numeric(value * other.value))-> + setflag(status_flags::dynallocated)); } -numeric const & numeric::mul_dyn(numeric const & other) const + +/** Numerical division method. Divides *this by argument and returns result as + * a numeric object on the heap. Use internally only for direct wrapping + * into an ex object, where the result would end up on the heap + * anyways. + * + * @exception overflow_error (division by zero) */ +const numeric &numeric::div_dyn(const numeric &other) const { - static const numeric * numONEp=&numONE(); - if (this==numONEp) { - return other; - } else if (&other==numONEp) { - return *this; - } - return static_cast((new numeric((*value)*(*other.value)))-> - setflag(status_flags::dynallocated)); + // Efficiency shortcut: trap the neutral element by pointer. This hack + // is supposed to keep the number of distinct numeric objects low. + if (&other==_num1_p) + return *this; + if (cln::zerop(cln::the(other.value))) + throw std::overflow_error("division by zero"); + return static_cast((new numeric(value / other.value))-> + setflag(status_flags::dynallocated)); } -numeric const & numeric::div_dyn(numeric const & other) const + +/** Numerical exponentiation. Raises *this to the power given as argument and + * returns result as a numeric object on the heap. Use internally only for + * direct wrapping into an ex object, where the result would end up on the + * heap anyways. */ +const numeric &numeric::power_dyn(const numeric &other) const { - if (zerop(*other.value)) - throw (std::overflow_error("division by zero")); - return static_cast((new numeric((*value)/(*other.value)))-> - setflag(status_flags::dynallocated)); + // Efficiency shortcut: trap the neutral exponent (first try by pointer, then + // try harder, since calls to cln::expt() below may return amazing results for + // floating point exponent 1.0). + if (&other==_num1_p || cln::equal(other.value, _num1_p->value)) + return *this; + + if (cln::zerop(value)) { + if (cln::zerop(other.value)) + throw std::domain_error("numeric::eval(): pow(0,0) is undefined"); + else if (cln::zerop(cln::realpart(other.value))) + throw std::domain_error("numeric::eval(): pow(0,I) is undefined"); + else if (cln::minusp(cln::realpart(other.value))) + throw std::overflow_error("numeric::eval(): division by zero"); + else + return *_num0_p; + } + return static_cast((new numeric(cln::expt(value, other.value)))-> + setflag(status_flags::dynallocated)); } -numeric const & numeric::power_dyn(numeric const & other) const + +const numeric &numeric::operator=(int i) { - static const numeric * numONEp=&numONE(); - if (&other==numONEp) { - return *this; - } - // The ifs are only a workaround for a bug in CLN. It gets stuck otherwise: - if ( !other.is_integer() && - other.is_rational() && - (*this).is_nonneg_integer() ) { - if ( !zerop(*value) ) { - return static_cast((new numeric(exp(*other.value * log(*value))))-> - setflag(status_flags::dynallocated)); - } else { - if ( !zerop(*other.value) ) { // 0^(n/m) - return static_cast((new numeric(0))-> - setflag(status_flags::dynallocated)); - } else { // raise FPE (0^0 requested) - return static_cast((new numeric(1/(*other.value)))-> - setflag(status_flags::dynallocated)); - } - } - } else { // default -> CLN - return static_cast((new numeric(expt(*value,*other.value)))-> - setflag(status_flags::dynallocated)); - } + return operator=(numeric(i)); } -numeric const & numeric::operator=(int i) + +const numeric &numeric::operator=(unsigned int i) { - return operator=(numeric(i)); + return operator=(numeric(i)); } -numeric const & numeric::operator=(unsigned int i) + +const numeric &numeric::operator=(long i) { - return operator=(numeric(i)); + return operator=(numeric(i)); } -numeric const & numeric::operator=(long i) + +const numeric &numeric::operator=(unsigned long i) { - return operator=(numeric(i)); + return operator=(numeric(i)); } -numeric const & numeric::operator=(unsigned long i) + +const numeric &numeric::operator=(double d) { - return operator=(numeric(i)); + return operator=(numeric(d)); } -numeric const & numeric::operator=(double d) + +const numeric &numeric::operator=(const char * s) { - return operator=(numeric(d)); + return operator=(numeric(s)); } -numeric const & numeric::operator=(char const * s) + +/** Inverse of a number. */ +const numeric numeric::inverse() const { - return operator=(numeric(s)); + if (cln::zerop(value)) + throw std::overflow_error("numeric::inverse(): division by zero"); + return numeric(cln::recip(value)); +} + +/** Return the step function of a numeric. The imaginary part of it is + * ignored because the step function is generally considered real but + * a numeric may develop a small imaginary part due to rounding errors. + */ +numeric numeric::step() const +{ cln::cl_R r = cln::realpart(value); + if(cln::zerop(r)) + return numeric(1,2); + if(cln::plusp(r)) + return 1; + return 0; } /** Return the complex half-plane (left or right) in which the number lies. * csgn(x)==0 for x==0, csgn(x)==1 for Re(x)>0 or Re(x)=0 and Im(x)>0, * csgn(x)==-1 for Re(x)<0 or Re(x)=0 and Im(x)<0. * - * @see numeric::compare(numeric const & other) */ -int numeric::csgn(void) const -{ - if (is_zero()) - return 0; - if (!zerop(realpart(*value))) { - if (plusp(realpart(*value))) - return 1; - else - return -1; - } else { - if (plusp(imagpart(*value))) - return 1; - else - return -1; - } + * @see numeric::compare(const numeric &other) */ +int numeric::csgn() const +{ + if (cln::zerop(value)) + return 0; + cln::cl_R r = cln::realpart(value); + if (!cln::zerop(r)) { + if (cln::plusp(r)) + return 1; + else + return -1; + } else { + if (cln::plusp(cln::imagpart(value))) + return 1; + else + return -1; + } } + /** This method establishes a canonical order on all numbers. For complex * numbers this is not possible in a mathematically consistent way but we need * to establish some order and it ought to be fast. So we simply define it * to be compatible with our method csgn. * * @return csgn(*this-other) - * @see numeric::csgn(void) */ -int numeric::compare(numeric const & other) const + * @see numeric::csgn() */ +int numeric::compare(const numeric &other) const { - // Comparing two real numbers? - if (is_real() && other.is_real()) - // Yes, just compare them - return cl_compare(The(cl_R)(*value), The(cl_R)(*other.value)); - else { - // No, first compare real parts - cl_signean real_cmp = cl_compare(realpart(*value), realpart(*other.value)); - if (real_cmp) - return real_cmp; - - return cl_compare(imagpart(*value), imagpart(*other.value)); - } + // Comparing two real numbers? + if (cln::instanceof(value, cln::cl_R_ring) && + cln::instanceof(other.value, cln::cl_R_ring)) + // Yes, so just cln::compare them + return cln::compare(cln::the(value), cln::the(other.value)); + else { + // No, first cln::compare real parts... + cl_signean real_cmp = cln::compare(cln::realpart(value), cln::realpart(other.value)); + if (real_cmp) + return real_cmp; + // ...and then the imaginary parts. + return cln::compare(cln::imagpart(value), cln::imagpart(other.value)); + } } -bool numeric::is_equal(numeric const & other) const + +bool numeric::is_equal(const numeric &other) const { - return (*value == *other.value); + return cln::equal(value, other.value); } + /** True if object is zero. */ -bool numeric::is_zero(void) const +bool numeric::is_zero() const { - return zerop(*value); // -> CLN + return cln::zerop(value); } + /** True if object is not complex and greater than zero. */ -bool numeric::is_positive(void) const +bool numeric::is_positive() const { - if (is_real()) { - return plusp(The(cl_R)(*value)); // -> CLN - } - return false; + if (cln::instanceof(value, cln::cl_R_ring)) // real? + return cln::plusp(cln::the(value)); + return false; } + /** True if object is not complex and less than zero. */ -bool numeric::is_negative(void) const +bool numeric::is_negative() const { - if (is_real()) { - return minusp(The(cl_R)(*value)); // -> CLN - } - return false; + if (cln::instanceof(value, cln::cl_R_ring)) // real? + return cln::minusp(cln::the(value)); + return false; } + /** True if object is a non-complex integer. */ -bool numeric::is_integer(void) const +bool numeric::is_integer() const { - return (bool)instanceof(*value, cl_I_ring); // -> CLN + return cln::instanceof(value, cln::cl_I_ring); } + /** True if object is an exact integer greater than zero. */ -bool numeric::is_pos_integer(void) const +bool numeric::is_pos_integer() const { - return (is_integer() && - plusp(The(cl_I)(*value))); // -> CLN + return (cln::instanceof(value, cln::cl_I_ring) && cln::plusp(cln::the(value))); } + /** True if object is an exact integer greater or equal zero. */ -bool numeric::is_nonneg_integer(void) const +bool numeric::is_nonneg_integer() const { - return (is_integer() && - !minusp(The(cl_I)(*value))); // -> CLN + return (cln::instanceof(value, cln::cl_I_ring) && !cln::minusp(cln::the(value))); } + /** True if object is an exact even integer. */ -bool numeric::is_even(void) const +bool numeric::is_even() const { - return (is_integer() && - evenp(The(cl_I)(*value))); // -> CLN + return (cln::instanceof(value, cln::cl_I_ring) && cln::evenp(cln::the(value))); } + /** True if object is an exact odd integer. */ -bool numeric::is_odd(void) const +bool numeric::is_odd() const { - return (is_integer() && - oddp(The(cl_I)(*value))); // -> CLN + return (cln::instanceof(value, cln::cl_I_ring) && cln::oddp(cln::the(value))); } + /** Probabilistic primality test. * * @return true if object is exact integer and prime. */ -bool numeric::is_prime(void) const +bool numeric::is_prime() const { - return (is_integer() && - isprobprime(The(cl_I)(*value))); // -> CLN + return (cln::instanceof(value, cln::cl_I_ring) // integer? + && cln::plusp(cln::the(value)) // positive? + && cln::isprobprime(cln::the(value))); } + /** True if object is an exact rational number, may even be complex * (denominator may be unity). */ -bool numeric::is_rational(void) const +bool numeric::is_rational() const { - if (instanceof(*value, cl_RA_ring)) { - return true; - } else if (!is_real()) { // complex case, handle Q(i): - if ( instanceof(realpart(*value), cl_RA_ring) && - instanceof(imagpart(*value), cl_RA_ring) ) - return true; - } - return false; + return cln::instanceof(value, cln::cl_RA_ring); } + /** True if object is a real integer, rational or float (but not complex). */ -bool numeric::is_real(void) const +bool numeric::is_real() const { - return (bool)instanceof(*value, cl_R_ring); // -> CLN + return cln::instanceof(value, cln::cl_R_ring); } -bool numeric::operator==(numeric const & other) const + +bool numeric::operator==(const numeric &other) const { - return (*value == *other.value); // -> CLN + return cln::equal(value, other.value); } -bool numeric::operator!=(numeric const & other) const + +bool numeric::operator!=(const numeric &other) const { - return (*value != *other.value); // -> CLN + return !cln::equal(value, other.value); } + +/** True if object is element of the domain of integers extended by I, i.e. is + * of the form a+b*I, where a and b are integers. */ +bool numeric::is_cinteger() const +{ + if (cln::instanceof(value, cln::cl_I_ring)) + return true; + else if (!this->is_real()) { // complex case, handle n+m*I + if (cln::instanceof(cln::realpart(value), cln::cl_I_ring) && + cln::instanceof(cln::imagpart(value), cln::cl_I_ring)) + return true; + } + return false; +} + + +/** True if object is an exact rational number, may even be complex + * (denominator may be unity). */ +bool numeric::is_crational() const +{ + if (cln::instanceof(value, cln::cl_RA_ring)) + return true; + else if (!this->is_real()) { // complex case, handle Q(i): + if (cln::instanceof(cln::realpart(value), cln::cl_RA_ring) && + cln::instanceof(cln::imagpart(value), cln::cl_RA_ring)) + return true; + } + return false; +} + + /** Numerical comparison: less. * * @exception invalid_argument (complex inequality) */ -bool numeric::operator<(numeric const & other) const +bool numeric::operator<(const numeric &other) const { - if ( is_real() && other.is_real() ) { - return (bool)(The(cl_R)(*value) < The(cl_R)(*other.value)); // -> CLN - } - throw (std::invalid_argument("numeric::operator<(): complex inequality")); - return false; // make compiler shut up + if (this->is_real() && other.is_real()) + return (cln::the(value) < cln::the(other.value)); + throw std::invalid_argument("numeric::operator<(): complex inequality"); } + /** Numerical comparison: less or equal. * * @exception invalid_argument (complex inequality) */ -bool numeric::operator<=(numeric const & other) const +bool numeric::operator<=(const numeric &other) const { - if ( is_real() && other.is_real() ) { - return (bool)(The(cl_R)(*value) <= The(cl_R)(*other.value)); // -> CLN - } - throw (std::invalid_argument("numeric::operator<=(): complex inequality")); - return false; // make compiler shut up + if (this->is_real() && other.is_real()) + return (cln::the(value) <= cln::the(other.value)); + throw std::invalid_argument("numeric::operator<=(): complex inequality"); } + /** Numerical comparison: greater. * * @exception invalid_argument (complex inequality) */ -bool numeric::operator>(numeric const & other) const +bool numeric::operator>(const numeric &other) const { - if ( is_real() && other.is_real() ) { - return (bool)(The(cl_R)(*value) > The(cl_R)(*other.value)); // -> CLN - } - throw (std::invalid_argument("numeric::operator>(): complex inequality")); - return false; // make compiler shut up + if (this->is_real() && other.is_real()) + return (cln::the(value) > cln::the(other.value)); + throw std::invalid_argument("numeric::operator>(): complex inequality"); } + /** Numerical comparison: greater or equal. * * @exception invalid_argument (complex inequality) */ -bool numeric::operator>=(numeric const & other) const +bool numeric::operator>=(const numeric &other) const { - if ( is_real() && other.is_real() ) { - return (bool)(The(cl_R)(*value) >= The(cl_R)(*other.value)); // -> CLN - } - throw (std::invalid_argument("numeric::operator>=(): complex inequality")); - return false; // make compiler shut up + if (this->is_real() && other.is_real()) + return (cln::the(value) >= cln::the(other.value)); + throw std::invalid_argument("numeric::operator>=(): complex inequality"); } -/** Converts numeric types to machine's int. You should check with is_integer() - * if the number is really an integer before calling this method. */ -int numeric::to_int(void) const + +/** Converts numeric types to machine's int. You should check with + * is_integer() if the number is really an integer before calling this method. + * You may also consider checking the range first. */ +int numeric::to_int() const { - GINAC_ASSERT(is_integer()); - return cl_I_to_int(The(cl_I)(*value)); + GINAC_ASSERT(this->is_integer()); + return cln::cl_I_to_int(cln::the(value)); } + +/** Converts numeric types to machine's long. You should check with + * is_integer() if the number is really an integer before calling this method. + * You may also consider checking the range first. */ +long numeric::to_long() const +{ + GINAC_ASSERT(this->is_integer()); + return cln::cl_I_to_long(cln::the(value)); +} + + /** Converts numeric types to machine's double. You should check with is_real() * if the number is really not complex before calling this method. */ -double numeric::to_double(void) const +double numeric::to_double() const { - GINAC_ASSERT(is_real()); - return cl_double_approx(realpart(*value)); + GINAC_ASSERT(this->is_real()); + return cln::double_approx(cln::realpart(value)); } + +/** Returns a new CLN object of type cl_N, representing the value of *this. + * This method may be used when mixing GiNaC and CLN in one project. + */ +cln::cl_N numeric::to_cl_N() const +{ + return value; +} + + /** Real part of a number. */ -numeric numeric::real(void) const +const numeric numeric::real() const { - return numeric(realpart(*value)); // -> CLN + return numeric(cln::realpart(value)); } + /** Imaginary part of a number. */ -numeric numeric::imag(void) const +const numeric numeric::imag() const { - return numeric(imagpart(*value)); // -> CLN + return numeric(cln::imagpart(value)); } -#ifndef SANE_LINKER -// Unfortunately, CLN did not provide an official way to access the numerator -// or denominator of a rational number (cl_RA). Doing some excavations in CLN -// one finds how it works internally in src/rational/cl_RA.h: -struct cl_heap_ratio : cl_heap { - cl_I numerator; - cl_I denominator; -}; - -inline cl_heap_ratio* TheRatio (const cl_N& obj) -{ return (cl_heap_ratio*)(obj.pointer); } -#endif // ndef SANE_LINKER /** Numerator. Computes the numerator of rational numbers, rationalized * numerator of complex if real and imaginary part are both rational numbers * (i.e numer(4/3+5/6*I) == 8+5*I), the number carrying the sign in all other * cases. */ -numeric numeric::numer(void) const -{ - if (is_integer()) { - return numeric(*this); - } -#ifdef SANE_LINKER - else if (instanceof(*value, cl_RA_ring)) { - return numeric(numerator(The(cl_RA)(*value))); - } - else if (!is_real()) { // complex case, handle Q(i): - cl_R r = realpart(*value); - cl_R i = imagpart(*value); - if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring)) - return numeric(*this); - if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring)) - return numeric(complex(r*denominator(The(cl_RA)(i)), numerator(The(cl_RA)(i)))); - if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring)) - return numeric(complex(numerator(The(cl_RA)(r)), i*denominator(The(cl_RA)(r)))); - if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) { - cl_I s = lcm(denominator(The(cl_RA)(r)), denominator(The(cl_RA)(i))); - return numeric(complex(numerator(The(cl_RA)(r))*(exquo(s,denominator(The(cl_RA)(r)))), - numerator(The(cl_RA)(i))*(exquo(s,denominator(The(cl_RA)(i)))))); - } - } -#else - else if (instanceof(*value, cl_RA_ring)) { - return numeric(TheRatio(*value)->numerator); - } - else if (!is_real()) { // complex case, handle Q(i): - cl_R r = realpart(*value); - cl_R i = imagpart(*value); - if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring)) - return numeric(*this); - if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring)) - return numeric(complex(r*TheRatio(i)->denominator, TheRatio(i)->numerator)); - if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring)) - return numeric(complex(TheRatio(r)->numerator, i*TheRatio(r)->denominator)); - if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) { - cl_I s = lcm(TheRatio(r)->denominator, TheRatio(i)->denominator); - return numeric(complex(TheRatio(r)->numerator*(exquo(s,TheRatio(r)->denominator)), - TheRatio(i)->numerator*(exquo(s,TheRatio(i)->denominator)))); - } - } -#endif // def SANE_LINKER - // at least one float encountered - return numeric(*this); +const numeric numeric::numer() const +{ + if (cln::instanceof(value, cln::cl_I_ring)) + return numeric(*this); // integer case + + else if (cln::instanceof(value, cln::cl_RA_ring)) + return numeric(cln::numerator(cln::the(value))); + + else if (!this->is_real()) { // complex case, handle Q(i): + const cln::cl_RA r = cln::the(cln::realpart(value)); + const cln::cl_RA i = cln::the(cln::imagpart(value)); + if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_I_ring)) + return numeric(*this); + if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_RA_ring)) + return numeric(cln::complex(r*cln::denominator(i), cln::numerator(i))); + if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_I_ring)) + return numeric(cln::complex(cln::numerator(r), i*cln::denominator(r))); + if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_RA_ring)) { + const cln::cl_I s = cln::lcm(cln::denominator(r), cln::denominator(i)); + return numeric(cln::complex(cln::numerator(r)*(cln::exquo(s,cln::denominator(r))), + cln::numerator(i)*(cln::exquo(s,cln::denominator(i))))); + } + } + // at least one float encountered + return numeric(*this); } + /** Denominator. Computes the denominator of rational numbers, common integer * denominator of complex if real and imaginary part are both rational numbers * (i.e denom(4/3+5/6*I) == 6), one in all other cases. */ -numeric numeric::denom(void) const -{ - if (is_integer()) { - return numONE(); - } -#ifdef SANE_LINKER - if (instanceof(*value, cl_RA_ring)) { - return numeric(denominator(The(cl_RA)(*value))); - } - if (!is_real()) { // complex case, handle Q(i): - cl_R r = realpart(*value); - cl_R i = imagpart(*value); - if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring)) - return numONE(); - if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring)) - return numeric(denominator(The(cl_RA)(i))); - if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring)) - return numeric(denominator(The(cl_RA)(r))); - if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) - return numeric(lcm(denominator(The(cl_RA)(r)), denominator(The(cl_RA)(i)))); - } -#else - if (instanceof(*value, cl_RA_ring)) { - return numeric(TheRatio(*value)->denominator); - } - if (!is_real()) { // complex case, handle Q(i): - cl_R r = realpart(*value); - cl_R i = imagpart(*value); - if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring)) - return numONE(); - if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring)) - return numeric(TheRatio(i)->denominator); - if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring)) - return numeric(TheRatio(r)->denominator); - if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) - return numeric(lcm(TheRatio(r)->denominator, TheRatio(i)->denominator)); - } -#endif // def SANE_LINKER - // at least one float encountered - return numONE(); +const numeric numeric::denom() const +{ + if (cln::instanceof(value, cln::cl_I_ring)) + return *_num1_p; // integer case + + if (cln::instanceof(value, cln::cl_RA_ring)) + return numeric(cln::denominator(cln::the(value))); + + if (!this->is_real()) { // complex case, handle Q(i): + const cln::cl_RA r = cln::the(cln::realpart(value)); + const cln::cl_RA i = cln::the(cln::imagpart(value)); + if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_I_ring)) + return *_num1_p; + if (cln::instanceof(r, cln::cl_I_ring) && cln::instanceof(i, cln::cl_RA_ring)) + return numeric(cln::denominator(i)); + if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_I_ring)) + return numeric(cln::denominator(r)); + if (cln::instanceof(r, cln::cl_RA_ring) && cln::instanceof(i, cln::cl_RA_ring)) + return numeric(cln::lcm(cln::denominator(r), cln::denominator(i))); + } + // at least one float encountered + return *_num1_p; } + /** Size in binary notation. For integers, this is the smallest n >= 0 such * that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that * 2^(n-1) <= x < 2^n. * * @return number of bits (excluding sign) needed to represent that number * in two's complement if it is an integer, 0 otherwise. */ -int numeric::int_length(void) const +int numeric::int_length() const { - if (is_integer()) { - return integer_length(The(cl_I)(*value)); // -> CLN - } else { - return 0; - } + if (cln::instanceof(value, cln::cl_I_ring)) + return cln::integer_length(cln::the(value)); + else + return 0; } - -////////// -// static member variables -////////// - -// protected - -unsigned numeric::precedence = 30; - ////////// // global constants ////////// -const numeric some_numeric; -type_info const & typeid_numeric=typeid(some_numeric); /** Imaginary unit. This is not a constant but a numeric since we are - * natively handing complex numbers anyways. */ -const numeric I = numeric(complex(cl_I(0),cl_I(1))); - -////////// -// global functions -////////// - -numeric const & numZERO(void) -{ - const static ex eZERO = ex((new numeric(0))->setflag(status_flags::dynallocated)); - const static numeric * nZERO = static_cast(eZERO.bp); - return *nZERO; -} - -numeric const & numONE(void) -{ - const static ex eONE = ex((new numeric(1))->setflag(status_flags::dynallocated)); - const static numeric * nONE = static_cast(eONE.bp); - return *nONE; -} - -numeric const & numTWO(void) -{ - const static ex eTWO = ex((new numeric(2))->setflag(status_flags::dynallocated)); - const static numeric * nTWO = static_cast(eTWO.bp); - return *nTWO; -} - -numeric const & numTHREE(void) -{ - const static ex eTHREE = ex((new numeric(3))->setflag(status_flags::dynallocated)); - const static numeric * nTHREE = static_cast(eTHREE.bp); - return *nTHREE; -} - -numeric const & numMINUSONE(void) -{ - const static ex eMINUSONE = ex((new numeric(-1))->setflag(status_flags::dynallocated)); - const static numeric * nMINUSONE = static_cast(eMINUSONE.bp); - return *nMINUSONE; -} - -numeric const & numHALF(void) -{ - const static ex eHALF = ex((new numeric(1, 2))->setflag(status_flags::dynallocated)); - const static numeric * nHALF = static_cast(eHALF.bp); - return *nHALF; -} - -/** Exponential function. - * - * @return arbitrary precision numerical exp(x). */ -numeric exp(numeric const & x) -{ - return ::exp(*x.value); // -> CLN -} - -/** Natural logarithm. - * - * @param z complex number - * @return arbitrary precision numerical log(x). - * @exception overflow_error (logarithmic singularity) */ -numeric log(numeric const & z) -{ - if (z.is_zero()) - throw (std::overflow_error("log(): logarithmic singularity")); - return ::log(*z.value); // -> CLN -} - -/** Numeric sine (trigonometric function). + * natively handing complex numbers anyways, so in each expression containing + * an I it is automatically eval'ed away anyhow. */ +const numeric I = numeric(cln::complex(cln::cl_I(0),cln::cl_I(1))); + +/*static cln::cl_N Li2_series(const ::cl_N &x, + const ::float_format_t &prec) +{ + // Note: argument must be in the unit circle + // This is very inefficient unless we have fast floating point Bernoulli + // numbers implemented! + cln::cl_N c1 = -cln::log(1-x); + cln::cl_N c2 = c1; + // hard-wire the first two Bernoulli numbers + cln::cl_N acc = c1 - cln::square(c1)/4; + cln::cl_N aug; + cln::cl_F pisq = cln::square(cln::cl_pi(prec)); // pi^2 + cln::cl_F piac = cln::cl_float(1, prec); // accumulator: pi^(2*i) + unsigned i = 1; + c1 = cln::square(c1); + do { + c2 = c1 * c2; + piac = piac * pisq; + aug = c2 * (*(bernoulli(numeric(2*i)).clnptr())) / cln::factorial(2*i+1); + // 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)); + acc = acc + aug; + ++i; + } while (acc != acc+aug); + return acc; +}*/ + +/** Numeric evaluation of Dilogarithm within circle of convergence (unit + * circle) using a power series. */ +static cln::cl_N Li2_series(const cln::cl_N &x, + const cln::float_format_t &prec) +{ + // Note: argument must be in the unit circle + cln::cl_N aug, acc; + cln::cl_N num = cln::complex(cln::cl_float(1, prec), 0); + cln::cl_I den = 0; + unsigned i = 1; + do { + num = num * x; + den = den + i; // 1, 4, 9, 16, ... + i += 2; + aug = num / den; + acc = acc + aug; + } while (acc != acc+aug); + return acc; +} + +/** Folds Li2's argument inside a small rectangle to enhance convergence. */ +static cln::cl_N Li2_projection(const cln::cl_N &x, + const cln::float_format_t &prec) +{ + const cln::cl_R re = cln::realpart(x); + const cln::cl_R im = cln::imagpart(x); + if (re > cln::cl_F(".5")) + // zeta(2) - Li2(1-x) - log(x)*log(1-x) + return(cln::zeta(2) + - Li2_series(1-x, prec) + - cln::log(x)*cln::log(1-x)); + if ((re <= 0 && cln::abs(im) > cln::cl_F(".75")) || (re < cln::cl_F("-.5"))) + // -log(1-x)^2 / 2 - Li2(x/(x-1)) + return(- cln::square(cln::log(1-x))/2 + - Li2_series(x/(x-1), prec)); + if (re > 0 && cln::abs(im) > cln::cl_LF(".75")) + // Li2(x^2)/2 - Li2(-x) + return(Li2_projection(cln::square(x), prec)/2 + - Li2_projection(-x, prec)); + return Li2_series(x, prec); +} + +/** Numeric evaluation of Dilogarithm. The domain is the entire complex plane, + * the branch cut lies along the positive real axis, starting at 1 and + * continuous with quadrant IV. * - * @return arbitrary precision numerical sin(x). */ -numeric sin(numeric const & x) -{ - return ::sin(*x.value); // -> CLN + * @return arbitrary precision numerical Li2(x). */ +const numeric Li2(const numeric &x) +{ + if (x.is_zero()) + return *_num0_p; + + // what is the desired float format? + // first guess: default format + cln::float_format_t prec = cln::default_float_format; + const cln::cl_N value = x.to_cl_N(); + // second guess: the argument's format + if (!x.real().is_rational()) + prec = cln::float_format(cln::the(cln::realpart(value))); + else if (!x.imag().is_rational()) + prec = cln::float_format(cln::the(cln::imagpart(value))); + + if (value==1) // may cause trouble with log(1-x) + return cln::zeta(2, prec); + + if (cln::abs(value) > 1) + // -log(-x)^2 / 2 - zeta(2) - Li2(1/x) + return(- cln::square(cln::log(-value))/2 + - cln::zeta(2, prec) + - Li2_projection(cln::recip(value), prec)); + else + return Li2_projection(x.to_cl_N(), prec); } -/** Numeric cosine (trigonometric function). - * - * @return arbitrary precision numerical cos(x). */ -numeric cos(numeric const & x) -{ - return ::cos(*x.value); // -> CLN -} - -/** Numeric tangent (trigonometric function). - * - * @return arbitrary precision numerical tan(x). */ -numeric tan(numeric const & x) -{ - return ::tan(*x.value); // -> CLN -} - -/** Numeric inverse sine (trigonometric function). - * - * @return arbitrary precision numerical asin(x). */ -numeric asin(numeric const & x) -{ - return ::asin(*x.value); // -> CLN -} - -/** Numeric inverse cosine (trigonometric function). - * - * @return arbitrary precision numerical acos(x). */ -numeric acos(numeric const & x) -{ - return ::acos(*x.value); // -> CLN -} - -/** Arcustangents. - * - * @param z complex number - * @return atan(z) - * @exception overflow_error (logarithmic singularity) */ -numeric atan(numeric const & x) -{ - if (!x.is_real() && - x.real().is_zero() && - !abs(x.imag()).is_equal(numONE())) - throw (std::overflow_error("atan(): logarithmic singularity")); - return ::atan(*x.value); // -> CLN -} - -/** Arcustangents. - * - * @param x real number - * @param y real number - * @return atan(y/x) */ -numeric atan(numeric const & y, numeric const & x) -{ - if (x.is_real() && y.is_real()) - return ::atan(realpart(*x.value), realpart(*y.value)); // -> CLN - else - throw (std::invalid_argument("numeric::atan(): complex argument")); -} - -/** Numeric hyperbolic sine (trigonometric function). - * - * @return arbitrary precision numerical sinh(x). */ -numeric sinh(numeric const & x) -{ - return ::sinh(*x.value); // -> CLN -} - -/** Numeric hyperbolic cosine (trigonometric function). - * - * @return arbitrary precision numerical cosh(x). */ -numeric cosh(numeric const & x) -{ - return ::cosh(*x.value); // -> CLN -} - -/** Numeric hyperbolic tangent (trigonometric function). - * - * @return arbitrary precision numerical tanh(x). */ -numeric tanh(numeric const & x) -{ - return ::tanh(*x.value); // -> CLN -} - -/** Numeric inverse hyperbolic sine (trigonometric function). - * - * @return arbitrary precision numerical asinh(x). */ -numeric asinh(numeric const & x) -{ - return ::asinh(*x.value); // -> CLN -} - -/** Numeric inverse hyperbolic cosine (trigonometric function). - * - * @return arbitrary precision numerical acosh(x). */ -numeric acosh(numeric const & x) -{ - return ::acosh(*x.value); // -> CLN -} - -/** Numeric inverse hyperbolic tangent (trigonometric function). - * - * @return arbitrary precision numerical atanh(x). */ -numeric atanh(numeric const & x) -{ - return ::atanh(*x.value); // -> CLN -} /** Numeric evaluation of Riemann's Zeta function. Currently works only for * integer arguments. */ -numeric zeta(numeric const & x) +const numeric zeta(const numeric &x) { - if (x.is_integer()) - return ::cl_zeta(x.to_int()); // -> CLN - else - clog << "zeta(): Does anybody know good way to calculate this numerically?" << endl; - return numeric(0); + // A dirty hack to allow for things like zeta(3.0), since CLN currently + // only knows about integer arguments and zeta(3).evalf() automatically + // cascades down to zeta(3.0).evalf(). The trick is to rely on 3.0-3 + // being an exact zero for CLN, which can be tested and then we can just + // pass the number casted to an int: + if (x.is_real()) { + const int aux = (int)(cln::double_approx(cln::the(x.to_cl_N()))); + if (cln::zerop(x.to_cl_N()-aux)) + return cln::zeta(aux); + } + throw dunno(); } -/** The gamma function. - * This is only a stub! */ -numeric gamma(numeric const & x) -{ - clog << "gamma(): Does anybody know good way to calculate this numerically?" << endl; - return numeric(0); -} - -/** The psi function (aka polygamma function). - * This is only a stub! */ -numeric psi(numeric const & n, numeric const & x) -{ - clog << "psi(): Does anybody know good way to calculate this numerically?" << endl; - return numeric(0); -} - -/** Factorial combinatorial function. - * - * @exception range_error (argument must be integer >= 0) */ -numeric factorial(numeric const & nn) -{ - if ( !nn.is_nonneg_integer() ) { - throw (std::range_error("numeric::factorial(): argument must be integer >= 0")); - } - - return numeric(::factorial(nn.to_int())); // -> CLN -} /** The double factorial combinatorial function. (Scarcely used, but still - * useful in cases, like for exact results of Gamma(n+1/2) for instance.) + * useful in cases, like for exact results of tgamma(n+1/2) for instance.) * * @param n integer argument >= -1 - * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == 1 == (-1)!! + * @return n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == (-1)!! == 1 * @exception range_error (argument must be integer >= -1) */ -numeric doublefactorial(numeric const & nn) -{ - // META-NOTE: The whole shit here will become obsolete and may be moved - // out once CLN learns about double factorial, which should be as soon as - // 1.0.3 rolls out! - - // We store the results separately for even and odd arguments. This has - // the advantage that we don't have to compute any even result at all if - // the function is always called with odd arguments and vice versa. There - // is no tradeoff involved in this, it is guaranteed to save time as well - // as memory. (If this is not enough justification consider the Gamma - // function of half integer arguments: it only needs odd doublefactorials.) - static vector evenresults; - static int highest_evenresult = -1; - static vector oddresults; - static int highest_oddresult = -1; - - if (nn == numeric(-1)) { - return numONE(); - } - if (!nn.is_nonneg_integer()) { - throw (std::range_error("numeric::doublefactorial(): argument must be integer >= -1")); - } - if (nn.is_even()) { - int n = nn.div(numTWO()).to_int(); - if (n <= highest_evenresult) { - return evenresults[n]; - } - if (evenresults.capacity() < (unsigned)(n+1)) { - evenresults.reserve(n+1); - } - if (highest_evenresult < 0) { - evenresults.push_back(numONE()); - highest_evenresult=0; - } - for (int i=highest_evenresult+1; i<=n; i++) { - evenresults.push_back(numeric(evenresults[i-1].mul(numeric(i*2)))); - } - highest_evenresult=n; - return evenresults[n]; - } else { - int n = nn.sub(numONE()).div(numTWO()).to_int(); - if (n <= highest_oddresult) { - return oddresults[n]; - } - if (oddresults.capacity() < (unsigned)n) { - oddresults.reserve(n+1); - } - if (highest_oddresult < 0) { - oddresults.push_back(numONE()); - highest_oddresult=0; - } - for (int i=highest_oddresult+1; i<=n; i++) { - oddresults.push_back(numeric(oddresults[i-1].mul(numeric(i*2+1)))); - } - highest_oddresult=n; - return oddresults[n]; - } -} - -/** The Binomial coefficients. It computes the binomial coefficients. For - * integer n and k and positive n this is the number of ways of choosing k - * objects from n distinct objects. If n is negative, the formula - * binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result. */ -numeric binomial(numeric const & n, numeric const & k) -{ - if (n.is_integer() && k.is_integer()) { - if (n.is_nonneg_integer()) { - if (k.compare(n)!=1 && k.compare(numZERO())!=-1) - return numeric(::binomial(n.to_int(),k.to_int())); // -> CLN - else - return numZERO(); - } else { - return numMINUSONE().power(k)*binomial(k-n-numONE(),k); - } - } - - // should really be gamma(n+1)/(gamma(r+1)/gamma(n-r+1) or a suitable limit - throw (std::range_error("numeric::binomial(): donĀ“t know how to evaluate that.")); +const numeric doublefactorial(const numeric &n) +{ + if (n.is_equal(*_num_1_p)) + return *_num1_p; + + if (!n.is_nonneg_integer()) + throw std::range_error("numeric::doublefactorial(): argument must be integer >= -1"); + + return numeric(cln::doublefactorial(n.to_int())); } + /** Bernoulli number. The nth Bernoulli number is the coefficient of x^n/n! * in the expansion of the function x/(e^x-1). * * @return the nth Bernoulli number (a rational number). * @exception range_error (argument must be integer >= 0) */ -numeric bernoulli(numeric const & nn) -{ - if (!nn.is_integer() || nn.is_negative()) - throw (std::range_error("numeric::bernoulli(): argument must be integer >= 0")); - if (nn.is_zero()) - return numONE(); - if (!nn.compare(numONE())) - return numeric(-1,2); - if (nn.is_odd()) - return numZERO(); - // Until somebody has the Blues and comes up with a much better idea and - // codes it (preferably in CLN) we make this a remembering function which - // computes its results using the formula - // B(nn) == - 1/(nn+1) * sum_{k=0}^{nn-1}(binomial(nn+1,k)*B(k)) - // whith B(0) == 1. - static vector results; - static int highest_result = -1; - int n = nn.sub(numTWO()).div(numTWO()).to_int(); - if (n <= highest_result) - return results[n]; - if (results.capacity() < (unsigned)(n+1)) - results.reserve(n+1); - - numeric tmp; // used to store the sum - for (int i=highest_result+1; i<=n; ++i) { - // the first two elements: - tmp = numeric(-2*i-1,2); - // accumulate the remaining elements: - for (int j=0; j CLN -} +const numeric bernoulli(const numeric &nn) +{ + if (!nn.is_integer() || nn.is_negative()) + throw std::range_error("numeric::bernoulli(): argument must be integer >= 0"); + + // Method: + // + // The Bernoulli numbers are rational numbers that may be computed using + // the relation + // + // B_n = - 1/(n+1) * sum_{k=0}^{n-1}(binomial(n+1,k)*B_k) + // + // with B(0) = 1. Since the n'th Bernoulli number depends on all the + // previous ones, the computation is necessarily very expensive. There are + // several other ways of computing them, a particularly good one being + // cl_I s = 1; + // cl_I c = n+1; + // cl_RA Bern = 0; + // for (unsigned i=0; i results; + static unsigned next_r = 0; + + // algorithm not applicable to B(2), so just store it + if (!next_r) { + results.push_back(cln::recip(cln::cl_RA(6))); + next_r = 4; + } + if (n= 1, n >= 0. + // + // (Proof: For fixed m, the LHS and the RHS satisfy the same recurrence + // w.r.t. n, and the initial values (n=0, n=1) agree. Hence all values + // agree.) + // Replace m by m+1: + // F(n+m+1) = F(m)*F(n) + F(m+1)*F(n+1) for m >= 0, n >= 0 + // Now put in m = n, to get + // F(2n) = (F(n+1)-F(n))*F(n) + F(n)*F(n+1) = F(n)*(2*F(n+1) - F(n)) + // F(2n+1) = F(n)^2 + F(n+1)^2 + // hence + // F(2n+2) = F(n+1)*(2*F(n) + F(n+1)) + if (n.is_zero()) + return *_num0_p; + if (n.is_negative()) + if (n.is_even()) + return -fibonacci(-n); + else + return fibonacci(-n); + + cln::cl_I u(0); + cln::cl_I v(1); + cln::cl_I m = cln::the(n.to_cl_N()) >> 1L; // floor(n/2); + for (uintL bit=cln::integer_length(m); bit>0; --bit) { + // Since a squaring is cheaper than a multiplication, better use + // three squarings instead of one multiplication and two squarings. + cln::cl_I u2 = cln::square(u); + cln::cl_I v2 = cln::square(v); + if (cln::logbitp(bit-1, m)) { + v = cln::square(u + v) - u2; + u = u2 + v2; + } else { + u = v2 - cln::square(v - u); + v = u2 + v2; + } + } + if (n.is_even()) + // Here we don't use the squaring formula because one multiplication + // is cheaper than two squarings. + return u * ((v << 1) - u); + else + return cln::square(u) + cln::square(v); +} + + +///** Absolute value. */ +//const numeric abs(const numeric& x) +//{ +// return cln::abs(x.to_cl_N()); +//} + /** Modulus (in positive representation). * In general, mod(a,b) has the sign of b or is zero, and rem(a,b) has the @@ -1244,193 +1609,249 @@ numeric abs(numeric const & x) * * @return a mod b in the range [0,abs(b)-1] with sign of b if both are * integer, 0 otherwise. */ -numeric mod(numeric const & a, numeric const & b) +const numeric mod(const numeric &a, const numeric &b) { - if (a.is_integer() && b.is_integer()) { - return ::mod(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN - } - else { - return numZERO(); // Throw? - } + if (a.is_integer() && b.is_integer()) + return cln::mod(cln::the(a.to_cl_N()), + cln::the(b.to_cl_N())); + else + return *_num0_p; } + /** Modulus (in symmetric representation). * Equivalent to Maple's mods. * - * @return a mod b in the range [-iquo(abs(m)-1,2), iquo(abs(m),2)]. */ -numeric smod(numeric const & a, numeric const & b) + * @return a mod b in the range [-iquo(abs(b)-1,2), iquo(abs(b),2)]. */ +const numeric smod(const numeric &a, const numeric &b) { - if (a.is_integer() && b.is_integer()) { - cl_I b2 = The(cl_I)(ceiling1(The(cl_I)(*b.value) / 2)) - 1; - return ::mod(The(cl_I)(*a.value) + b2, The(cl_I)(*b.value)) - b2; - } else { - return numZERO(); // Throw? - } + if (a.is_integer() && b.is_integer()) { + const cln::cl_I b2 = cln::ceiling1(cln::the(b.to_cl_N()) >> 1) - 1; + return cln::mod(cln::the(a.to_cl_N()) + b2, + cln::the(b.to_cl_N())) - b2; + } else + return *_num0_p; } + /** Numeric integer remainder. * Equivalent to Maple's irem(a,b) as far as sign conventions are concerned. * In general, mod(a,b) has the sign of b or is zero, and irem(a,b) has the * sign of a or is zero. * - * @return remainder of a/b if both are integer, 0 otherwise. */ -numeric irem(numeric const & a, numeric const & b) + * @return remainder of a/b if both are integer, 0 otherwise. + * @exception overflow_error (division by zero) if b is zero. */ +const numeric irem(const numeric &a, const numeric &b) { - if (a.is_integer() && b.is_integer()) { - return ::rem(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN - } - else { - return numZERO(); // Throw? - } + if (b.is_zero()) + throw std::overflow_error("numeric::irem(): division by zero"); + if (a.is_integer() && b.is_integer()) + return cln::rem(cln::the(a.to_cl_N()), + cln::the(b.to_cl_N())); + else + return *_num0_p; } + /** Numeric integer remainder. * Equivalent to Maple's irem(a,b,'q') it obeyes the relation * irem(a,b,q) == a - q*b. In general, mod(a,b) has the sign of b or is zero, - * and irem(a,b) has the sign of a or is zero. + * and irem(a,b) has the sign of a or is zero. * * @return remainder of a/b and quotient stored in q if both are integer, - * 0 otherwise. */ -numeric irem(numeric const & a, numeric const & b, numeric & q) + * 0 otherwise. + * @exception overflow_error (division by zero) if b is zero. */ +const numeric irem(const numeric &a, const numeric &b, numeric &q) { - if (a.is_integer() && b.is_integer()) { // -> CLN - cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value)); - q = rem_quo.quotient; - return rem_quo.remainder; - } - else { - q = numZERO(); - return numZERO(); // Throw? - } + if (b.is_zero()) + throw std::overflow_error("numeric::irem(): division by zero"); + if (a.is_integer() && b.is_integer()) { + const cln::cl_I_div_t rem_quo = cln::truncate2(cln::the(a.to_cl_N()), + cln::the(b.to_cl_N())); + q = rem_quo.quotient; + return rem_quo.remainder; + } else { + q = *_num0_p; + return *_num0_p; + } } + /** Numeric integer quotient. * Equivalent to Maple's iquo as far as sign conventions are concerned. * - * @return truncated quotient of a/b if both are integer, 0 otherwise. */ -numeric iquo(numeric const & a, numeric const & b) + * @return truncated quotient of a/b if both are integer, 0 otherwise. + * @exception overflow_error (division by zero) if b is zero. */ +const numeric iquo(const numeric &a, const numeric &b) { - if (a.is_integer() && b.is_integer()) { - return truncate1(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN - } else { - return numZERO(); // Throw? - } + if (b.is_zero()) + throw std::overflow_error("numeric::iquo(): division by zero"); + if (a.is_integer() && b.is_integer()) + return cln::truncate1(cln::the(a.to_cl_N()), + cln::the(b.to_cl_N())); + else + return *_num0_p; } + /** Numeric integer quotient. * Equivalent to Maple's iquo(a,b,'r') it obeyes the relation * r == a - iquo(a,b,r)*b. * * @return truncated quotient of a/b and remainder stored in r if both are - * integer, 0 otherwise. */ -numeric iquo(numeric const & a, numeric const & b, numeric & r) + * integer, 0 otherwise. + * @exception overflow_error (division by zero) if b is zero. */ +const numeric iquo(const numeric &a, const numeric &b, numeric &r) { - if (a.is_integer() && b.is_integer()) { // -> CLN - cl_I_div_t rem_quo = truncate2(The(cl_I)(*a.value), The(cl_I)(*b.value)); - r = rem_quo.remainder; - return rem_quo.quotient; - } else { - r = numZERO(); - return numZERO(); // Throw? - } + if (b.is_zero()) + throw std::overflow_error("numeric::iquo(): division by zero"); + if (a.is_integer() && b.is_integer()) { + const cln::cl_I_div_t rem_quo = cln::truncate2(cln::the(a.to_cl_N()), + cln::the(b.to_cl_N())); + r = rem_quo.remainder; + return rem_quo.quotient; + } else { + r = *_num0_p; + return *_num0_p; + } } -/** Numeric square root. - * If possible, sqrt(z) should respect squares of exact numbers, i.e. sqrt(4) - * should return integer 2. - * - * @param z numeric argument - * @return square root of z. Branch cut along negative real axis, the negative - * real axis itself where imag(z)==0 and real(z)<0 belongs to the upper part - * where imag(z)>0. */ -numeric sqrt(numeric const & z) -{ - return ::sqrt(*z.value); // -> CLN -} - -/** Integer numeric square root. */ -numeric isqrt(numeric const & x) -{ - if (x.is_integer()) { - cl_I root; - ::isqrt(The(cl_I)(*x.value), &root); // -> CLN - return root; - } else - return numZERO(); // Throw? -} /** Greatest Common Divisor. * * @return The GCD of two numbers if both are integer, a numerical 1 * if they are not. */ -numeric gcd(numeric const & a, numeric const & b) +const numeric gcd(const numeric &a, const numeric &b) { - if (a.is_integer() && b.is_integer()) - return ::gcd(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN - else - return numONE(); + if (a.is_integer() && b.is_integer()) + return cln::gcd(cln::the(a.to_cl_N()), + cln::the(b.to_cl_N())); + else + return *_num1_p; } + /** Least Common Multiple. * * @return The LCM of two numbers if both are integer, the product of those * two numbers if they are not. */ -numeric lcm(numeric const & a, numeric const & b) +const numeric lcm(const numeric &a, const numeric &b) +{ + if (a.is_integer() && b.is_integer()) + return cln::lcm(cln::the(a.to_cl_N()), + cln::the(b.to_cl_N())); + else + return a.mul(b); +} + + +/** Numeric square root. + * If possible, sqrt(x) should respect squares of exact numbers, i.e. sqrt(4) + * should return integer 2. + * + * @param x numeric argument + * @return square root of x. Branch cut along negative real axis, the negative + * real axis itself where imag(x)==0 and real(x)<0 belongs to the upper part + * where imag(x)>0. */ +const numeric sqrt(const numeric &x) { - if (a.is_integer() && b.is_integer()) - return ::lcm(The(cl_I)(*a.value), The(cl_I)(*b.value)); // -> CLN - else - return *a.value * *b.value; + return cln::sqrt(x.to_cl_N()); +} + + +/** Integer numeric square root. */ +const numeric isqrt(const numeric &x) +{ + if (x.is_integer()) { + cln::cl_I root; + cln::isqrt(cln::the(x.to_cl_N()), &root); + return root; + } else + return *_num0_p; } -ex PiEvalf(void) + +/** Floating point evaluation of Archimedes' constant Pi. */ +ex PiEvalf() { - return numeric(cl_pi(cl_default_float_format)); // -> CLN + return numeric(cln::pi(cln::default_float_format)); } -ex EulerGammaEvalf(void) + +/** Floating point evaluation of Euler's constant gamma. */ +ex EulerEvalf() { - return numeric(cl_eulerconst(cl_default_float_format)); // -> CLN + return numeric(cln::eulerconst(cln::default_float_format)); } -ex CatalanEvalf(void) + +/** Floating point evaluation of Catalan's constant. */ +ex CatalanEvalf() { - return numeric(cl_catalanconst(cl_default_float_format)); // -> CLN + return numeric(cln::catalanconst(cln::default_float_format)); } -// It initializes to 17 digits, because in CLN cl_float_format(17) turns out to -// be 61 (<64) while cl_float_format(18)=65. We want to have a cl_LF instead -// of cl_SF, cl_FF or cl_DF but everything else is basically arbitrary. + +/** _numeric_digits default ctor, checking for singleton invariance. */ _numeric_digits::_numeric_digits() - : digits(17) + : digits(17) { - assert(!too_late); - too_late = true; - cl_default_float_format = cl_float_format(17); + // It initializes to 17 digits, because in CLN float_format(17) turns out + // to be 61 (<64) while float_format(18)=65. The reason is we want to + // have a cl_LF instead of cl_SF, cl_FF or cl_DF. + if (too_late) + throw(std::runtime_error("I told you not to do instantiate me!")); + too_late = true; + cln::default_float_format = cln::float_format(17); + + // add callbacks for built-in functions + // like ... add_callback(Li_lookuptable); } + +/** Assign a native long to global Digits object. */ _numeric_digits& _numeric_digits::operator=(long prec) { - digits=prec; - cl_default_float_format = cl_float_format(prec); - return *this; + long digitsdiff = prec - digits; + digits = prec; + cln::default_float_format = cln::float_format(prec); + + // call registered callbacks + std::vector::const_iterator it = callbacklist.begin(), end = callbacklist.end(); + for (; it != end; ++it) { + (*it)(digitsdiff); + } + + return *this; } + +/** Convert global Digits object to native type long. */ _numeric_digits::operator long() { - return (long)digits; + // BTW, this is approx. unsigned(cln::default_float_format*0.301)-1 + return (long)digits; } -void _numeric_digits::print(ostream & os) const + +/** Append global Digits object to ostream. */ +void _numeric_digits::print(std::ostream &os) const { - debugmsg("_numeric_digits print", LOGLEVEL_PRINT); - os << digits; + os << digits; } -ostream& operator<<(ostream& os, _numeric_digits const & e) + +/** Add a new callback function. */ +void _numeric_digits::add_callback(digits_changed_callback callback) { - e.print(os); - return os; + callbacklist.push_back(callback); +} + + +std::ostream& operator<<(std::ostream &os, const _numeric_digits &e) +{ + e.print(os); + return os; } ////////// @@ -1441,6 +1862,7 @@ ostream& operator<<(ostream& os, _numeric_digits const & e) bool _numeric_digits::too_late = false; + /** Accuracy in decimal digits. Only object of this type! Can be set using * assignment from C++ unsigned ints and evaluated like any built-in type. */ _numeric_digits Digits; diff --git a/ginac/numeric.h b/ginac/numeric.h index 88b7d953..ce4c7264 100644 --- a/ginac/numeric.h +++ b/ginac/numeric.h @@ -3,7 +3,7 @@ * Makes the interface to the underlying bignum package available. */ /* - * GiNaC Copyright (C) 1999 Johannes Gutenberg University Mainz, Germany + * GiNaC Copyright (C) 1999-2006 Johannes Gutenberg University Mainz, Germany * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -17,26 +17,38 @@ * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef __GINAC_NUMERIC_H__ #define __GINAC_NUMERIC_H__ -#include -#include -#include +#include "basic.h" +#include "ex.h" -class cl_N; // We want to include cln.h only in numeric.cpp in order to - // avoid namespace pollution and keep compile-time low. +#include +#include + +#include + +#if defined(G__CINTVERSION) && !defined(__MAKECINT__) +// Cint @$#$! doesn't like forward declaring classes used for casting operators +// so we have to include the definition of cln::cl_N here, but it is enough to +// do so for the compiler, hence the !defined(__MAKECINT__). + #include +#endif namespace GiNaC { -#define HASHVALUE_NUMERIC 0x80000001U +/** Function pointer to implement callbacks in the case 'Digits' gets changed. + * Main purpose of such callbacks is to adjust look-up tables of certain + * functions to the new precision. Parameter contains the signed difference + * between new Digits and old Digits. */ +typedef void (* digits_changed_callback)(long); -/** This class is used to instantiate a global object Digits which - * behaves just like Maple's Digits. We need an object rather than a - * dumber basic type since as a side-effect we let it change +/** This class is used to instantiate a global singleton object Digits + * which behaves just like Maple's Digits. We need an object rather + * than a dumber basic type since as a side-effect we let it change * cl_default_float_format when it gets changed. The only other * meaningful thing to do with it is converting it to an unsigned, * for temprary storing its value e.g. The user must not create an @@ -47,286 +59,248 @@ class _numeric_digits { // member functions public: - _numeric_digits(); - _numeric_digits& operator=(long prec); - operator long(); - void print(ostream & os) const; + _numeric_digits(); + _numeric_digits& operator=(long prec); + operator long(); + void print(std::ostream& os) const; + void add_callback(digits_changed_callback callback); // member variables private: - long digits; - static bool too_late; + long digits; ///< Number of decimal digits + static bool too_late; ///< Already one object present + // Holds a list of functions that get called when digits is changed. + std::vector callbacklist; +}; + + +/** Exception class thrown when a singularity is encountered. */ +class pole_error : public std::domain_error { +public: + explicit pole_error(const std::string& what_arg, int degree); + int degree() const; +private: + int deg; }; + /** This class is a wrapper around CLN-numbers within the GiNaC class * hierarchy. Objects of this type may directly be created by the user.*/ class numeric : public basic { -// friends - friend numeric exp(numeric const & x); - friend numeric log(numeric const & x); - friend numeric sin(numeric const & x); - friend numeric cos(numeric const & x); - friend numeric tan(numeric const & x); - friend numeric asin(numeric const & x); - friend numeric acos(numeric const & x); - friend numeric atan(numeric const & x); - friend numeric atan(numeric const & y, numeric const & x); - friend numeric sinh(numeric const & x); - friend numeric cosh(numeric const & x); - friend numeric tanh(numeric const & x); - friend numeric asinh(numeric const & x); - friend numeric acosh(numeric const & x); - friend numeric atanh(numeric const & x); - friend numeric bernoulli(numeric const & n); - friend numeric abs(numeric const & x); - friend numeric mod(numeric const & a, numeric const & b); - friend numeric smod(numeric const & a, numeric const & b); - friend numeric irem(numeric const & a, numeric const & b); - friend numeric irem(numeric const & a, numeric const & b, numeric & q); - friend numeric iquo(numeric const & a, numeric const & b); - friend numeric iquo(numeric const & a, numeric const & b, numeric & r); - friend numeric sqrt(numeric const & x); - friend numeric isqrt(numeric const & x); - friend numeric gcd(numeric const & a, numeric const & b); - friend numeric lcm(numeric const & a, numeric const & b); - friend numeric const & numZERO(void); - friend numeric const & numONE(void); - friend numeric const & numTWO(void); - friend numeric const & numTHREE(void); - friend numeric const & numMINUSONE(void); - friend numeric const & numHALF(void); - + GINAC_DECLARE_REGISTERED_CLASS(numeric, basic) + // member functions - - // default constructor, destructor, copy constructor assignment - // operator and helpers -public: - numeric(); - ~numeric(); - numeric(numeric const & other); - numeric const & operator=(numeric const & other); -protected: - void copy(numeric const & other); - void destroy(bool call_parent); - - // other constructors + + // other constructors public: - explicit numeric(int i); - explicit numeric(unsigned int i); - explicit numeric(long i); - explicit numeric(unsigned long i); - explicit numeric(long numer, long denom); - explicit numeric(double d); - explicit numeric(char const *); - numeric(cl_N const & z); - - // functions overriding virtual functions from bases classes + numeric(int i); + numeric(unsigned int i); + numeric(long i); + numeric(unsigned long i); + numeric(long numer, long denom); + numeric(double d); + numeric(const char *); + + // functions overriding virtual functions from base classes public: - basic * duplicate() const; - void printraw(ostream & os) const; - void printtree(ostream & os, unsigned indent) const; - void print(ostream & os, unsigned precedence=0) const; - void printcsrc(ostream & os, unsigned type, unsigned precedence=0) const; - bool info(unsigned inf) const; - ex evalf(int level=0) const; - ex diff(symbol const & s) const; - ex normal(lst &sym_lst, lst &repl_lst, int level=0) const; - numeric integer_content(void) const; - ex smod(numeric const &xi) const; - numeric max_coefficient(void) const; + unsigned precedence() const {return 30;} + bool info(unsigned inf) const; + bool is_polynomial(const ex & var) const; + int degree(const ex & s) const; + int ldegree(const ex & s) const; + ex coeff(const ex & s, int n = 1) const; + bool has(const ex &other, unsigned options = 0) const; + ex eval(int level = 0) const; + ex evalf(int level = 0) const; + ex subs(const exmap & m, unsigned options = 0) const { return subs_one_level(m, options); } // overwrites basic::subs() for performance reasons + ex normal(exmap & repl, exmap & rev_lookup, int level = 0) const; + ex to_rational(exmap & repl) const; + ex to_polynomial(exmap & repl) const; + numeric integer_content() const; + ex smod(const numeric &xi) const; + numeric max_coefficient() const; + ex conjugate() const; protected: - int compare_same_type(basic const & other) const; - bool is_equal_same_type(basic const & other) const; - unsigned calchash(void) const { - hashvalue=HASHVALUE_NUMERIC; - return HASHVALUE_NUMERIC; - } - - // new virtual functions which can be overridden by derived classes - // (none) - - // non-virtual functions in this class + /** Implementation of ex::diff for a numeric always returns 0. + * @see ex::diff */ + ex derivative(const symbol &s) const { return 0; } + bool is_equal_same_type(const basic &other) const; + unsigned calchash() const; + + // new virtual functions which can be overridden by derived classes + // (none) + + // non-virtual functions in this class public: - numeric add(numeric const & other) const; - numeric sub(numeric const & other) const; - numeric mul(numeric const & other) const; - numeric div(numeric const & other) const; - numeric power(numeric const & other) const; - numeric const & add_dyn(numeric const & other) const; - numeric const & sub_dyn(numeric const & other) const; - numeric const & mul_dyn(numeric const & other) const; - numeric const & div_dyn(numeric const & other) const; - numeric const & power_dyn(numeric const & other) const; - numeric const & operator=(int i); - numeric const & operator=(unsigned int i); - numeric const & operator=(long i); - numeric const & operator=(unsigned long i); - numeric const & operator=(double d); - numeric const & operator=(char const * s); - /* - numeric add_dyn(numeric const & other) const { return add(other); } - numeric sub_dyn(numeric const & other) const { return sub(other); } - numeric mul_dyn(numeric const & other) const { return mul(other); } - numeric div_dyn(numeric const & other) const { return div(other); } - numeric power_dyn(numeric const & other) const { return power(other); } - */ - numeric inverse(void) const; - int csgn(void) const; - int compare(numeric const & other) const; - bool is_equal(numeric const & other) const; - bool is_zero(void) const; - bool is_positive(void) const; - bool is_negative(void) const; - bool is_integer(void) const; - bool is_pos_integer(void) const; - bool is_nonneg_integer(void) const; - bool is_even(void) const; - bool is_odd(void) const; - bool is_prime(void) const; - bool is_rational(void) const; - bool is_real(void) const; - bool operator==(numeric const & other) const; - bool operator!=(numeric const & other) const; - bool operator<(numeric const & other) const; - bool operator<=(numeric const & other) const; - bool operator>(numeric const & other) const; - bool operator>=(numeric const & other) const; - int to_int(void) const; - double to_double(void) const; - numeric real(void) const; - numeric imag(void) const; - numeric numer(void) const; - numeric denom(void) const; - int int_length(void) const; + const numeric add(const numeric &other) const; + const numeric sub(const numeric &other) const; + const numeric mul(const numeric &other) const; + const numeric div(const numeric &other) const; + const numeric power(const numeric &other) const; + const numeric & add_dyn(const numeric &other) const; + const numeric & sub_dyn(const numeric &other) const; + const numeric & mul_dyn(const numeric &other) const; + const numeric & div_dyn(const numeric &other) const; + const numeric & power_dyn(const numeric &other) const; + const numeric & operator=(int i); + const numeric & operator=(unsigned int i); + const numeric & operator=(long i); + const numeric & operator=(unsigned long i); + const numeric & operator=(double d); + const numeric & operator=(const char *s); + const numeric inverse() const; + numeric step() const; + int csgn() const; + int compare(const numeric &other) const; + bool is_equal(const numeric &other) const; + bool is_zero() const; + bool is_positive() const; + bool is_negative() const; + bool is_integer() const; + bool is_pos_integer() const; + bool is_nonneg_integer() const; + bool is_even() const; + bool is_odd() const; + bool is_prime() const; + bool is_rational() const; + bool is_real() const; + bool is_cinteger() const; + bool is_crational() const; + bool operator==(const numeric &other) const; + bool operator!=(const numeric &other) const; + bool operator<(const numeric &other) const; + bool operator<=(const numeric &other) const; + bool operator>(const numeric &other) const; + bool operator>=(const numeric &other) const; + int to_int() const; + long to_long() const; + double to_double() const; + cln::cl_N to_cl_N() const; + const numeric real() const; + const numeric imag() const; + const numeric numer() const; + const numeric denom() const; + int int_length() const; + // converting routines for interfacing with CLN: + numeric(const cln::cl_N &z); + +protected: + void print_numeric(const print_context & c, const char *par_open, const char *par_close, const char *imag_sym, const char *mul_sym, unsigned level) const; + void do_print(const print_context & c, unsigned level) const; + void do_print_latex(const print_latex & c, unsigned level) const; + void do_print_csrc(const print_csrc & c, unsigned level) const; + void do_print_csrc_cl_N(const print_csrc_cl_N & c, unsigned level) const; + void do_print_tree(const print_tree & c, unsigned level) const; + void do_print_python_repr(const print_python_repr & c, unsigned level) const; // member variables protected: - static unsigned precedence; - cl_N *value; + cln::cl_N value; }; + // global constants -extern const numeric some_numeric; extern const numeric I; -extern type_info const & typeid_numeric; extern _numeric_digits Digits; -#define is_a_numeric_hash(x) ((x)==HASHVALUE_NUMERIC) -// may have to be changed to ((x)>=0x80000000U) - // global functions -numeric const & numZERO(void); -numeric const & numONE(void); -numeric const & numTWO(void); -numeric const & numMINUSONE(void); -numeric const & numHALF(void); - -numeric exp(numeric const & x); -numeric log(numeric const & x); -numeric sin(numeric const & x); -numeric cos(numeric const & x); -numeric tan(numeric const & x); -numeric asin(numeric const & x); -numeric acos(numeric const & x); -numeric atan(numeric const & x); -numeric atan(numeric const & y, numeric const & x); -numeric sinh(numeric const & x); -numeric cosh(numeric const & x); -numeric tanh(numeric const & x); -numeric asinh(numeric const & x); -numeric acosh(numeric const & x); -numeric atanh(numeric const & x); -numeric zeta(numeric const & x); -numeric gamma(numeric const & x); -numeric psi(numeric const & n, numeric const & x); -numeric factorial(numeric const & n); -numeric doublefactorial(numeric const & n); -numeric binomial(numeric const & n, numeric const & k); -numeric bernoulli(numeric const & n); - -numeric abs(numeric const & x); -numeric mod(numeric const & a, numeric const & b); -numeric smod(numeric const & a, numeric const & b); -numeric irem(numeric const & a, numeric const & b); -numeric irem(numeric const & a, numeric const & b, numeric & q); -numeric iquo(numeric const & a, numeric const & b); -numeric iquo(numeric const & a, numeric const & b, numeric & r); -numeric sqrt(numeric const & x); -numeric isqrt(numeric const & x); - -numeric gcd(numeric const & a, numeric const & b); -numeric lcm(numeric const & a, numeric const & b); - -/** Exception thrown by numeric members to signal failure */ -struct numeric_fail -{ - int failval; - numeric_fail(int n) { failval = n; } -}; +//-- to go ... +const numeric Li2(const numeric &x); +const numeric zeta(const numeric &x); +const numeric doublefactorial(const numeric &n); +const numeric bernoulli(const numeric &n); +const numeric fibonacci(const numeric &n); +//-- +const numeric isqrt(const numeric &x); +const numeric sqrt(const numeric &x); +const numeric mod(const numeric &a, const numeric &b); +const numeric smod(const numeric &a, const numeric &b); +const numeric irem(const numeric &a, const numeric &b); +const numeric irem(const numeric &a, const numeric &b, numeric &q); +const numeric iquo(const numeric &a, const numeric &b); +const numeric iquo(const numeric &a, const numeric &b, numeric &r); +const numeric gcd(const numeric &a, const numeric &b); +const numeric lcm(const numeric &a, const numeric &b); // wrapper functions around member functions -inline numeric inverse(numeric const & x) -{ return x.inverse(); } +inline const numeric pow(const numeric &x, const numeric &y) +{ return x.power(y); } -inline bool csgn(numeric const & x) -{ return x.csgn(); } +inline const numeric inverse(const numeric &x) +{ return x.inverse(); } -inline bool is_zero(numeric const & x) +inline bool is_zero(const numeric &x) { return x.is_zero(); } -inline bool is_positive(numeric const & x) +inline bool is_positive(const numeric &x) { return x.is_positive(); } -inline bool is_integer(numeric const & x) +inline bool is_integer(const numeric &x) { return x.is_integer(); } -inline bool is_pos_integer(numeric const & x) +inline bool is_pos_integer(const numeric &x) { return x.is_pos_integer(); } -inline bool is_nonneg_integer(numeric const & x) +inline bool is_nonneg_integer(const numeric &x) { return x.is_nonneg_integer(); } -inline bool is_even(numeric const & x) +inline bool is_even(const numeric &x) { return x.is_even(); } -inline bool is_odd(numeric const & x) +inline bool is_odd(const numeric &x) { return x.is_odd(); } -inline bool is_prime(numeric const & x) +inline bool is_prime(const numeric &x) { return x.is_prime(); } -inline bool is_rational(numeric const & x) +inline bool is_rational(const numeric &x) { return x.is_rational(); } -inline bool is_real(numeric const & x) +inline bool is_real(const numeric &x) { return x.is_real(); } -inline numeric real(numeric const & x) +inline bool is_cinteger(const numeric &x) +{ return x.is_cinteger(); } + +inline bool is_crational(const numeric &x) +{ return x.is_crational(); } + +inline int to_int(const numeric &x) +{ return x.to_int(); } + +inline long to_long(const numeric &x) +{ return x.to_long(); } + +inline double to_double(const numeric &x) +{ return x.to_double(); } + +inline const numeric real(const numeric &x) { return x.real(); } -inline numeric imag(numeric const & x) +inline const numeric imag(const numeric &x) { return x.imag(); } -inline numeric numer(numeric const & x) +inline const numeric numer(const numeric &x) { return x.numer(); } -inline numeric denom(numeric const & x) +inline const numeric denom(const numeric &x) { return x.denom(); } -ex IEvalf(void); -ex PiEvalf(void); -ex EulerGammaEvalf(void); -ex CatalanEvalf(void); +// numeric evaluation functions for class constant objects: + +ex PiEvalf(); +ex EulerEvalf(); +ex CatalanEvalf(); -// utility functions -inline const numeric &ex_to_numeric(const ex &e) -{ - return static_cast(*e.bp); -} } // namespace GiNaC +#ifdef __MAKECINT__ +#pragma link off defined_in cln/number.h; +#pragma link off defined_in cln/complex_class.h; +#endif + #endif // ndef __GINAC_NUMERIC_H__ diff --git a/ginac/power.cpp b/ginac/power.cpp index ce477e2a..7d0762c8 100644 --- a/ginac/power.cpp +++ b/ginac/power.cpp @@ -33,6 +33,7 @@ #include "numeric.h" #include "constant.h" #include "operators.h" +#include "inifcns.h" // for binomial() #include "inifcns_exp.h" // for log() in power::derivative() #include "matrix.h" #include "indexed.h" @@ -461,7 +462,7 @@ ex power::eval(int level) const if (is_exactly_a(sub_exponent)) { const numeric & num_sub_exponent = ex_to(sub_exponent); GINAC_ASSERT(num_sub_exponent!=numeric(1)); - if (num_exponent->is_integer() || (abs(num_sub_exponent) - (*_num1_p)).is_negative()) + if (num_exponent->is_integer() || (abs_function::eval_numeric(num_sub_exponent) - (*_num1_p)).is_negative()) return power(sub_basis,num_sub_exponent.mul(*num_exponent)); } } @@ -494,7 +495,7 @@ ex power::eval(int level) const mulp->clearflag(status_flags::evaluated); mulp->clearflag(status_flags::hash_calculated); return (new mul(power(*mulp,exponent), - power(abs(num_coeff),*num_exponent)))->setflag(status_flags::dynallocated); + power(abs_function::eval_numeric(num_coeff),*num_exponent)))->setflag(status_flags::dynallocated); } } } @@ -744,7 +745,7 @@ ex power::expand_add(const add & a, int n, unsigned options) const // i.e. the number of unordered arrangements of m nonnegative integers // which sum up to n. It is frequently written as C_n(m) and directly // related with binomial coefficients: - result.reserve(binomial(numeric(n+m-1), numeric(m-1)).to_int()); + result.reserve(binomial::eval_numeric(numeric(n+m-1), numeric(m-1)).to_int()); intvector k(m-1); intvector k_cum(m-1); // k_cum[l]:=sum(i=0,l,k[l]); intvector upper_limit(m-1); @@ -787,9 +788,9 @@ ex power::expand_add(const add & a, int n, unsigned options) const else term.push_back(power(b,n-k_cum[m-2])); - numeric f = binomial(numeric(n),numeric(k[0])); + numeric f = binomial::eval_numeric(numeric(n),numeric(k[0])); for (l=1; l(i->rest)) { + if (!is_exactly_a(i->rest)) { // print 'rest', i.e. the expansion coefficient if (i->rest.info(info_flags::numeric) && @@ -267,7 +267,7 @@ ex pseries::op(size_t i) const if (i >= seq.size()) throw (std::out_of_range("op() out of range")); - if (is_exactly_a(seq[i].rest)) + if (is_exactly_a(seq[i].rest)) return Order(power(var-point, seq[i].coeff)); return seq[i].rest * power(var - point, seq[i].coeff); } @@ -499,7 +499,7 @@ ex pseries::derivative(const symbol & s) const // FIXME: coeff might depend on var while (it != itend) { - if (is_exactly_a(it->rest)) { + if (is_exactly_a(it->rest)) { new_seq.push_back(expair(it->rest, it->coeff - 1)); } else { ex c = it->rest * it->coeff; @@ -512,7 +512,7 @@ ex pseries::derivative(const symbol & s) const } else { while (it != itend) { - if (is_exactly_a(it->rest)) { + if (is_exactly_a(it->rest)) { new_seq.push_back(*it); } else { ex c = it->rest.diff(s); @@ -532,7 +532,7 @@ ex pseries::convert_to_poly(bool no_order) const epvector::const_iterator it = seq.begin(), itend = seq.end(); while (it != itend) { - if (is_exactly_a(it->rest)) { + if (is_exactly_a(it->rest)) { if (!no_order) e += Order(power(var - point, it->coeff)); } else @@ -544,7 +544,7 @@ ex pseries::convert_to_poly(bool no_order) const bool pseries::is_terminating() const { - return seq.empty() || !is_exactly_a((seq.end()-1)->rest); + return seq.empty() || !is_exactly_a((seq.end()-1)->rest); } ex pseries::coeffop(size_t i) const @@ -679,18 +679,18 @@ ex pseries::add_series(const pseries &other) const if (pow_a < pow_b) { // a has lesser power, get coefficient from a new_seq.push_back(*a); - if (is_exactly_a((*a).rest)) + if (is_exactly_a((*a).rest)) break; ++a; } else if (pow_b < pow_a) { // b has lesser power, get coefficient from b new_seq.push_back(*b); - if (is_exactly_a((*b).rest)) + if (is_exactly_a((*b).rest)) break; ++b; } else { // Add coefficient of a and b - if (is_exactly_a((*a).rest) || is_exactly_a((*b).rest)) { + if (is_exactly_a((*a).rest) || is_exactly_a((*b).rest)) { new_seq.push_back(expair(Order(_ex1), (*a).coeff)); break; // Order term ends the sequence } else { @@ -747,7 +747,7 @@ ex pseries::mul_const(const numeric &other) const epvector::const_iterator it = seq.begin(), itend = seq.end(); while (it != itend) { - if (!is_exactly_a(it->rest)) + if (!is_exactly_a(it->rest)) new_seq.push_back(expair(it->rest * other, it->coeff)); else new_seq.push_back(*it); @@ -788,9 +788,9 @@ ex pseries::mul_series(const pseries &other) const int higher_order_a = INT_MAX; int higher_order_b = INT_MAX; - if (is_exactly_a(coeff(var, a_max))) + if (is_exactly_a(coeff(var, a_max))) higher_order_a = a_max + b_min; - if (is_exactly_a(other.coeff(var, b_max))) + if (is_exactly_a(other.coeff(var, b_max))) higher_order_b = b_max + a_min; int higher_order_c = std::min(higher_order_a, higher_order_b); if (cdeg_max >= higher_order_c) @@ -802,7 +802,7 @@ ex pseries::mul_series(const pseries &other) const for (int i=a_min; cdeg-i>=b_min; ++i) { ex a_coeff = coeff(var, i); ex b_coeff = other.coeff(var, cdeg-i); - if (!is_exactly_a(a_coeff) && !is_exactly_a(b_coeff)) + if (!is_exactly_a(a_coeff) && !is_exactly_a(b_coeff)) co += a_coeff * b_coeff; } if (!co.is_zero()) @@ -937,7 +937,7 @@ ex pseries::power_const(const numeric &p, int deg) const } // O(x^n)^(-m) is undefined - if (seq.size() == 1 && is_exactly_a(seq[0].rest) && p.real().is_negative()) + if (seq.size() == 1 && is_exactly_a(seq[0].rest) && p.real().is_negative()) throw pole_error("pseries::power_const(): division by zero",1); // Compute coefficients of the powered series @@ -948,7 +948,7 @@ ex pseries::power_const(const numeric &p, int deg) const ex sum = _ex0; for (int j=1; j<=i; ++j) { ex c = coeff(var, j + ldeg); - if (is_exactly_a(c)) { + if (is_exactly_a(c)) { co.push_back(Order(_ex1)); break; } else @@ -963,7 +963,7 @@ ex pseries::power_const(const numeric &p, int deg) const for (int i=0; i(co[i])) { + if (is_exactly_a(co[i])) { higher_order = true; break; } @@ -1114,7 +1114,7 @@ ex integral::series(const relational & r, int order, unsigned options) const fseries = f.series(x == (a.subs(r)), order, options); for (size_t i=0; i(fseries).coeffop(i); - if (is_exactly_a(currcoeff)) + if (is_exactly_a(currcoeff)) break; ex currexpon = ex_to(fseries).exponop(i); int orderforf = order-ex_to(currexpon).to_int()-1; @@ -1130,7 +1130,7 @@ ex integral::series(const relational & r, int order, unsigned options) const fseries = f.series(x == (b.subs(r)), order, options); for (size_t i=0; i(fseries).coeffop(i); - if (is_exactly_a(currcoeff)) + if (is_exactly_a(currcoeff)) break; ex currexpon = ex_to(fseries).exponop(i); int orderforf = order-ex_to(currexpon).to_int()-1; diff --git a/ginac/symbol.cpp b/ginac/symbol.cpp index 5e39ea59..8a05c8e6 100644 --- a/ginac/symbol.cpp +++ b/ginac/symbol.cpp @@ -220,7 +220,7 @@ ex symbol::eval(int level) const ex symbol::conjugate() const { if (this->domain == domain::complex) { - return GiNaC::conjugate(*this); + return GiNaC::conjugate(*this).hold(); } else { return *this; } diff --git a/ginac/symmetry.cpp b/ginac/symmetry.cpp index 10157e0f..847b441f 100644 --- a/ginac/symmetry.cpp +++ b/ginac/symmetry.cpp @@ -438,7 +438,7 @@ static ex symm(const ex & e, exvector::const_iterator first, exvector::const_ite delete[] iv; delete[] iv2; - return sum / factorial(numeric(num)); + return sum / factorial::eval_numeric(numeric(num)); } ex symmetrize(const ex & e, exvector::const_iterator first, exvector::const_iterator last) -- 2.45.0