3 * Implementation of GiNaC's initially known functions. */
6 * GiNaC Copyright (C) 1999-2024 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::positive:
113 case info_flags::negative:
114 case info_flags::nonnegative:
115 case info_flags::posint:
116 case info_flags::negint:
117 case info_flags::nonnegint:
118 case info_flags::has_indices:
119 return arg.info(inf);
124 static bool conjugate_info(const ex & arg, unsigned inf)
126 return func_arg_info(arg, inf);
129 REGISTER_FUNCTION(conjugate_function, eval_func(conjugate_eval).
130 evalf_func(conjugate_evalf).
131 expl_derivative_func(conjugate_expl_derivative).
132 info_func(conjugate_info).
133 print_func<print_latex>(conjugate_print_latex).
134 conjugate_func(conjugate_conjugate).
135 real_part_func(conjugate_real_part).
136 imag_part_func(conjugate_imag_part).
137 set_name("conjugate","conjugate"));
143 static ex real_part_evalf(const ex & arg)
145 if (is_exactly_a<numeric>(arg)) {
146 return ex_to<numeric>(arg).real();
148 return real_part_function(arg).hold();
151 static ex real_part_eval(const ex & arg)
153 return arg.real_part();
156 static void real_part_print_latex(const ex & arg, const print_context & c)
158 c.s << "\\Re"; arg.print(c); c.s << "";
161 static ex real_part_conjugate(const ex & arg)
163 return real_part_function(arg).hold();
166 static ex real_part_real_part(const ex & arg)
168 return real_part_function(arg).hold();
171 static ex real_part_imag_part(const ex & arg)
176 // If x is real then Re(e).diff(x) is equal to Re(e.diff(x))
177 static ex real_part_expl_derivative(const ex & arg, const symbol & s)
179 if (s.info(info_flags::real))
180 return real_part_function(arg.diff(s));
183 vec_arg.push_back(arg);
184 return fderivative(ex_to<function>(real_part(arg)).get_serial(),0,vec_arg).hold()*arg.diff(s);
188 REGISTER_FUNCTION(real_part_function, eval_func(real_part_eval).
189 evalf_func(real_part_evalf).
190 expl_derivative_func(real_part_expl_derivative).
191 print_func<print_latex>(real_part_print_latex).
192 conjugate_func(real_part_conjugate).
193 real_part_func(real_part_real_part).
194 imag_part_func(real_part_imag_part).
195 set_name("real_part","real_part"));
201 static ex imag_part_evalf(const ex & arg)
203 if (is_exactly_a<numeric>(arg)) {
204 return ex_to<numeric>(arg).imag();
206 return imag_part_function(arg).hold();
209 static ex imag_part_eval(const ex & arg)
211 return arg.imag_part();
214 static void imag_part_print_latex(const ex & arg, const print_context & c)
216 c.s << "\\Im"; arg.print(c); c.s << "";
219 static ex imag_part_conjugate(const ex & arg)
221 return imag_part_function(arg).hold();
224 static ex imag_part_real_part(const ex & arg)
226 return imag_part_function(arg).hold();
229 static ex imag_part_imag_part(const ex & arg)
234 // If x is real then Im(e).diff(x) is equal to Im(e.diff(x))
235 static ex imag_part_expl_derivative(const ex & arg, const symbol & s)
237 if (s.info(info_flags::real))
238 return imag_part_function(arg.diff(s));
241 vec_arg.push_back(arg);
242 return fderivative(ex_to<function>(imag_part(arg)).get_serial(),0,vec_arg).hold()*arg.diff(s);
246 REGISTER_FUNCTION(imag_part_function, eval_func(imag_part_eval).
247 evalf_func(imag_part_evalf).
248 expl_derivative_func(imag_part_expl_derivative).
249 print_func<print_latex>(imag_part_print_latex).
250 conjugate_func(imag_part_conjugate).
251 real_part_func(imag_part_real_part).
252 imag_part_func(imag_part_imag_part).
253 set_name("imag_part","imag_part"));
259 static ex abs_evalf(const ex & arg)
261 if (is_exactly_a<numeric>(arg))
262 return abs(ex_to<numeric>(arg));
264 return abs(arg).hold();
267 static ex abs_eval(const ex & arg)
269 if (is_exactly_a<numeric>(arg))
270 return abs(ex_to<numeric>(arg));
272 if (arg.info(info_flags::nonnegative))
275 if (arg.info(info_flags::negative) || (-arg).info(info_flags::nonnegative))
278 if (is_ex_the_function(arg, abs))
281 if (is_ex_the_function(arg, exp))
282 return exp(arg.op(0).real_part());
284 if (is_exactly_a<power>(arg)) {
285 const ex& base = arg.op(0);
286 const ex& exponent = arg.op(1);
287 if (base.info(info_flags::positive) || exponent.info(info_flags::real))
288 return pow(abs(base), exponent.real_part());
291 if (is_ex_the_function(arg, conjugate_function))
292 return abs(arg.op(0));
294 if (is_ex_the_function(arg, step))
297 return abs(arg).hold();
300 static ex abs_expand(const ex & arg, unsigned options)
302 if ((options & expand_options::expand_transcendental)
303 && is_exactly_a<mul>(arg)) {
305 prodseq.reserve(arg.nops());
306 for (const_iterator i = arg.begin(); i != arg.end(); ++i) {
307 if (options & expand_options::expand_function_args)
308 prodseq.push_back(abs(i->expand(options)));
310 prodseq.push_back(abs(*i));
312 return dynallocate<mul>(prodseq).setflag(status_flags::expanded);
315 if (options & expand_options::expand_function_args)
316 return abs(arg.expand(options)).hold();
318 return abs(arg).hold();
321 static ex abs_expl_derivative(const ex & arg, const symbol & s)
323 ex diff_arg = arg.diff(s);
324 return (diff_arg*arg.conjugate()+arg*diff_arg.conjugate())/2/abs(arg);
327 static void abs_print_latex(const ex & arg, const print_context & c)
329 c.s << "{|"; arg.print(c); c.s << "|}";
332 static void abs_print_csrc_float(const ex & arg, const print_context & c)
334 c.s << "fabs("; arg.print(c); c.s << ")";
337 static ex abs_conjugate(const ex & arg)
339 return abs(arg).hold();
342 static ex abs_real_part(const ex & arg)
344 return abs(arg).hold();
347 static ex abs_imag_part(const ex& arg)
352 static ex abs_power(const ex & arg, const ex & exp)
354 if ((is_a<numeric>(exp) && ex_to<numeric>(exp).is_even()) || exp.info(info_flags::even)) {
355 if (arg.info(info_flags::real) || arg.is_equal(arg.conjugate()))
356 return pow(arg, exp);
358 return pow(arg, exp/2) * pow(arg.conjugate(), exp/2);
360 return power(abs(arg), exp).hold();
363 bool abs_info(const ex & arg, unsigned inf)
366 case info_flags::integer:
367 case info_flags::even:
368 case info_flags::odd:
369 case info_flags::prime:
370 return arg.info(inf);
371 case info_flags::nonnegint:
372 return arg.info(info_flags::integer);
373 case info_flags::nonnegative:
374 case info_flags::real:
376 case info_flags::negative:
378 case info_flags::positive:
379 return arg.info(info_flags::positive) || arg.info(info_flags::negative);
380 case info_flags::has_indices: {
381 if (arg.info(info_flags::has_indices))
390 REGISTER_FUNCTION(abs, eval_func(abs_eval).
391 evalf_func(abs_evalf).
392 expand_func(abs_expand).
393 expl_derivative_func(abs_expl_derivative).
395 print_func<print_latex>(abs_print_latex).
396 print_func<print_csrc_float>(abs_print_csrc_float).
397 print_func<print_csrc_double>(abs_print_csrc_float).
398 conjugate_func(abs_conjugate).
399 real_part_func(abs_real_part).
400 imag_part_func(abs_imag_part).
401 power_func(abs_power));
407 static ex step_evalf(const ex & arg)
409 if (is_exactly_a<numeric>(arg))
410 return step(ex_to<numeric>(arg));
412 return step(arg).hold();
415 static ex step_eval(const ex & arg)
417 if (is_exactly_a<numeric>(arg))
418 return step(ex_to<numeric>(arg));
420 else if (is_exactly_a<mul>(arg) &&
421 is_exactly_a<numeric>(arg.op(arg.nops()-1))) {
422 numeric oc = ex_to<numeric>(arg.op(arg.nops()-1));
425 // step(42*x) -> step(x)
426 return step(arg/oc).hold();
428 // step(-42*x) -> step(-x)
429 return step(-arg/oc).hold();
431 if (oc.real().is_zero()) {
433 // step(42*I*x) -> step(I*x)
434 return step(I*arg/oc).hold();
436 // step(-42*I*x) -> step(-I*x)
437 return step(-I*arg/oc).hold();
441 return step(arg).hold();
444 static ex step_series(const ex & arg,
445 const relational & rel,
449 const ex arg_pt = arg.subs(rel, subs_options::no_pattern);
450 if (arg_pt.info(info_flags::numeric)
451 && ex_to<numeric>(arg_pt).real().is_zero()
452 && !(options & series_options::suppress_branchcut))
453 throw (std::domain_error("step_series(): on imaginary axis"));
455 epvector seq { expair(step(arg_pt), _ex0) };
456 return pseries(rel, std::move(seq));
459 static ex step_conjugate(const ex& arg)
461 return step(arg).hold();
464 static ex step_real_part(const ex& arg)
466 return step(arg).hold();
469 static ex step_imag_part(const ex& arg)
474 REGISTER_FUNCTION(step, eval_func(step_eval).
475 evalf_func(step_evalf).
476 series_func(step_series).
477 conjugate_func(step_conjugate).
478 real_part_func(step_real_part).
479 imag_part_func(step_imag_part));
485 static ex csgn_evalf(const ex & arg)
487 if (is_exactly_a<numeric>(arg))
488 return csgn(ex_to<numeric>(arg));
490 return csgn(arg).hold();
493 static ex csgn_eval(const ex & arg)
495 if (is_exactly_a<numeric>(arg))
496 return csgn(ex_to<numeric>(arg));
498 else if (is_exactly_a<mul>(arg) &&
499 is_exactly_a<numeric>(arg.op(arg.nops()-1))) {
500 numeric oc = ex_to<numeric>(arg.op(arg.nops()-1));
503 // csgn(42*x) -> csgn(x)
504 return csgn(arg/oc).hold();
506 // csgn(-42*x) -> -csgn(x)
507 return -csgn(arg/oc).hold();
509 if (oc.real().is_zero()) {
511 // csgn(42*I*x) -> csgn(I*x)
512 return csgn(I*arg/oc).hold();
514 // csgn(-42*I*x) -> -csgn(I*x)
515 return -csgn(I*arg/oc).hold();
519 return csgn(arg).hold();
522 static ex csgn_series(const ex & arg,
523 const relational & rel,
527 const ex arg_pt = arg.subs(rel, subs_options::no_pattern);
528 if (arg_pt.info(info_flags::numeric)
529 && ex_to<numeric>(arg_pt).real().is_zero()
530 && !(options & series_options::suppress_branchcut))
531 throw (std::domain_error("csgn_series(): on imaginary axis"));
533 epvector seq { expair(csgn(arg_pt), _ex0) };
534 return pseries(rel, std::move(seq));
537 static ex csgn_conjugate(const ex& arg)
539 return csgn(arg).hold();
542 static ex csgn_real_part(const ex& arg)
544 return csgn(arg).hold();
547 static ex csgn_imag_part(const ex& arg)
552 static ex csgn_power(const ex & arg, const ex & exp)
554 if (is_a<numeric>(exp) && exp.info(info_flags::positive) && ex_to<numeric>(exp).is_integer()) {
555 if (ex_to<numeric>(exp).is_odd())
556 return csgn(arg).hold();
558 return power(csgn(arg), _ex2).hold();
560 return power(csgn(arg), exp).hold();
564 REGISTER_FUNCTION(csgn, eval_func(csgn_eval).
565 evalf_func(csgn_evalf).
566 series_func(csgn_series).
567 conjugate_func(csgn_conjugate).
568 real_part_func(csgn_real_part).
569 imag_part_func(csgn_imag_part).
570 power_func(csgn_power));
574 // Eta function: eta(x,y) == log(x*y) - log(x) - log(y).
575 // This function is closely related to the unwinding number K, sometimes found
576 // in modern literature: K(z) == (z-log(exp(z)))/(2*Pi*I).
579 static ex eta_evalf(const ex &x, const ex &y)
581 // It seems like we basically have to replicate the eval function here,
582 // since the expression might not be fully evaluated yet.
583 if (x.info(info_flags::positive) || y.info(info_flags::positive))
586 if (x.info(info_flags::numeric) && y.info(info_flags::numeric)) {
587 const numeric nx = ex_to<numeric>(x);
588 const numeric ny = ex_to<numeric>(y);
589 const numeric nxy = ex_to<numeric>(x*y);
591 if (nx.is_real() && nx.is_negative())
593 if (ny.is_real() && ny.is_negative())
595 if (nxy.is_real() && nxy.is_negative())
597 return evalf(I/4*Pi)*((csgn(-imag(nx))+1)*(csgn(-imag(ny))+1)*(csgn(imag(nxy))+1)-
598 (csgn(imag(nx))+1)*(csgn(imag(ny))+1)*(csgn(-imag(nxy))+1)+cut);
601 return eta(x,y).hold();
604 static ex eta_eval(const ex &x, const ex &y)
606 // trivial: eta(x,c) -> 0 if c is real and positive
607 if (x.info(info_flags::positive) || y.info(info_flags::positive))
610 if (x.info(info_flags::numeric) && y.info(info_flags::numeric)) {
611 // don't call eta_evalf here because it would call Pi.evalf()!
612 const numeric nx = ex_to<numeric>(x);
613 const numeric ny = ex_to<numeric>(y);
614 const numeric nxy = ex_to<numeric>(x*y);
616 if (nx.is_real() && nx.is_negative())
618 if (ny.is_real() && ny.is_negative())
620 if (nxy.is_real() && nxy.is_negative())
622 return (I/4)*Pi*((csgn(-imag(nx))+1)*(csgn(-imag(ny))+1)*(csgn(imag(nxy))+1)-
623 (csgn(imag(nx))+1)*(csgn(imag(ny))+1)*(csgn(-imag(nxy))+1)+cut);
626 return eta(x,y).hold();
629 static ex eta_series(const ex & x, const ex & y,
630 const relational & rel,
634 const ex x_pt = x.subs(rel, subs_options::no_pattern);
635 const ex y_pt = y.subs(rel, subs_options::no_pattern);
636 if ((x_pt.info(info_flags::numeric) && x_pt.info(info_flags::negative)) ||
637 (y_pt.info(info_flags::numeric) && y_pt.info(info_flags::negative)) ||
638 ((x_pt*y_pt).info(info_flags::numeric) && (x_pt*y_pt).info(info_flags::negative)))
639 throw (std::domain_error("eta_series(): on discontinuity"));
640 epvector seq { expair(eta(x_pt,y_pt), _ex0) };
641 return pseries(rel, std::move(seq));
644 static ex eta_conjugate(const ex & x, const ex & y)
646 return -eta(x, y).hold();
649 static ex eta_real_part(const ex & x, const ex & y)
654 static ex eta_imag_part(const ex & x, const ex & y)
656 return -I*eta(x, y).hold();
659 REGISTER_FUNCTION(eta, eval_func(eta_eval).
660 evalf_func(eta_evalf).
661 series_func(eta_series).
663 set_symmetry(sy_symm(0, 1)).
664 conjugate_func(eta_conjugate).
665 real_part_func(eta_real_part).
666 imag_part_func(eta_imag_part));
673 static ex Li2_evalf(const ex & x)
675 if (is_exactly_a<numeric>(x))
676 return Li2(ex_to<numeric>(x));
678 return Li2(x).hold();
681 static ex Li2_eval(const ex & x)
683 if (x.info(info_flags::numeric)) {
688 if (x.is_equal(_ex1))
689 return power(Pi,_ex2)/_ex6;
690 // Li2(1/2) -> Pi^2/12 - log(2)^2/2
691 if (x.is_equal(_ex1_2))
692 return power(Pi,_ex2)/_ex12 + power(log(_ex2),_ex2)*_ex_1_2;
693 // Li2(-1) -> -Pi^2/12
694 if (x.is_equal(_ex_1))
695 return -power(Pi,_ex2)/_ex12;
696 // Li2(I) -> -Pi^2/48+Catalan*I
698 return power(Pi,_ex2)/_ex_48 + Catalan*I;
699 // Li2(-I) -> -Pi^2/48-Catalan*I
701 return power(Pi,_ex2)/_ex_48 - Catalan*I;
703 if (!x.info(info_flags::crational))
704 return Li2(ex_to<numeric>(x));
707 return Li2(x).hold();
710 static ex Li2_deriv(const ex & x, unsigned deriv_param)
712 GINAC_ASSERT(deriv_param==0);
714 // d/dx Li2(x) -> -log(1-x)/x
715 return -log(_ex1-x)/x;
718 static ex Li2_series(const ex &x, const relational &rel, int order, unsigned options)
720 const ex x_pt = x.subs(rel, subs_options::no_pattern);
721 if (x_pt.info(info_flags::numeric)) {
722 // First special case: x==0 (derivatives have poles)
723 if (x_pt.is_zero()) {
725 // The problem is that in d/dx Li2(x==0) == -log(1-x)/x we cannot
726 // simply substitute x==0. The limit, however, exists: it is 1.
727 // We also know all higher derivatives' limits:
728 // (d/dx)^n Li2(x) == n!/n^2.
729 // So the primitive series expansion is
730 // Li2(x==0) == x + x^2/4 + x^3/9 + ...
732 // We first construct such a primitive series expansion manually in
733 // a dummy symbol s and then insert the argument's series expansion
734 // for s. Reexpanding the resulting series returns the desired
738 // manually construct the primitive expansion
739 for (int i=1; i<order; ++i)
740 ser += pow(s,i) / pow(numeric(i), *_num2_p);
741 // substitute the argument's series expansion
742 ser = ser.subs(s==x.series(rel, order), subs_options::no_pattern);
743 // maybe that was terminating, so add a proper order term
744 epvector nseq { expair(Order(_ex1), order) };
745 ser += pseries(rel, std::move(nseq));
746 // reexpanding it will collapse the series again
747 return ser.series(rel, order);
748 // NB: Of course, this still does not allow us to compute anything
749 // like sin(Li2(x)).series(x==0,2), since then this code here is
750 // not reached and the derivative of sin(Li2(x)) doesn't allow the
751 // substitution x==0. Probably limits *are* needed for the general
752 // cases. In case L'Hospital's rule is implemented for limits and
753 // basic::series() takes care of this, this whole block is probably
756 // second special case: x==1 (branch point)
757 if (x_pt.is_equal(_ex1)) {
759 // construct series manually in a dummy symbol s
762 // manually construct the primitive expansion
763 for (int i=1; i<order; ++i)
764 ser += pow(1-s,i) * (numeric(1,i)*(I*Pi+log(s-1)) - numeric(1,i*i));
765 // substitute the argument's series expansion
766 ser = ser.subs(s==x.series(rel, order), subs_options::no_pattern);
767 // maybe that was terminating, so add a proper order term
768 epvector nseq { expair(Order(_ex1), order) };
769 ser += pseries(rel, std::move(nseq));
770 // reexpanding it will collapse the series again
771 return ser.series(rel, order);
773 // third special case: x real, >=1 (branch cut)
774 if (!(options & series_options::suppress_branchcut) &&
775 ex_to<numeric>(x_pt).is_real() && ex_to<numeric>(x_pt)>1) {
777 // This is the branch cut: assemble the primitive series manually
778 // and then add the corresponding complex step function.
779 const symbol &s = ex_to<symbol>(rel.lhs());
780 const ex point = rel.rhs();
783 // zeroth order term:
784 seq.push_back(expair(Li2(x_pt), _ex0));
785 // compute the intermediate terms:
786 ex replarg = series(Li2(x), s==foo, order);
787 for (size_t i=1; i<replarg.nops()-1; ++i)
788 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));
789 // append an order term:
790 seq.push_back(expair(Order(_ex1), replarg.nops()-1));
791 return pseries(rel, std::move(seq));
794 // all other cases should be safe, by now:
795 throw do_taylor(); // caught by function::series()
798 static ex Li2_conjugate(const ex & x)
800 // conjugate(Li2(x))==Li2(conjugate(x)) unless on the branch cuts which
801 // run along the positive real axis beginning at 1.
802 if (x.info(info_flags::negative)) {
803 return Li2(x).hold();
805 if (is_exactly_a<numeric>(x) &&
806 (!x.imag_part().is_zero() || x < *_num1_p)) {
807 return Li2(x.conjugate());
809 return conjugate_function(Li2(x)).hold();
812 REGISTER_FUNCTION(Li2, eval_func(Li2_eval).
813 evalf_func(Li2_evalf).
814 derivative_func(Li2_deriv).
815 series_func(Li2_series).
816 conjugate_func(Li2_conjugate).
817 latex_name("\\mathrm{Li}_2"));
823 static ex Li3_eval(const ex & x)
827 return Li3(x).hold();
830 REGISTER_FUNCTION(Li3, eval_func(Li3_eval).
831 latex_name("\\mathrm{Li}_3"));
834 // Derivatives of Riemann's Zeta-function zetaderiv(0,x)==zeta(x)
837 static ex zetaderiv_eval(const ex & n, const ex & x)
839 if (n.info(info_flags::numeric)) {
840 // zetaderiv(0,x) -> zeta(x)
842 return zeta(x).hold();
845 return zetaderiv(n, x).hold();
848 static ex zetaderiv_deriv(const ex & n, const ex & x, unsigned deriv_param)
850 GINAC_ASSERT(deriv_param<2);
852 if (deriv_param==0) {
854 throw(std::logic_error("cannot diff zetaderiv(n,x) with respect to n"));
857 return zetaderiv(n+1,x);
860 REGISTER_FUNCTION(zetaderiv, eval_func(zetaderiv_eval).
861 derivative_func(zetaderiv_deriv).
862 latex_name("\\zeta^\\prime"));
868 static ex factorial_evalf(const ex & x)
870 return factorial(x).hold();
873 static ex factorial_eval(const ex & x)
875 if (is_exactly_a<numeric>(x))
876 return factorial(ex_to<numeric>(x));
878 return factorial(x).hold();
881 static void factorial_print_dflt_latex(const ex & x, const print_context & c)
883 if (is_exactly_a<symbol>(x) ||
884 is_exactly_a<constant>(x) ||
885 is_exactly_a<function>(x)) {
886 x.print(c); c.s << "!";
888 c.s << "("; x.print(c); c.s << ")!";
892 static ex factorial_conjugate(const ex & x)
894 return factorial(x).hold();
897 static ex factorial_real_part(const ex & x)
899 return factorial(x).hold();
902 static ex factorial_imag_part(const ex & x)
907 REGISTER_FUNCTION(factorial, eval_func(factorial_eval).
908 evalf_func(factorial_evalf).
909 print_func<print_dflt>(factorial_print_dflt_latex).
910 print_func<print_latex>(factorial_print_dflt_latex).
911 conjugate_func(factorial_conjugate).
912 real_part_func(factorial_real_part).
913 imag_part_func(factorial_imag_part));
919 static ex binomial_evalf(const ex & x, const ex & y)
921 return binomial(x, y).hold();
924 static ex binomial_sym(const ex & x, const numeric & y)
926 if (y.is_integer()) {
927 if (y.is_nonneg_integer()) {
928 const unsigned N = y.to_int();
929 if (N == 0) return _ex1;
930 if (N == 1) return x;
932 for (unsigned i = 2; i <= N; ++i)
933 t = (t * (x + i - y - 1)).expand() / i;
939 return binomial(x, y).hold();
942 static ex binomial_eval(const ex & x, const ex &y)
944 if (is_exactly_a<numeric>(y)) {
945 if (is_exactly_a<numeric>(x) && ex_to<numeric>(x).is_integer())
946 return binomial(ex_to<numeric>(x), ex_to<numeric>(y));
948 return binomial_sym(x, ex_to<numeric>(y));
950 return binomial(x, y).hold();
953 // At the moment the numeric evaluation of a binomial function always
954 // gives a real number, but if this would be implemented using the gamma
955 // function, also complex conjugation should be changed (or rather, deleted).
956 static ex binomial_conjugate(const ex & x, const ex & y)
958 return binomial(x,y).hold();
961 static ex binomial_real_part(const ex & x, const ex & y)
963 return binomial(x,y).hold();
966 static ex binomial_imag_part(const ex & x, const ex & y)
971 REGISTER_FUNCTION(binomial, eval_func(binomial_eval).
972 evalf_func(binomial_evalf).
973 conjugate_func(binomial_conjugate).
974 real_part_func(binomial_real_part).
975 imag_part_func(binomial_imag_part));
978 // Order term function (for truncated power series)
981 static ex Order_eval(const ex & x)
983 if (is_exactly_a<numeric>(x)) {
986 return Order(_ex1).hold();
989 } else if (is_exactly_a<mul>(x)) {
990 const mul &m = ex_to<mul>(x);
991 // O(c*expr) -> O(expr)
992 if (is_exactly_a<numeric>(m.op(m.nops() - 1)))
993 return Order(x / m.op(m.nops() - 1)).hold();
995 return Order(x).hold();
998 static ex Order_series(const ex & x, const relational & r, int order, unsigned options)
1000 // Just wrap the function into a pseries object
1001 GINAC_ASSERT(is_a<symbol>(r.lhs()));
1002 const symbol &s = ex_to<symbol>(r.lhs());
1003 epvector new_seq { expair(Order(_ex1), numeric(std::min(x.ldegree(s), order))) };
1004 return pseries(r, std::move(new_seq));
1007 static ex Order_conjugate(const ex & x)
1009 return Order(x).hold();
1012 static ex Order_real_part(const ex & x)
1014 return Order(x).hold();
1017 static ex Order_imag_part(const ex & x)
1019 if(x.info(info_flags::real))
1021 return Order(x).hold();
1024 static ex Order_power(const ex & x, const ex & e)
1026 // Order(x)^e -> Order(x^e) for positive integer e
1027 if (is_exactly_a<numeric>(e) && e.info(info_flags::posint))
1028 return Order(pow(x, e));
1029 // NB: For negative exponents, the above could be wrong.
1030 // This is because series() produces Order(x^n) to denote the order where
1031 // it gave up. So, Order(x^n) can also be an x^(n+1) term if the x^n term
1032 // vanishes. In this situation, 1/Order(x^n) can also be a x^(-n-1) term.
1033 // Transforming it to Order(x^-n) would miss that.
1035 return power(Order(x), e).hold();
1038 static ex Order_expl_derivative(const ex & arg, const symbol & s)
1040 return Order(arg.diff(s));
1043 REGISTER_FUNCTION(Order, eval_func(Order_eval).
1044 series_func(Order_series).
1045 latex_name("\\mathcal{O}").
1046 expl_derivative_func(Order_expl_derivative).
1047 conjugate_func(Order_conjugate).
1048 real_part_func(Order_real_part).
1049 imag_part_func(Order_imag_part).
1050 power_func(Order_power));
1053 // Solve linear system
1058 void insert_symbols(const ex &e)
1060 if (is_a<symbol>(e)) {
1063 for (const ex &sube : e) {
1064 insert_symbols(sube);
1069 explicit symbolset(const ex &e)
1073 bool has(const ex &e) const
1075 return s.find(e) != s.end();
1079 ex lsolve(const ex &eqns, const ex &symbols, unsigned options)
1081 // solve a system of linear equations
1082 if (eqns.info(info_flags::relation_equal)) {
1083 if (!symbols.info(info_flags::symbol))
1084 throw(std::invalid_argument("lsolve(): 2nd argument must be a symbol"));
1085 const ex sol = lsolve(lst{eqns}, lst{symbols});
1087 GINAC_ASSERT(sol.nops()==1);
1088 GINAC_ASSERT(is_exactly_a<relational>(sol.op(0)));
1090 return sol.op(0).op(1); // return rhs of first solution
1094 if (!(eqns.info(info_flags::list) || eqns.info(info_flags::exprseq))) {
1095 throw(std::invalid_argument("lsolve(): 1st argument must be a list, a sequence, or an equation"));
1097 for (size_t i=0; i<eqns.nops(); i++) {
1098 if (!eqns.op(i).info(info_flags::relation_equal)) {
1099 throw(std::invalid_argument("lsolve(): 1st argument must be a list of equations"));
1102 if (!(symbols.info(info_flags::list) || symbols.info(info_flags::exprseq))) {
1103 throw(std::invalid_argument("lsolve(): 2nd argument must be a list, a sequence, or a symbol"));
1105 for (size_t i=0; i<symbols.nops(); i++) {
1106 if (!symbols.op(i).info(info_flags::symbol)) {
1107 throw(std::invalid_argument("lsolve(): 2nd argument must be a list or a sequence of symbols"));
1111 // build matrix from equation system
1112 matrix sys(eqns.nops(),symbols.nops());
1113 matrix rhs(eqns.nops(),1);
1114 matrix vars(symbols.nops(),1);
1116 for (size_t r=0; r<eqns.nops(); r++) {
1117 const ex eq = eqns.op(r).op(0)-eqns.op(r).op(1); // lhs-rhs==0
1118 const symbolset syms(eq);
1120 for (size_t c=0; c<symbols.nops(); c++) {
1121 if (!syms.has(symbols.op(c)))
1123 const ex co = eq.coeff(ex_to<symbol>(symbols.op(c)),1);
1124 linpart -= co*symbols.op(c);
1127 linpart = linpart.expand();
1128 rhs(r,0) = -linpart;
1131 // test if system is linear and fill vars matrix
1132 const symbolset sys_syms(sys);
1133 const symbolset rhs_syms(rhs);
1134 for (size_t i=0; i<symbols.nops(); i++) {
1135 vars(i,0) = symbols.op(i);
1136 if (sys_syms.has(symbols.op(i)))
1137 throw(std::logic_error("lsolve: system is not linear"));
1138 if (rhs_syms.has(symbols.op(i)))
1139 throw(std::logic_error("lsolve: system is not linear"));
1144 solution = sys.solve(vars,rhs,options);
1145 } catch (const std::runtime_error & e) {
1146 // Probably singular matrix or otherwise overdetermined system:
1147 // It is consistent to return an empty list
1150 GINAC_ASSERT(solution.cols()==1);
1151 GINAC_ASSERT(solution.rows()==symbols.nops());
1153 // return list of equations of the form lst{var1==sol1,var2==sol2,...}
1155 for (size_t i=0; i<symbols.nops(); i++)
1156 sollist.append(symbols.op(i)==solution(i,0));
1162 // Find real root of f(x) numerically
1166 fsolve(const ex& f_in, const symbol& x, const numeric& x1, const numeric& x2)
1168 if (!x1.is_real() || !x2.is_real()) {
1169 throw std::runtime_error("fsolve(): interval not bounded by real numbers");
1172 throw std::runtime_error("fsolve(): vanishing interval");
1174 // xx[0] == left interval limit, xx[1] == right interval limit.
1175 // fx[0] == f(xx[0]), fx[1] == f(xx[1]).
1176 // We keep the root bracketed: xx[0]<xx[1] and fx[0]*fx[1]<0.
1177 numeric xx[2] = { x1<x2 ? x1 : x2,
1180 if (is_a<relational>(f_in)) {
1181 f = f_in.lhs()-f_in.rhs();
1185 const ex fx_[2] = { f.subs(x==xx[0]).evalf(),
1186 f.subs(x==xx[1]).evalf() };
1187 if (!is_a<numeric>(fx_[0]) || !is_a<numeric>(fx_[1])) {
1188 throw std::runtime_error("fsolve(): function does not evaluate numerically");
1190 numeric fx[2] = { ex_to<numeric>(fx_[0]),
1191 ex_to<numeric>(fx_[1]) };
1192 if (!fx[0].is_real() || !fx[1].is_real()) {
1193 throw std::runtime_error("fsolve(): function evaluates to complex values at interval boundaries");
1195 if (fx[0]*fx[1]>=0) {
1196 throw std::runtime_error("fsolve(): function does not change sign at interval boundaries");
1199 // The Newton-Raphson method has quadratic convergence! Simply put, it
1200 // replaces x with x-f(x)/f'(x) at each step. -f/f' is the delta:
1201 const ex ff = normal(-f/f.diff(x));
1202 int side = 0; // Start at left interval limit.
1208 ex dx_ = ff.subs(x == xx[side]).evalf();
1209 if (!is_a<numeric>(dx_))
1210 throw std::runtime_error("fsolve(): function derivative does not evaluate numerically");
1211 xx[side] += ex_to<numeric>(dx_);
1212 // Now check if Newton-Raphson method shot out of the interval
1213 bool bad_shot = (side == 0 && xx[0] < xxprev) ||
1214 (side == 1 && xx[1] > xxprev) || xx[0] > xx[1];
1216 // Compute f(x) only if new x is inside the interval.
1217 // The function might be difficult to compute numerically
1218 // or even ill defined outside the interval. Also it's
1219 // a small optimization.
1220 ex f_x = f.subs(x == xx[side]).evalf();
1221 if (!is_a<numeric>(f_x))
1222 throw std::runtime_error("fsolve(): function does not evaluate numerically");
1223 fx[side] = ex_to<numeric>(f_x);
1226 // Oops, Newton-Raphson method shot out of the interval.
1227 // Restore, and try again with the other side instead!
1234 ex dx_ = ff.subs(x == xx[side]).evalf();
1235 if (!is_a<numeric>(dx_))
1236 throw std::runtime_error("fsolve(): function derivative does not evaluate numerically [2]");
1237 xx[side] += ex_to<numeric>(dx_);
1239 ex f_x = f.subs(x==xx[side]).evalf();
1240 if (!is_a<numeric>(f_x))
1241 throw std::runtime_error("fsolve(): function does not evaluate numerically [2]");
1242 fx[side] = ex_to<numeric>(f_x);
1244 if ((fx[side]<0 && fx[!side]<0) || (fx[side]>0 && fx[!side]>0)) {
1245 // Oops, the root isn't bracketed any more.
1246 // Restore, and perform a bisection!
1250 // Ah, the bisection! Bisections converge linearly. Unfortunately,
1251 // they occur pretty often when Newton-Raphson arrives at an x too
1252 // close to the result on one side of the interval and
1253 // f(x-f(x)/f'(x)) turns out to have the same sign as f(x) due to
1254 // precision errors! Recall that this function does not have a
1255 // precision goal as one of its arguments but instead relies on
1256 // x converging to a fixed point. We speed up the (safe but slow)
1257 // bisection method by mixing in a dash of the (unsafer but faster)
1258 // secant method: Instead of splitting the interval at the
1259 // arithmetic mean (bisection), we split it nearer to the root as
1260 // determined by the secant between the values xx[0] and xx[1].
1261 // Don't set the secant_weight to one because that could disturb
1262 // the convergence in some corner cases!
1263 constexpr double secant_weight = 0.984375; // == 63/64 < 1
1264 numeric xxmid = (1-secant_weight)*0.5*(xx[0]+xx[1])
1265 + secant_weight*(xx[0]+fx[0]*(xx[0]-xx[1])/(fx[1]-fx[0]));
1266 ex fxmid_ = f.subs(x == xxmid).evalf();
1267 if (!is_a<numeric>(fxmid_))
1268 throw std::runtime_error("fsolve(): function does not evaluate numerically [3]");
1269 numeric fxmid = ex_to<numeric>(fxmid_);
1270 if (fxmid.is_zero()) {
1274 if ((fxmid<0 && fx[side]>0) || (fxmid>0 && fx[side]<0)) {
1282 } while (xxprev!=xx[side]);
1287 /* Force inclusion of functions from inifcns_gamma and inifcns_zeta
1288 * for static lib (so ginsh will see them). */
1289 unsigned force_include_tgamma = tgamma_SERIAL::serial;
1290 unsigned force_include_zeta1 = zeta1_SERIAL::serial;
1292 } // namespace GiNaC