3 * Implementation of GiNaC's initially known functions. */
6 * GiNaC Copyright (C) 1999-2016 Johannes Gutenberg University Mainz, Germany
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include "fderivative.h"
31 #include "operators.h"
32 #include "relational.h"
47 static ex conjugate_evalf(const ex & arg)
49 if (is_exactly_a<numeric>(arg)) {
50 return ex_to<numeric>(arg).conjugate();
52 return conjugate_function(arg).hold();
55 static ex conjugate_eval(const ex & arg)
57 return arg.conjugate();
60 static void conjugate_print_latex(const ex & arg, const print_context & c)
62 c.s << "\\bar{"; arg.print(c); c.s << "}";
65 static ex conjugate_conjugate(const ex & arg)
70 // If x is real then U.diff(x)-I*V.diff(x) represents both conjugate(U+I*V).diff(x)
71 // and conjugate((U+I*V).diff(x))
72 static ex conjugate_expl_derivative(const ex & arg, const symbol & s)
74 if (s.info(info_flags::real))
75 return conjugate(arg.diff(s));
78 vec_arg.push_back(arg);
79 return fderivative(ex_to<function>(conjugate(arg)).get_serial(),0,vec_arg).hold()*arg.diff(s);
83 static ex conjugate_real_part(const ex & arg)
85 return arg.real_part();
88 static ex conjugate_imag_part(const ex & arg)
90 return -arg.imag_part();
93 static bool func_arg_info(const ex & arg, unsigned inf)
95 // for some functions we can return the info() of its argument
96 // (think of conjugate())
98 case info_flags::polynomial:
99 case info_flags::integer_polynomial:
100 case info_flags::cinteger_polynomial:
101 case info_flags::rational_polynomial:
102 case info_flags::real:
103 case info_flags::rational:
104 case info_flags::integer:
105 case info_flags::crational:
106 case info_flags::cinteger:
107 case info_flags::even:
108 case info_flags::odd:
109 case info_flags::prime:
110 case info_flags::crational_polynomial:
111 case info_flags::rational_function:
112 case info_flags::algebraic:
113 case info_flags::positive:
114 case info_flags::negative:
115 case info_flags::nonnegative:
116 case info_flags::posint:
117 case info_flags::negint:
118 case info_flags::nonnegint:
119 case info_flags::has_indices:
120 return arg.info(inf);
125 static bool conjugate_info(const ex & arg, unsigned inf)
127 return func_arg_info(arg, inf);
130 REGISTER_FUNCTION(conjugate_function, eval_func(conjugate_eval).
131 evalf_func(conjugate_evalf).
132 expl_derivative_func(conjugate_expl_derivative).
133 info_func(conjugate_info).
134 print_func<print_latex>(conjugate_print_latex).
135 conjugate_func(conjugate_conjugate).
136 real_part_func(conjugate_real_part).
137 imag_part_func(conjugate_imag_part).
138 set_name("conjugate","conjugate"));
144 static ex real_part_evalf(const ex & arg)
146 if (is_exactly_a<numeric>(arg)) {
147 return ex_to<numeric>(arg).real();
149 return real_part_function(arg).hold();
152 static ex real_part_eval(const ex & arg)
154 return arg.real_part();
157 static void real_part_print_latex(const ex & arg, const print_context & c)
159 c.s << "\\Re"; arg.print(c); c.s << "";
162 static ex real_part_conjugate(const ex & arg)
164 return real_part_function(arg).hold();
167 static ex real_part_real_part(const ex & arg)
169 return real_part_function(arg).hold();
172 static ex real_part_imag_part(const ex & arg)
177 // If x is real then Re(e).diff(x) is equal to Re(e.diff(x))
178 static ex real_part_expl_derivative(const ex & arg, const symbol & s)
180 if (s.info(info_flags::real))
181 return real_part_function(arg.diff(s));
184 vec_arg.push_back(arg);
185 return fderivative(ex_to<function>(real_part(arg)).get_serial(),0,vec_arg).hold()*arg.diff(s);
189 REGISTER_FUNCTION(real_part_function, eval_func(real_part_eval).
190 evalf_func(real_part_evalf).
191 expl_derivative_func(real_part_expl_derivative).
192 print_func<print_latex>(real_part_print_latex).
193 conjugate_func(real_part_conjugate).
194 real_part_func(real_part_real_part).
195 imag_part_func(real_part_imag_part).
196 set_name("real_part","real_part"));
202 static ex imag_part_evalf(const ex & arg)
204 if (is_exactly_a<numeric>(arg)) {
205 return ex_to<numeric>(arg).imag();
207 return imag_part_function(arg).hold();
210 static ex imag_part_eval(const ex & arg)
212 return arg.imag_part();
215 static void imag_part_print_latex(const ex & arg, const print_context & c)
217 c.s << "\\Im"; arg.print(c); c.s << "";
220 static ex imag_part_conjugate(const ex & arg)
222 return imag_part_function(arg).hold();
225 static ex imag_part_real_part(const ex & arg)
227 return imag_part_function(arg).hold();
230 static ex imag_part_imag_part(const ex & arg)
235 // If x is real then Im(e).diff(x) is equal to Im(e.diff(x))
236 static ex imag_part_expl_derivative(const ex & arg, const symbol & s)
238 if (s.info(info_flags::real))
239 return imag_part_function(arg.diff(s));
242 vec_arg.push_back(arg);
243 return fderivative(ex_to<function>(imag_part(arg)).get_serial(),0,vec_arg).hold()*arg.diff(s);
247 REGISTER_FUNCTION(imag_part_function, eval_func(imag_part_eval).
248 evalf_func(imag_part_evalf).
249 expl_derivative_func(imag_part_expl_derivative).
250 print_func<print_latex>(imag_part_print_latex).
251 conjugate_func(imag_part_conjugate).
252 real_part_func(imag_part_real_part).
253 imag_part_func(imag_part_imag_part).
254 set_name("imag_part","imag_part"));
260 static ex abs_evalf(const ex & arg)
262 if (is_exactly_a<numeric>(arg))
263 return abs(ex_to<numeric>(arg));
265 return abs(arg).hold();
268 static ex abs_eval(const ex & arg)
270 if (is_exactly_a<numeric>(arg))
271 return abs(ex_to<numeric>(arg));
273 if (arg.info(info_flags::nonnegative))
276 if (arg.info(info_flags::negative) || (-arg).info(info_flags::nonnegative))
279 if (is_ex_the_function(arg, abs))
282 if (is_ex_the_function(arg, exp))
283 return exp(arg.op(0).real_part());
285 if (is_exactly_a<power>(arg)) {
286 const ex& base = arg.op(0);
287 const ex& exponent = arg.op(1);
288 if (base.info(info_flags::positive) || exponent.info(info_flags::real))
289 return pow(abs(base), exponent.real_part());
292 if (is_ex_the_function(arg, conjugate_function))
293 return abs(arg.op(0));
295 if (is_ex_the_function(arg, step))
298 return abs(arg).hold();
301 static ex abs_expand(const ex & arg, unsigned options)
303 if ((options & expand_options::expand_transcendental)
304 && is_exactly_a<mul>(arg)) {
306 prodseq.reserve(arg.nops());
307 for (const_iterator i = arg.begin(); i != arg.end(); ++i) {
308 if (options & expand_options::expand_function_args)
309 prodseq.push_back(abs(i->expand(options)));
311 prodseq.push_back(abs(*i));
313 return (new mul(prodseq))->setflag(status_flags::dynallocated | status_flags::expanded);
316 if (options & expand_options::expand_function_args)
317 return abs(arg.expand(options)).hold();
319 return abs(arg).hold();
322 static ex abs_expl_derivative(const ex & arg, const symbol & s)
324 ex diff_arg = arg.diff(s);
325 return (diff_arg*arg.conjugate()+arg*diff_arg.conjugate())/2/abs(arg);
328 static void abs_print_latex(const ex & arg, const print_context & c)
330 c.s << "{|"; arg.print(c); c.s << "|}";
333 static void abs_print_csrc_float(const ex & arg, const print_context & c)
335 c.s << "fabs("; arg.print(c); c.s << ")";
338 static ex abs_conjugate(const ex & arg)
340 return abs(arg).hold();
343 static ex abs_real_part(const ex & arg)
345 return abs(arg).hold();
348 static ex abs_imag_part(const ex& arg)
353 static ex abs_power(const ex & arg, const ex & exp)
355 if ((is_a<numeric>(exp) && ex_to<numeric>(exp).is_even()) || exp.info(info_flags::even)) {
356 if (arg.info(info_flags::real) || arg.is_equal(arg.conjugate()))
357 return power(arg, exp);
359 return power(arg, exp/2)*power(arg.conjugate(), exp/2);
361 return power(abs(arg), exp).hold();
364 bool abs_info(const ex & arg, unsigned inf)
367 case info_flags::integer:
368 case info_flags::even:
369 case info_flags::odd:
370 case info_flags::prime:
371 return arg.info(inf);
372 case info_flags::nonnegint:
373 return arg.info(info_flags::integer);
374 case info_flags::nonnegative:
375 case info_flags::real:
377 case info_flags::negative:
379 case info_flags::positive:
380 return arg.info(info_flags::positive) || arg.info(info_flags::negative);
381 case info_flags::has_indices: {
382 if (arg.info(info_flags::has_indices))
391 REGISTER_FUNCTION(abs, eval_func(abs_eval).
392 evalf_func(abs_evalf).
393 expand_func(abs_expand).
394 expl_derivative_func(abs_expl_derivative).
396 print_func<print_latex>(abs_print_latex).
397 print_func<print_csrc_float>(abs_print_csrc_float).
398 print_func<print_csrc_double>(abs_print_csrc_float).
399 conjugate_func(abs_conjugate).
400 real_part_func(abs_real_part).
401 imag_part_func(abs_imag_part).
402 power_func(abs_power));
408 static ex step_evalf(const ex & arg)
410 if (is_exactly_a<numeric>(arg))
411 return step(ex_to<numeric>(arg));
413 return step(arg).hold();
416 static ex step_eval(const ex & arg)
418 if (is_exactly_a<numeric>(arg))
419 return step(ex_to<numeric>(arg));
421 else if (is_exactly_a<mul>(arg) &&
422 is_exactly_a<numeric>(arg.op(arg.nops()-1))) {
423 numeric oc = ex_to<numeric>(arg.op(arg.nops()-1));
426 // step(42*x) -> step(x)
427 return step(arg/oc).hold();
429 // step(-42*x) -> step(-x)
430 return step(-arg/oc).hold();
432 if (oc.real().is_zero()) {
434 // step(42*I*x) -> step(I*x)
435 return step(I*arg/oc).hold();
437 // step(-42*I*x) -> step(-I*x)
438 return step(-I*arg/oc).hold();
442 return step(arg).hold();
445 static ex step_series(const ex & arg,
446 const relational & rel,
450 const ex arg_pt = arg.subs(rel, subs_options::no_pattern);
451 if (arg_pt.info(info_flags::numeric)
452 && ex_to<numeric>(arg_pt).real().is_zero()
453 && !(options & series_options::suppress_branchcut))
454 throw (std::domain_error("step_series(): on imaginary axis"));
457 seq.push_back(expair(step(arg_pt), _ex0));
458 return pseries(rel,seq);
461 static ex step_conjugate(const ex& arg)
463 return step(arg).hold();
466 static ex step_real_part(const ex& arg)
468 return step(arg).hold();
471 static ex step_imag_part(const ex& arg)
476 REGISTER_FUNCTION(step, eval_func(step_eval).
477 evalf_func(step_evalf).
478 series_func(step_series).
479 conjugate_func(step_conjugate).
480 real_part_func(step_real_part).
481 imag_part_func(step_imag_part));
487 static ex csgn_evalf(const ex & arg)
489 if (is_exactly_a<numeric>(arg))
490 return csgn(ex_to<numeric>(arg));
492 return csgn(arg).hold();
495 static ex csgn_eval(const ex & arg)
497 if (is_exactly_a<numeric>(arg))
498 return csgn(ex_to<numeric>(arg));
500 else if (is_exactly_a<mul>(arg) &&
501 is_exactly_a<numeric>(arg.op(arg.nops()-1))) {
502 numeric oc = ex_to<numeric>(arg.op(arg.nops()-1));
505 // csgn(42*x) -> csgn(x)
506 return csgn(arg/oc).hold();
508 // csgn(-42*x) -> -csgn(x)
509 return -csgn(arg/oc).hold();
511 if (oc.real().is_zero()) {
513 // csgn(42*I*x) -> csgn(I*x)
514 return csgn(I*arg/oc).hold();
516 // csgn(-42*I*x) -> -csgn(I*x)
517 return -csgn(I*arg/oc).hold();
521 return csgn(arg).hold();
524 static ex csgn_series(const ex & arg,
525 const relational & rel,
529 const ex arg_pt = arg.subs(rel, subs_options::no_pattern);
530 if (arg_pt.info(info_flags::numeric)
531 && ex_to<numeric>(arg_pt).real().is_zero()
532 && !(options & series_options::suppress_branchcut))
533 throw (std::domain_error("csgn_series(): on imaginary axis"));
536 seq.push_back(expair(csgn(arg_pt), _ex0));
537 return pseries(rel,seq);
540 static ex csgn_conjugate(const ex& arg)
542 return csgn(arg).hold();
545 static ex csgn_real_part(const ex& arg)
547 return csgn(arg).hold();
550 static ex csgn_imag_part(const ex& arg)
555 static ex csgn_power(const ex & arg, const ex & exp)
557 if (is_a<numeric>(exp) && exp.info(info_flags::positive) && ex_to<numeric>(exp).is_integer()) {
558 if (ex_to<numeric>(exp).is_odd())
559 return csgn(arg).hold();
561 return power(csgn(arg), _ex2).hold();
563 return power(csgn(arg), exp).hold();
567 REGISTER_FUNCTION(csgn, eval_func(csgn_eval).
568 evalf_func(csgn_evalf).
569 series_func(csgn_series).
570 conjugate_func(csgn_conjugate).
571 real_part_func(csgn_real_part).
572 imag_part_func(csgn_imag_part).
573 power_func(csgn_power));
577 // Eta function: eta(x,y) == log(x*y) - log(x) - log(y).
578 // This function is closely related to the unwinding number K, sometimes found
579 // in modern literature: K(z) == (z-log(exp(z)))/(2*Pi*I).
582 static ex eta_evalf(const ex &x, const ex &y)
584 // It seems like we basically have to replicate the eval function here,
585 // since the expression might not be fully evaluated yet.
586 if (x.info(info_flags::positive) || y.info(info_flags::positive))
589 if (x.info(info_flags::numeric) && y.info(info_flags::numeric)) {
590 const numeric nx = ex_to<numeric>(x);
591 const numeric ny = ex_to<numeric>(y);
592 const numeric nxy = ex_to<numeric>(x*y);
594 if (nx.is_real() && nx.is_negative())
596 if (ny.is_real() && ny.is_negative())
598 if (nxy.is_real() && nxy.is_negative())
600 return evalf(I/4*Pi)*((csgn(-imag(nx))+1)*(csgn(-imag(ny))+1)*(csgn(imag(nxy))+1)-
601 (csgn(imag(nx))+1)*(csgn(imag(ny))+1)*(csgn(-imag(nxy))+1)+cut);
604 return eta(x,y).hold();
607 static ex eta_eval(const ex &x, const ex &y)
609 // trivial: eta(x,c) -> 0 if c is real and positive
610 if (x.info(info_flags::positive) || y.info(info_flags::positive))
613 if (x.info(info_flags::numeric) && y.info(info_flags::numeric)) {
614 // don't call eta_evalf here because it would call Pi.evalf()!
615 const numeric nx = ex_to<numeric>(x);
616 const numeric ny = ex_to<numeric>(y);
617 const numeric nxy = ex_to<numeric>(x*y);
619 if (nx.is_real() && nx.is_negative())
621 if (ny.is_real() && ny.is_negative())
623 if (nxy.is_real() && nxy.is_negative())
625 return (I/4)*Pi*((csgn(-imag(nx))+1)*(csgn(-imag(ny))+1)*(csgn(imag(nxy))+1)-
626 (csgn(imag(nx))+1)*(csgn(imag(ny))+1)*(csgn(-imag(nxy))+1)+cut);
629 return eta(x,y).hold();
632 static ex eta_series(const ex & x, const ex & y,
633 const relational & rel,
637 const ex x_pt = x.subs(rel, subs_options::no_pattern);
638 const ex y_pt = y.subs(rel, subs_options::no_pattern);
639 if ((x_pt.info(info_flags::numeric) && x_pt.info(info_flags::negative)) ||
640 (y_pt.info(info_flags::numeric) && y_pt.info(info_flags::negative)) ||
641 ((x_pt*y_pt).info(info_flags::numeric) && (x_pt*y_pt).info(info_flags::negative)))
642 throw (std::domain_error("eta_series(): on discontinuity"));
644 seq.push_back(expair(eta(x_pt,y_pt), _ex0));
645 return pseries(rel,seq);
648 static ex eta_conjugate(const ex & x, const ex & y)
650 return -eta(x, y).hold();
653 static ex eta_real_part(const ex & x, const ex & y)
658 static ex eta_imag_part(const ex & x, const ex & y)
660 return -I*eta(x, y).hold();
663 REGISTER_FUNCTION(eta, eval_func(eta_eval).
664 evalf_func(eta_evalf).
665 series_func(eta_series).
667 set_symmetry(sy_symm(0, 1)).
668 conjugate_func(eta_conjugate).
669 real_part_func(eta_real_part).
670 imag_part_func(eta_imag_part));
677 static ex Li2_evalf(const ex & x)
679 if (is_exactly_a<numeric>(x))
680 return Li2(ex_to<numeric>(x));
682 return Li2(x).hold();
685 static ex Li2_eval(const ex & x)
687 if (x.info(info_flags::numeric)) {
692 if (x.is_equal(_ex1))
693 return power(Pi,_ex2)/_ex6;
694 // Li2(1/2) -> Pi^2/12 - log(2)^2/2
695 if (x.is_equal(_ex1_2))
696 return power(Pi,_ex2)/_ex12 + power(log(_ex2),_ex2)*_ex_1_2;
697 // Li2(-1) -> -Pi^2/12
698 if (x.is_equal(_ex_1))
699 return -power(Pi,_ex2)/_ex12;
700 // Li2(I) -> -Pi^2/48+Catalan*I
702 return power(Pi,_ex2)/_ex_48 + Catalan*I;
703 // Li2(-I) -> -Pi^2/48-Catalan*I
705 return power(Pi,_ex2)/_ex_48 - Catalan*I;
707 if (!x.info(info_flags::crational))
708 return Li2(ex_to<numeric>(x));
711 return Li2(x).hold();
714 static ex Li2_deriv(const ex & x, unsigned deriv_param)
716 GINAC_ASSERT(deriv_param==0);
718 // d/dx Li2(x) -> -log(1-x)/x
719 return -log(_ex1-x)/x;
722 static ex Li2_series(const ex &x, const relational &rel, int order, unsigned options)
724 const ex x_pt = x.subs(rel, subs_options::no_pattern);
725 if (x_pt.info(info_flags::numeric)) {
726 // First special case: x==0 (derivatives have poles)
727 if (x_pt.is_zero()) {
729 // The problem is that in d/dx Li2(x==0) == -log(1-x)/x we cannot
730 // simply substitute x==0. The limit, however, exists: it is 1.
731 // We also know all higher derivatives' limits:
732 // (d/dx)^n Li2(x) == n!/n^2.
733 // So the primitive series expansion is
734 // Li2(x==0) == x + x^2/4 + x^3/9 + ...
736 // We first construct such a primitive series expansion manually in
737 // a dummy symbol s and then insert the argument's series expansion
738 // for s. Reexpanding the resulting series returns the desired
742 // manually construct the primitive expansion
743 for (int i=1; i<order; ++i)
744 ser += pow(s,i) / pow(numeric(i), *_num2_p);
745 // substitute the argument's series expansion
746 ser = ser.subs(s==x.series(rel, order), subs_options::no_pattern);
747 // maybe that was terminating, so add a proper order term
749 nseq.push_back(expair(Order(_ex1), order));
750 ser += pseries(rel, nseq);
751 // reexpanding it will collapse the series again
752 return ser.series(rel, order);
753 // NB: Of course, this still does not allow us to compute anything
754 // like sin(Li2(x)).series(x==0,2), since then this code here is
755 // not reached and the derivative of sin(Li2(x)) doesn't allow the
756 // substitution x==0. Probably limits *are* needed for the general
757 // cases. In case L'Hospital's rule is implemented for limits and
758 // basic::series() takes care of this, this whole block is probably
761 // second special case: x==1 (branch point)
762 if (x_pt.is_equal(_ex1)) {
764 // construct series manually in a dummy symbol s
767 // manually construct the primitive expansion
768 for (int i=1; i<order; ++i)
769 ser += pow(1-s,i) * (numeric(1,i)*(I*Pi+log(s-1)) - numeric(1,i*i));
770 // substitute the argument's series expansion
771 ser = ser.subs(s==x.series(rel, order), subs_options::no_pattern);
772 // maybe that was terminating, so add a proper order term
774 nseq.push_back(expair(Order(_ex1), order));
775 ser += pseries(rel, nseq);
776 // reexpanding it will collapse the series again
777 return ser.series(rel, order);
779 // third special case: x real, >=1 (branch cut)
780 if (!(options & series_options::suppress_branchcut) &&
781 ex_to<numeric>(x_pt).is_real() && ex_to<numeric>(x_pt)>1) {
783 // This is the branch cut: assemble the primitive series manually
784 // and then add the corresponding complex step function.
785 const symbol &s = ex_to<symbol>(rel.lhs());
786 const ex point = rel.rhs();
789 // zeroth order term:
790 seq.push_back(expair(Li2(x_pt), _ex0));
791 // compute the intermediate terms:
792 ex replarg = series(Li2(x), s==foo, order);
793 for (size_t i=1; i<replarg.nops()-1; ++i)
794 seq.push_back(expair((replarg.op(i)/power(s-foo,i)).series(foo==point,1,options).op(0).subs(foo==s, subs_options::no_pattern),i));
795 // append an order term:
796 seq.push_back(expair(Order(_ex1), replarg.nops()-1));
797 return pseries(rel, seq);
800 // all other cases should be safe, by now:
801 throw do_taylor(); // caught by function::series()
804 static ex Li2_conjugate(const ex & x)
806 // conjugate(Li2(x))==Li2(conjugate(x)) unless on the branch cuts which
807 // run along the positive real axis beginning at 1.
808 if (x.info(info_flags::negative)) {
809 return Li2(x).hold();
811 if (is_exactly_a<numeric>(x) &&
812 (!x.imag_part().is_zero() || x < *_num1_p)) {
813 return Li2(x.conjugate());
815 return conjugate_function(Li2(x)).hold();
818 REGISTER_FUNCTION(Li2, eval_func(Li2_eval).
819 evalf_func(Li2_evalf).
820 derivative_func(Li2_deriv).
821 series_func(Li2_series).
822 conjugate_func(Li2_conjugate).
823 latex_name("\\mathrm{Li}_2"));
829 static ex Li3_eval(const ex & x)
833 return Li3(x).hold();
836 REGISTER_FUNCTION(Li3, eval_func(Li3_eval).
837 latex_name("\\mathrm{Li}_3"));
840 // Derivatives of Riemann's Zeta-function zetaderiv(0,x)==zeta(x)
843 static ex zetaderiv_eval(const ex & n, const ex & x)
845 if (n.info(info_flags::numeric)) {
846 // zetaderiv(0,x) -> zeta(x)
848 return zeta(x).hold();
851 return zetaderiv(n, x).hold();
854 static ex zetaderiv_deriv(const ex & n, const ex & x, unsigned deriv_param)
856 GINAC_ASSERT(deriv_param<2);
858 if (deriv_param==0) {
860 throw(std::logic_error("cannot diff zetaderiv(n,x) with respect to n"));
863 return zetaderiv(n+1,x);
866 REGISTER_FUNCTION(zetaderiv, eval_func(zetaderiv_eval).
867 derivative_func(zetaderiv_deriv).
868 latex_name("\\zeta^\\prime"));
874 static ex factorial_evalf(const ex & x)
876 return factorial(x).hold();
879 static ex factorial_eval(const ex & x)
881 if (is_exactly_a<numeric>(x))
882 return factorial(ex_to<numeric>(x));
884 return factorial(x).hold();
887 static void factorial_print_dflt_latex(const ex & x, const print_context & c)
889 if (is_exactly_a<symbol>(x) ||
890 is_exactly_a<constant>(x) ||
891 is_exactly_a<function>(x)) {
892 x.print(c); c.s << "!";
894 c.s << "("; x.print(c); c.s << ")!";
898 static ex factorial_conjugate(const ex & x)
900 return factorial(x).hold();
903 static ex factorial_real_part(const ex & x)
905 return factorial(x).hold();
908 static ex factorial_imag_part(const ex & x)
913 REGISTER_FUNCTION(factorial, eval_func(factorial_eval).
914 evalf_func(factorial_evalf).
915 print_func<print_dflt>(factorial_print_dflt_latex).
916 print_func<print_latex>(factorial_print_dflt_latex).
917 conjugate_func(factorial_conjugate).
918 real_part_func(factorial_real_part).
919 imag_part_func(factorial_imag_part));
925 static ex binomial_evalf(const ex & x, const ex & y)
927 return binomial(x, y).hold();
930 static ex binomial_sym(const ex & x, const numeric & y)
932 if (y.is_integer()) {
933 if (y.is_nonneg_integer()) {
934 const unsigned N = y.to_int();
935 if (N == 0) return _ex1;
936 if (N == 1) return x;
938 for (unsigned i = 2; i <= N; ++i)
939 t = (t * (x + i - y - 1)).expand() / i;
945 return binomial(x, y).hold();
948 static ex binomial_eval(const ex & x, const ex &y)
950 if (is_exactly_a<numeric>(y)) {
951 if (is_exactly_a<numeric>(x) && ex_to<numeric>(x).is_integer())
952 return binomial(ex_to<numeric>(x), ex_to<numeric>(y));
954 return binomial_sym(x, ex_to<numeric>(y));
956 return binomial(x, y).hold();
959 // At the moment the numeric evaluation of a binomial function always
960 // gives a real number, but if this would be implemented using the gamma
961 // function, also complex conjugation should be changed (or rather, deleted).
962 static ex binomial_conjugate(const ex & x, const ex & y)
964 return binomial(x,y).hold();
967 static ex binomial_real_part(const ex & x, const ex & y)
969 return binomial(x,y).hold();
972 static ex binomial_imag_part(const ex & x, const ex & y)
977 REGISTER_FUNCTION(binomial, eval_func(binomial_eval).
978 evalf_func(binomial_evalf).
979 conjugate_func(binomial_conjugate).
980 real_part_func(binomial_real_part).
981 imag_part_func(binomial_imag_part));
984 // Order term function (for truncated power series)
987 static ex Order_eval(const ex & x)
989 if (is_exactly_a<numeric>(x)) {
992 return Order(_ex1).hold();
995 } else if (is_exactly_a<mul>(x)) {
996 const mul &m = ex_to<mul>(x);
997 // O(c*expr) -> O(expr)
998 if (is_exactly_a<numeric>(m.op(m.nops() - 1)))
999 return Order(x / m.op(m.nops() - 1)).hold();
1001 return Order(x).hold();
1004 static ex Order_series(const ex & x, const relational & r, int order, unsigned options)
1006 // Just wrap the function into a pseries object
1008 GINAC_ASSERT(is_a<symbol>(r.lhs()));
1009 const symbol &s = ex_to<symbol>(r.lhs());
1010 new_seq.push_back(expair(Order(_ex1), numeric(std::min(x.ldegree(s), order))));
1011 return pseries(r, new_seq);
1014 static ex Order_conjugate(const ex & x)
1016 return Order(x).hold();
1019 static ex Order_real_part(const ex & x)
1021 return Order(x).hold();
1024 static ex Order_imag_part(const ex & x)
1026 if(x.info(info_flags::real))
1028 return Order(x).hold();
1031 static ex Order_expl_derivative(const ex & arg, const symbol & s)
1033 return Order(arg.diff(s));
1036 REGISTER_FUNCTION(Order, eval_func(Order_eval).
1037 series_func(Order_series).
1038 latex_name("\\mathcal{O}").
1039 expl_derivative_func(Order_expl_derivative).
1040 conjugate_func(Order_conjugate).
1041 real_part_func(Order_real_part).
1042 imag_part_func(Order_imag_part));
1045 // Solve linear system
1048 ex lsolve(const ex &eqns, const ex &symbols, unsigned options)
1050 // solve a system of linear equations
1051 if (eqns.info(info_flags::relation_equal)) {
1052 if (!symbols.info(info_flags::symbol))
1053 throw(std::invalid_argument("lsolve(): 2nd argument must be a symbol"));
1054 const ex sol = lsolve(lst(eqns),lst(symbols));
1056 GINAC_ASSERT(sol.nops()==1);
1057 GINAC_ASSERT(is_exactly_a<relational>(sol.op(0)));
1059 return sol.op(0).op(1); // return rhs of first solution
1063 if (!eqns.info(info_flags::list)) {
1064 throw(std::invalid_argument("lsolve(): 1st argument must be a list or an equation"));
1066 for (size_t i=0; i<eqns.nops(); i++) {
1067 if (!eqns.op(i).info(info_flags::relation_equal)) {
1068 throw(std::invalid_argument("lsolve(): 1st argument must be a list of equations"));
1071 if (!symbols.info(info_flags::list)) {
1072 throw(std::invalid_argument("lsolve(): 2nd argument must be a list or a symbol"));
1074 for (size_t i=0; i<symbols.nops(); i++) {
1075 if (!symbols.op(i).info(info_flags::symbol)) {
1076 throw(std::invalid_argument("lsolve(): 2nd argument must be a list of symbols"));
1080 // build matrix from equation system
1081 matrix sys(eqns.nops(),symbols.nops());
1082 matrix rhs(eqns.nops(),1);
1083 matrix vars(symbols.nops(),1);
1085 for (size_t r=0; r<eqns.nops(); r++) {
1086 const ex eq = eqns.op(r).op(0)-eqns.op(r).op(1); // lhs-rhs==0
1088 for (size_t c=0; c<symbols.nops(); c++) {
1089 const ex co = eq.coeff(ex_to<symbol>(symbols.op(c)),1);
1090 linpart -= co*symbols.op(c);
1093 linpart = linpart.expand();
1094 rhs(r,0) = -linpart;
1097 // test if system is linear and fill vars matrix
1098 for (size_t i=0; i<symbols.nops(); i++) {
1099 vars(i,0) = symbols.op(i);
1100 if (sys.has(symbols.op(i)))
1101 throw(std::logic_error("lsolve: system is not linear"));
1102 if (rhs.has(symbols.op(i)))
1103 throw(std::logic_error("lsolve: system is not linear"));
1108 solution = sys.solve(vars,rhs,options);
1109 } catch (const std::runtime_error & e) {
1110 // Probably singular matrix or otherwise overdetermined system:
1111 // It is consistent to return an empty list
1114 GINAC_ASSERT(solution.cols()==1);
1115 GINAC_ASSERT(solution.rows()==symbols.nops());
1117 // return list of equations of the form lst(var1==sol1,var2==sol2,...)
1119 for (size_t i=0; i<symbols.nops(); i++)
1120 sollist.append(symbols.op(i)==solution(i,0));
1126 // Find real root of f(x) numerically
1130 fsolve(const ex& f_in, const symbol& x, const numeric& x1, const numeric& x2)
1132 if (!x1.is_real() || !x2.is_real()) {
1133 throw std::runtime_error("fsolve(): interval not bounded by real numbers");
1136 throw std::runtime_error("fsolve(): vanishing interval");
1138 // xx[0] == left interval limit, xx[1] == right interval limit.
1139 // fx[0] == f(xx[0]), fx[1] == f(xx[1]).
1140 // We keep the root bracketed: xx[0]<xx[1] and fx[0]*fx[1]<0.
1141 numeric xx[2] = { x1<x2 ? x1 : x2,
1144 if (is_a<relational>(f_in)) {
1145 f = f_in.lhs()-f_in.rhs();
1149 const ex fx_[2] = { f.subs(x==xx[0]).evalf(),
1150 f.subs(x==xx[1]).evalf() };
1151 if (!is_a<numeric>(fx_[0]) || !is_a<numeric>(fx_[1])) {
1152 throw std::runtime_error("fsolve(): function does not evaluate numerically");
1154 numeric fx[2] = { ex_to<numeric>(fx_[0]),
1155 ex_to<numeric>(fx_[1]) };
1156 if (!fx[0].is_real() || !fx[1].is_real()) {
1157 throw std::runtime_error("fsolve(): function evaluates to complex values at interval boundaries");
1159 if (fx[0]*fx[1]>=0) {
1160 throw std::runtime_error("fsolve(): function does not change sign at interval boundaries");
1163 // The Newton-Raphson method has quadratic convergence! Simply put, it
1164 // replaces x with x-f(x)/f'(x) at each step. -f/f' is the delta:
1165 const ex ff = normal(-f/f.diff(x));
1166 int side = 0; // Start at left interval limit.
1172 ex dx_ = ff.subs(x == xx[side]).evalf();
1173 if (!is_a<numeric>(dx_))
1174 throw std::runtime_error("fsolve(): function derivative does not evaluate numerically");
1175 xx[side] += ex_to<numeric>(dx_);
1176 // Now check if Newton-Raphson method shot out of the interval
1177 bool bad_shot = (side == 0 && xx[0] < xxprev) ||
1178 (side == 1 && xx[1] > xxprev) || xx[0] > xx[1];
1180 // Compute f(x) only if new x is inside the interval.
1181 // The function might be difficult to compute numerically
1182 // or even ill defined outside the interval. Also it's
1183 // a small optimization.
1184 ex f_x = f.subs(x == xx[side]).evalf();
1185 if (!is_a<numeric>(f_x))
1186 throw std::runtime_error("fsolve(): function does not evaluate numerically");
1187 fx[side] = ex_to<numeric>(f_x);
1190 // Oops, Newton-Raphson method shot out of the interval.
1191 // Restore, and try again with the other side instead!
1198 ex dx_ = ff.subs(x == xx[side]).evalf();
1199 if (!is_a<numeric>(dx_))
1200 throw std::runtime_error("fsolve(): function derivative does not evaluate numerically [2]");
1201 xx[side] += ex_to<numeric>(dx_);
1203 ex f_x = f.subs(x==xx[side]).evalf();
1204 if (!is_a<numeric>(f_x))
1205 throw std::runtime_error("fsolve(): function does not evaluate numerically [2]");
1206 fx[side] = ex_to<numeric>(f_x);
1208 if ((fx[side]<0 && fx[!side]<0) || (fx[side]>0 && fx[!side]>0)) {
1209 // Oops, the root isn't bracketed any more.
1210 // Restore, and perform a bisection!
1214 // Ah, the bisection! Bisections converge linearly. Unfortunately,
1215 // they occur pretty often when Newton-Raphson arrives at an x too
1216 // close to the result on one side of the interval and
1217 // f(x-f(x)/f'(x)) turns out to have the same sign as f(x) due to
1218 // precision errors! Recall that this function does not have a
1219 // precision goal as one of its arguments but instead relies on
1220 // x converging to a fixed point. We speed up the (safe but slow)
1221 // bisection method by mixing in a dash of the (unsafer but faster)
1222 // secant method: Instead of splitting the interval at the
1223 // arithmetic mean (bisection), we split it nearer to the root as
1224 // determined by the secant between the values xx[0] and xx[1].
1225 // Don't set the secant_weight to one because that could disturb
1226 // the convergence in some corner cases!
1227 static const double secant_weight = 0.984375; // == 63/64 < 1
1228 numeric xxmid = (1-secant_weight)*0.5*(xx[0]+xx[1])
1229 + secant_weight*(xx[0]+fx[0]*(xx[0]-xx[1])/(fx[1]-fx[0]));
1230 ex fxmid_ = f.subs(x == xxmid).evalf();
1231 if (!is_a<numeric>(fxmid_))
1232 throw std::runtime_error("fsolve(): function does not evaluate numerically [3]");
1233 numeric fxmid = ex_to<numeric>(fxmid_);
1234 if (fxmid.is_zero()) {
1238 if ((fxmid<0 && fx[side]>0) || (fxmid>0 && fx[side]<0)) {
1246 } while (xxprev!=xx[side]);
1251 /* Force inclusion of functions from inifcns_gamma and inifcns_zeta
1252 * for static lib (so ginsh will see them). */
1253 unsigned force_include_tgamma = tgamma_SERIAL::serial;
1254 unsigned force_include_zeta1 = zeta1_SERIAL::serial;
1256 } // namespace GiNaC