3 * Implementation of GiNaC's initially known functions. */
6 * GiNaC Copyright (C) 1999-2011 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
30 #include "operators.h"
31 #include "relational.h"
46 static ex conjugate_evalf(const ex & arg)
48 if (is_exactly_a<numeric>(arg)) {
49 return ex_to<numeric>(arg).conjugate();
51 return conjugate_function(arg).hold();
54 static ex conjugate_eval(const ex & arg)
56 return arg.conjugate();
59 static void conjugate_print_latex(const ex & arg, const print_context & c)
61 c.s << "\\bar{"; arg.print(c); c.s << "}";
64 static ex conjugate_conjugate(const ex & arg)
69 static ex conjugate_real_part(const ex & arg)
71 return arg.real_part();
74 static ex conjugate_imag_part(const ex & arg)
76 return -arg.imag_part();
79 REGISTER_FUNCTION(conjugate_function, eval_func(conjugate_eval).
80 evalf_func(conjugate_evalf).
81 print_func<print_latex>(conjugate_print_latex).
82 conjugate_func(conjugate_conjugate).
83 real_part_func(conjugate_real_part).
84 imag_part_func(conjugate_imag_part).
85 set_name("conjugate","conjugate"));
91 static ex real_part_evalf(const ex & arg)
93 if (is_exactly_a<numeric>(arg)) {
94 return ex_to<numeric>(arg).real();
96 return real_part_function(arg).hold();
99 static ex real_part_eval(const ex & arg)
101 return arg.real_part();
104 static void real_part_print_latex(const ex & arg, const print_context & c)
106 c.s << "\\Re"; arg.print(c); c.s << "";
109 static ex real_part_conjugate(const ex & arg)
111 return real_part_function(arg).hold();
114 static ex real_part_real_part(const ex & arg)
116 return real_part_function(arg).hold();
119 static ex real_part_imag_part(const ex & arg)
124 REGISTER_FUNCTION(real_part_function, eval_func(real_part_eval).
125 evalf_func(real_part_evalf).
126 print_func<print_latex>(real_part_print_latex).
127 conjugate_func(real_part_conjugate).
128 real_part_func(real_part_real_part).
129 imag_part_func(real_part_imag_part).
130 set_name("real_part","real_part"));
136 static ex imag_part_evalf(const ex & arg)
138 if (is_exactly_a<numeric>(arg)) {
139 return ex_to<numeric>(arg).imag();
141 return imag_part_function(arg).hold();
144 static ex imag_part_eval(const ex & arg)
146 return arg.imag_part();
149 static void imag_part_print_latex(const ex & arg, const print_context & c)
151 c.s << "\\Im"; arg.print(c); c.s << "";
154 static ex imag_part_conjugate(const ex & arg)
156 return imag_part_function(arg).hold();
159 static ex imag_part_real_part(const ex & arg)
161 return imag_part_function(arg).hold();
164 static ex imag_part_imag_part(const ex & arg)
169 REGISTER_FUNCTION(imag_part_function, eval_func(imag_part_eval).
170 evalf_func(imag_part_evalf).
171 print_func<print_latex>(imag_part_print_latex).
172 conjugate_func(imag_part_conjugate).
173 real_part_func(imag_part_real_part).
174 imag_part_func(imag_part_imag_part).
175 set_name("imag_part","imag_part"));
181 static ex abs_evalf(const ex & arg)
183 if (is_exactly_a<numeric>(arg))
184 return abs(ex_to<numeric>(arg));
186 return abs(arg).hold();
189 static ex abs_eval(const ex & arg)
191 if (is_exactly_a<numeric>(arg))
192 return abs(ex_to<numeric>(arg));
194 if (arg.info(info_flags::nonnegative))
197 if (is_ex_the_function(arg, abs))
200 if (is_ex_the_function(arg, exp))
201 return exp(arg.op(0).real_part());
203 if (is_exactly_a<power>(arg)) {
204 const ex& base = arg.op(0);
205 const ex& exponent = arg.op(1);
206 if (base.info(info_flags::positive) || exponent.info(info_flags::real))
207 return pow(abs(base), exponent.real_part());
210 return abs(arg).hold();
213 static void abs_print_latex(const ex & arg, const print_context & c)
215 c.s << "{|"; arg.print(c); c.s << "|}";
218 static void abs_print_csrc_float(const ex & arg, const print_context & c)
220 c.s << "fabs("; arg.print(c); c.s << ")";
223 static ex abs_conjugate(const ex & arg)
225 return abs(arg).hold();
228 static ex abs_real_part(const ex & arg)
230 return abs(arg).hold();
233 static ex abs_imag_part(const ex& arg)
238 static ex abs_power(const ex & arg, const ex & exp)
240 if (arg.is_equal(arg.conjugate()) && ((is_a<numeric>(exp) && ex_to<numeric>(exp).is_even())
241 || exp.info(info_flags::even)))
242 return power(arg, exp);
244 return power(abs(arg), exp).hold();
247 REGISTER_FUNCTION(abs, eval_func(abs_eval).
248 evalf_func(abs_evalf).
249 print_func<print_latex>(abs_print_latex).
250 print_func<print_csrc_float>(abs_print_csrc_float).
251 print_func<print_csrc_double>(abs_print_csrc_float).
252 conjugate_func(abs_conjugate).
253 real_part_func(abs_real_part).
254 imag_part_func(abs_imag_part).
255 power_func(abs_power));
261 static ex step_evalf(const ex & arg)
263 if (is_exactly_a<numeric>(arg))
264 return step(ex_to<numeric>(arg));
266 return step(arg).hold();
269 static ex step_eval(const ex & arg)
271 if (is_exactly_a<numeric>(arg))
272 return step(ex_to<numeric>(arg));
274 else if (is_exactly_a<mul>(arg) &&
275 is_exactly_a<numeric>(arg.op(arg.nops()-1))) {
276 numeric oc = ex_to<numeric>(arg.op(arg.nops()-1));
279 // step(42*x) -> step(x)
280 return step(arg/oc).hold();
282 // step(-42*x) -> step(-x)
283 return step(-arg/oc).hold();
285 if (oc.real().is_zero()) {
287 // step(42*I*x) -> step(I*x)
288 return step(I*arg/oc).hold();
290 // step(-42*I*x) -> step(-I*x)
291 return step(-I*arg/oc).hold();
295 return step(arg).hold();
298 static ex step_series(const ex & arg,
299 const relational & rel,
303 const ex arg_pt = arg.subs(rel, subs_options::no_pattern);
304 if (arg_pt.info(info_flags::numeric)
305 && ex_to<numeric>(arg_pt).real().is_zero()
306 && !(options & series_options::suppress_branchcut))
307 throw (std::domain_error("step_series(): on imaginary axis"));
310 seq.push_back(expair(step(arg_pt), _ex0));
311 return pseries(rel,seq);
314 static ex step_conjugate(const ex& arg)
316 return step(arg).hold();
319 static ex step_real_part(const ex& arg)
321 return step(arg).hold();
324 static ex step_imag_part(const ex& arg)
329 REGISTER_FUNCTION(step, eval_func(step_eval).
330 evalf_func(step_evalf).
331 series_func(step_series).
332 conjugate_func(step_conjugate).
333 real_part_func(step_real_part).
334 imag_part_func(step_imag_part));
340 static ex csgn_evalf(const ex & arg)
342 if (is_exactly_a<numeric>(arg))
343 return csgn(ex_to<numeric>(arg));
345 return csgn(arg).hold();
348 static ex csgn_eval(const ex & arg)
350 if (is_exactly_a<numeric>(arg))
351 return csgn(ex_to<numeric>(arg));
353 else if (is_exactly_a<mul>(arg) &&
354 is_exactly_a<numeric>(arg.op(arg.nops()-1))) {
355 numeric oc = ex_to<numeric>(arg.op(arg.nops()-1));
358 // csgn(42*x) -> csgn(x)
359 return csgn(arg/oc).hold();
361 // csgn(-42*x) -> -csgn(x)
362 return -csgn(arg/oc).hold();
364 if (oc.real().is_zero()) {
366 // csgn(42*I*x) -> csgn(I*x)
367 return csgn(I*arg/oc).hold();
369 // csgn(-42*I*x) -> -csgn(I*x)
370 return -csgn(I*arg/oc).hold();
374 return csgn(arg).hold();
377 static ex csgn_series(const ex & arg,
378 const relational & rel,
382 const ex arg_pt = arg.subs(rel, subs_options::no_pattern);
383 if (arg_pt.info(info_flags::numeric)
384 && ex_to<numeric>(arg_pt).real().is_zero()
385 && !(options & series_options::suppress_branchcut))
386 throw (std::domain_error("csgn_series(): on imaginary axis"));
389 seq.push_back(expair(csgn(arg_pt), _ex0));
390 return pseries(rel,seq);
393 static ex csgn_conjugate(const ex& arg)
395 return csgn(arg).hold();
398 static ex csgn_real_part(const ex& arg)
400 return csgn(arg).hold();
403 static ex csgn_imag_part(const ex& arg)
408 static ex csgn_power(const ex & arg, const ex & exp)
410 if (is_a<numeric>(exp) && exp.info(info_flags::positive) && ex_to<numeric>(exp).is_integer()) {
411 if (ex_to<numeric>(exp).is_odd())
412 return csgn(arg).hold();
414 return power(csgn(arg), _ex2).hold();
416 return power(csgn(arg), exp).hold();
420 REGISTER_FUNCTION(csgn, eval_func(csgn_eval).
421 evalf_func(csgn_evalf).
422 series_func(csgn_series).
423 conjugate_func(csgn_conjugate).
424 real_part_func(csgn_real_part).
425 imag_part_func(csgn_imag_part).
426 power_func(csgn_power));
430 // Eta function: eta(x,y) == log(x*y) - log(x) - log(y).
431 // This function is closely related to the unwinding number K, sometimes found
432 // in modern literature: K(z) == (z-log(exp(z)))/(2*Pi*I).
435 static ex eta_evalf(const ex &x, const ex &y)
437 // It seems like we basically have to replicate the eval function here,
438 // since the expression might not be fully evaluated yet.
439 if (x.info(info_flags::positive) || y.info(info_flags::positive))
442 if (x.info(info_flags::numeric) && y.info(info_flags::numeric)) {
443 const numeric nx = ex_to<numeric>(x);
444 const numeric ny = ex_to<numeric>(y);
445 const numeric nxy = ex_to<numeric>(x*y);
447 if (nx.is_real() && nx.is_negative())
449 if (ny.is_real() && ny.is_negative())
451 if (nxy.is_real() && nxy.is_negative())
453 return evalf(I/4*Pi)*((csgn(-imag(nx))+1)*(csgn(-imag(ny))+1)*(csgn(imag(nxy))+1)-
454 (csgn(imag(nx))+1)*(csgn(imag(ny))+1)*(csgn(-imag(nxy))+1)+cut);
457 return eta(x,y).hold();
460 static ex eta_eval(const ex &x, const ex &y)
462 // trivial: eta(x,c) -> 0 if c is real and positive
463 if (x.info(info_flags::positive) || y.info(info_flags::positive))
466 if (x.info(info_flags::numeric) && y.info(info_flags::numeric)) {
467 // don't call eta_evalf here because it would call Pi.evalf()!
468 const numeric nx = ex_to<numeric>(x);
469 const numeric ny = ex_to<numeric>(y);
470 const numeric nxy = ex_to<numeric>(x*y);
472 if (nx.is_real() && nx.is_negative())
474 if (ny.is_real() && ny.is_negative())
476 if (nxy.is_real() && nxy.is_negative())
478 return (I/4)*Pi*((csgn(-imag(nx))+1)*(csgn(-imag(ny))+1)*(csgn(imag(nxy))+1)-
479 (csgn(imag(nx))+1)*(csgn(imag(ny))+1)*(csgn(-imag(nxy))+1)+cut);
482 return eta(x,y).hold();
485 static ex eta_series(const ex & x, const ex & y,
486 const relational & rel,
490 const ex x_pt = x.subs(rel, subs_options::no_pattern);
491 const ex y_pt = y.subs(rel, subs_options::no_pattern);
492 if ((x_pt.info(info_flags::numeric) && x_pt.info(info_flags::negative)) ||
493 (y_pt.info(info_flags::numeric) && y_pt.info(info_flags::negative)) ||
494 ((x_pt*y_pt).info(info_flags::numeric) && (x_pt*y_pt).info(info_flags::negative)))
495 throw (std::domain_error("eta_series(): on discontinuity"));
497 seq.push_back(expair(eta(x_pt,y_pt), _ex0));
498 return pseries(rel,seq);
501 static ex eta_conjugate(const ex & x, const ex & y)
503 return -eta(x, y).hold();
506 static ex eta_real_part(const ex & x, const ex & y)
511 static ex eta_imag_part(const ex & x, const ex & y)
513 return -I*eta(x, y).hold();
516 REGISTER_FUNCTION(eta, eval_func(eta_eval).
517 evalf_func(eta_evalf).
518 series_func(eta_series).
520 set_symmetry(sy_symm(0, 1)).
521 conjugate_func(eta_conjugate).
522 real_part_func(eta_real_part).
523 imag_part_func(eta_imag_part));
530 static ex Li2_evalf(const ex & x)
532 if (is_exactly_a<numeric>(x))
533 return Li2(ex_to<numeric>(x));
535 return Li2(x).hold();
538 static ex Li2_eval(const ex & x)
540 if (x.info(info_flags::numeric)) {
545 if (x.is_equal(_ex1))
546 return power(Pi,_ex2)/_ex6;
547 // Li2(1/2) -> Pi^2/12 - log(2)^2/2
548 if (x.is_equal(_ex1_2))
549 return power(Pi,_ex2)/_ex12 + power(log(_ex2),_ex2)*_ex_1_2;
550 // Li2(-1) -> -Pi^2/12
551 if (x.is_equal(_ex_1))
552 return -power(Pi,_ex2)/_ex12;
553 // Li2(I) -> -Pi^2/48+Catalan*I
555 return power(Pi,_ex2)/_ex_48 + Catalan*I;
556 // Li2(-I) -> -Pi^2/48-Catalan*I
558 return power(Pi,_ex2)/_ex_48 - Catalan*I;
560 if (!x.info(info_flags::crational))
561 return Li2(ex_to<numeric>(x));
564 return Li2(x).hold();
567 static ex Li2_deriv(const ex & x, unsigned deriv_param)
569 GINAC_ASSERT(deriv_param==0);
571 // d/dx Li2(x) -> -log(1-x)/x
572 return -log(_ex1-x)/x;
575 static ex Li2_series(const ex &x, const relational &rel, int order, unsigned options)
577 const ex x_pt = x.subs(rel, subs_options::no_pattern);
578 if (x_pt.info(info_flags::numeric)) {
579 // First special case: x==0 (derivatives have poles)
580 if (x_pt.is_zero()) {
582 // The problem is that in d/dx Li2(x==0) == -log(1-x)/x we cannot
583 // simply substitute x==0. The limit, however, exists: it is 1.
584 // We also know all higher derivatives' limits:
585 // (d/dx)^n Li2(x) == n!/n^2.
586 // So the primitive series expansion is
587 // Li2(x==0) == x + x^2/4 + x^3/9 + ...
589 // We first construct such a primitive series expansion manually in
590 // a dummy symbol s and then insert the argument's series expansion
591 // for s. Reexpanding the resulting series returns the desired
595 // manually construct the primitive expansion
596 for (int i=1; i<order; ++i)
597 ser += pow(s,i) / pow(numeric(i), *_num2_p);
598 // substitute the argument's series expansion
599 ser = ser.subs(s==x.series(rel, order), subs_options::no_pattern);
600 // maybe that was terminating, so add a proper order term
602 nseq.push_back(expair(Order(_ex1), order));
603 ser += pseries(rel, nseq);
604 // reexpanding it will collapse the series again
605 return ser.series(rel, order);
606 // NB: Of course, this still does not allow us to compute anything
607 // like sin(Li2(x)).series(x==0,2), since then this code here is
608 // not reached and the derivative of sin(Li2(x)) doesn't allow the
609 // substitution x==0. Probably limits *are* needed for the general
610 // cases. In case L'Hospital's rule is implemented for limits and
611 // basic::series() takes care of this, this whole block is probably
614 // second special case: x==1 (branch point)
615 if (x_pt.is_equal(_ex1)) {
617 // construct series manually in a dummy symbol s
620 // manually construct the primitive expansion
621 for (int i=1; i<order; ++i)
622 ser += pow(1-s,i) * (numeric(1,i)*(I*Pi+log(s-1)) - numeric(1,i*i));
623 // substitute the argument's series expansion
624 ser = ser.subs(s==x.series(rel, order), subs_options::no_pattern);
625 // maybe that was terminating, so add a proper order term
627 nseq.push_back(expair(Order(_ex1), order));
628 ser += pseries(rel, nseq);
629 // reexpanding it will collapse the series again
630 return ser.series(rel, order);
632 // third special case: x real, >=1 (branch cut)
633 if (!(options & series_options::suppress_branchcut) &&
634 ex_to<numeric>(x_pt).is_real() && ex_to<numeric>(x_pt)>1) {
636 // This is the branch cut: assemble the primitive series manually
637 // and then add the corresponding complex step function.
638 const symbol &s = ex_to<symbol>(rel.lhs());
639 const ex point = rel.rhs();
642 // zeroth order term:
643 seq.push_back(expair(Li2(x_pt), _ex0));
644 // compute the intermediate terms:
645 ex replarg = series(Li2(x), s==foo, order);
646 for (size_t i=1; i<replarg.nops()-1; ++i)
647 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));
648 // append an order term:
649 seq.push_back(expair(Order(_ex1), replarg.nops()-1));
650 return pseries(rel, seq);
653 // all other cases should be safe, by now:
654 throw do_taylor(); // caught by function::series()
657 static ex Li2_conjugate(const ex & x)
659 // conjugate(Li2(x))==Li2(conjugate(x)) unless on the branch cuts which
660 // run along the positive real axis beginning at 1.
661 if (x.info(info_flags::negative)) {
662 return Li2(x).hold();
664 if (is_exactly_a<numeric>(x) &&
665 (!x.imag_part().is_zero() || x < *_num1_p)) {
666 return Li2(x.conjugate());
668 return conjugate_function(Li2(x)).hold();
671 REGISTER_FUNCTION(Li2, eval_func(Li2_eval).
672 evalf_func(Li2_evalf).
673 derivative_func(Li2_deriv).
674 series_func(Li2_series).
675 conjugate_func(Li2_conjugate).
676 latex_name("\\mathrm{Li}_2"));
682 static ex Li3_eval(const ex & x)
686 return Li3(x).hold();
689 REGISTER_FUNCTION(Li3, eval_func(Li3_eval).
690 latex_name("\\mathrm{Li}_3"));
693 // Derivatives of Riemann's Zeta-function zetaderiv(0,x)==zeta(x)
696 static ex zetaderiv_eval(const ex & n, const ex & x)
698 if (n.info(info_flags::numeric)) {
699 // zetaderiv(0,x) -> zeta(x)
701 return zeta(x).hold();
704 return zetaderiv(n, x).hold();
707 static ex zetaderiv_deriv(const ex & n, const ex & x, unsigned deriv_param)
709 GINAC_ASSERT(deriv_param<2);
711 if (deriv_param==0) {
713 throw(std::logic_error("cannot diff zetaderiv(n,x) with respect to n"));
716 return zetaderiv(n+1,x);
719 REGISTER_FUNCTION(zetaderiv, eval_func(zetaderiv_eval).
720 derivative_func(zetaderiv_deriv).
721 latex_name("\\zeta^\\prime"));
727 static ex factorial_evalf(const ex & x)
729 return factorial(x).hold();
732 static ex factorial_eval(const ex & x)
734 if (is_exactly_a<numeric>(x))
735 return factorial(ex_to<numeric>(x));
737 return factorial(x).hold();
740 static void factorial_print_dflt_latex(const ex & x, const print_context & c)
742 if (is_exactly_a<symbol>(x) ||
743 is_exactly_a<constant>(x) ||
744 is_exactly_a<function>(x)) {
745 x.print(c); c.s << "!";
747 c.s << "("; x.print(c); c.s << ")!";
751 static ex factorial_conjugate(const ex & x)
753 return factorial(x).hold();
756 static ex factorial_real_part(const ex & x)
758 return factorial(x).hold();
761 static ex factorial_imag_part(const ex & x)
766 REGISTER_FUNCTION(factorial, eval_func(factorial_eval).
767 evalf_func(factorial_evalf).
768 print_func<print_dflt>(factorial_print_dflt_latex).
769 print_func<print_latex>(factorial_print_dflt_latex).
770 conjugate_func(factorial_conjugate).
771 real_part_func(factorial_real_part).
772 imag_part_func(factorial_imag_part));
778 static ex binomial_evalf(const ex & x, const ex & y)
780 return binomial(x, y).hold();
783 static ex binomial_sym(const ex & x, const numeric & y)
785 if (y.is_integer()) {
786 if (y.is_nonneg_integer()) {
787 const unsigned N = y.to_int();
788 if (N == 0) return _ex1;
789 if (N == 1) return x;
791 for (unsigned i = 2; i <= N; ++i)
792 t = (t * (x + i - y - 1)).expand() / i;
798 return binomial(x, y).hold();
801 static ex binomial_eval(const ex & x, const ex &y)
803 if (is_exactly_a<numeric>(y)) {
804 if (is_exactly_a<numeric>(x) && ex_to<numeric>(x).is_integer())
805 return binomial(ex_to<numeric>(x), ex_to<numeric>(y));
807 return binomial_sym(x, ex_to<numeric>(y));
809 return binomial(x, y).hold();
812 // At the moment the numeric evaluation of a binomail function always
813 // gives a real number, but if this would be implemented using the gamma
814 // function, also complex conjugation should be changed (or rather, deleted).
815 static ex binomial_conjugate(const ex & x, const ex & y)
817 return binomial(x,y).hold();
820 static ex binomial_real_part(const ex & x, const ex & y)
822 return binomial(x,y).hold();
825 static ex binomial_imag_part(const ex & x, const ex & y)
830 REGISTER_FUNCTION(binomial, eval_func(binomial_eval).
831 evalf_func(binomial_evalf).
832 conjugate_func(binomial_conjugate).
833 real_part_func(binomial_real_part).
834 imag_part_func(binomial_imag_part));
837 // Order term function (for truncated power series)
840 static ex Order_eval(const ex & x)
842 if (is_exactly_a<numeric>(x)) {
845 return Order(_ex1).hold();
848 } else if (is_exactly_a<mul>(x)) {
849 const mul &m = ex_to<mul>(x);
850 // O(c*expr) -> O(expr)
851 if (is_exactly_a<numeric>(m.op(m.nops() - 1)))
852 return Order(x / m.op(m.nops() - 1)).hold();
854 return Order(x).hold();
857 static ex Order_series(const ex & x, const relational & r, int order, unsigned options)
859 // Just wrap the function into a pseries object
861 GINAC_ASSERT(is_a<symbol>(r.lhs()));
862 const symbol &s = ex_to<symbol>(r.lhs());
863 new_seq.push_back(expair(Order(_ex1), numeric(std::min(x.ldegree(s), order))));
864 return pseries(r, new_seq);
867 static ex Order_conjugate(const ex & x)
869 return Order(x).hold();
872 static ex Order_real_part(const ex & x)
874 return Order(x).hold();
877 static ex Order_imag_part(const ex & x)
879 if(x.info(info_flags::real))
881 return Order(x).hold();
884 // Differentiation is handled in function::derivative because of its special requirements
886 REGISTER_FUNCTION(Order, eval_func(Order_eval).
887 series_func(Order_series).
888 latex_name("\\mathcal{O}").
889 conjugate_func(Order_conjugate).
890 real_part_func(Order_real_part).
891 imag_part_func(Order_imag_part));
894 // Solve linear system
897 ex lsolve(const ex &eqns, const ex &symbols, unsigned options)
899 // solve a system of linear equations
900 if (eqns.info(info_flags::relation_equal)) {
901 if (!symbols.info(info_flags::symbol))
902 throw(std::invalid_argument("lsolve(): 2nd argument must be a symbol"));
903 const ex sol = lsolve(lst(eqns),lst(symbols));
905 GINAC_ASSERT(sol.nops()==1);
906 GINAC_ASSERT(is_exactly_a<relational>(sol.op(0)));
908 return sol.op(0).op(1); // return rhs of first solution
912 if (!eqns.info(info_flags::list)) {
913 throw(std::invalid_argument("lsolve(): 1st argument must be a list or an equation"));
915 for (size_t i=0; i<eqns.nops(); i++) {
916 if (!eqns.op(i).info(info_flags::relation_equal)) {
917 throw(std::invalid_argument("lsolve(): 1st argument must be a list of equations"));
920 if (!symbols.info(info_flags::list)) {
921 throw(std::invalid_argument("lsolve(): 2nd argument must be a list or a symbol"));
923 for (size_t i=0; i<symbols.nops(); i++) {
924 if (!symbols.op(i).info(info_flags::symbol)) {
925 throw(std::invalid_argument("lsolve(): 2nd argument must be a list of symbols"));
929 // build matrix from equation system
930 matrix sys(eqns.nops(),symbols.nops());
931 matrix rhs(eqns.nops(),1);
932 matrix vars(symbols.nops(),1);
934 for (size_t r=0; r<eqns.nops(); r++) {
935 const ex eq = eqns.op(r).op(0)-eqns.op(r).op(1); // lhs-rhs==0
937 for (size_t c=0; c<symbols.nops(); c++) {
938 const ex co = eq.coeff(ex_to<symbol>(symbols.op(c)),1);
939 linpart -= co*symbols.op(c);
942 linpart = linpart.expand();
946 // test if system is linear and fill vars matrix
947 for (size_t i=0; i<symbols.nops(); i++) {
948 vars(i,0) = symbols.op(i);
949 if (sys.has(symbols.op(i)))
950 throw(std::logic_error("lsolve: system is not linear"));
951 if (rhs.has(symbols.op(i)))
952 throw(std::logic_error("lsolve: system is not linear"));
957 solution = sys.solve(vars,rhs,options);
958 } catch (const std::runtime_error & e) {
959 // Probably singular matrix or otherwise overdetermined system:
960 // It is consistent to return an empty list
963 GINAC_ASSERT(solution.cols()==1);
964 GINAC_ASSERT(solution.rows()==symbols.nops());
966 // return list of equations of the form lst(var1==sol1,var2==sol2,...)
968 for (size_t i=0; i<symbols.nops(); i++)
969 sollist.append(symbols.op(i)==solution(i,0));
975 // Find real root of f(x) numerically
979 fsolve(const ex& f_in, const symbol& x, const numeric& x1, const numeric& x2)
981 if (!x1.is_real() || !x2.is_real()) {
982 throw std::runtime_error("fsolve(): interval not bounded by real numbers");
985 throw std::runtime_error("fsolve(): vanishing interval");
987 // xx[0] == left interval limit, xx[1] == right interval limit.
988 // fx[0] == f(xx[0]), fx[1] == f(xx[1]).
989 // We keep the root bracketed: xx[0]<xx[1] and fx[0]*fx[1]<0.
990 numeric xx[2] = { x1<x2 ? x1 : x2,
993 if (is_a<relational>(f_in)) {
994 f = f_in.lhs()-f_in.rhs();
998 const ex fx_[2] = { f.subs(x==xx[0]).evalf(),
999 f.subs(x==xx[1]).evalf() };
1000 if (!is_a<numeric>(fx_[0]) || !is_a<numeric>(fx_[1])) {
1001 throw std::runtime_error("fsolve(): function does not evaluate numerically");
1003 numeric fx[2] = { ex_to<numeric>(fx_[0]),
1004 ex_to<numeric>(fx_[1]) };
1005 if (!fx[0].is_real() || !fx[1].is_real()) {
1006 throw std::runtime_error("fsolve(): function evaluates to complex values at interval boundaries");
1008 if (fx[0]*fx[1]>=0) {
1009 throw std::runtime_error("fsolve(): function does not change sign at interval boundaries");
1012 // The Newton-Raphson method has quadratic convergence! Simply put, it
1013 // replaces x with x-f(x)/f'(x) at each step. -f/f' is the delta:
1014 const ex ff = normal(-f/f.diff(x));
1015 int side = 0; // Start at left interval limit.
1021 ex dx_ = ff.subs(x == xx[side]).evalf();
1022 if (!is_a<numeric>(dx_))
1023 throw std::runtime_error("fsolve(): function derivative does not evaluate numerically");
1024 xx[side] += ex_to<numeric>(dx_);
1025 // Now check if Newton-Raphson method shot out of the interval
1026 bool bad_shot = (side == 0 && xx[0] < xxprev) ||
1027 (side == 1 && xx[1] > xxprev) || xx[0] > xx[1];
1029 // Compute f(x) only if new x is inside the interval.
1030 // The function might be difficult to compute numerically
1031 // or even ill defined outside the interval. Also it's
1032 // a small optimization.
1033 ex f_x = f.subs(x == xx[side]).evalf();
1034 if (!is_a<numeric>(f_x))
1035 throw std::runtime_error("fsolve(): function does not evaluate numerically");
1036 fx[side] = ex_to<numeric>(f_x);
1039 // Oops, Newton-Raphson method shot out of the interval.
1040 // Restore, and try again with the other side instead!
1047 ex dx_ = ff.subs(x == xx[side]).evalf();
1048 if (!is_a<numeric>(dx_))
1049 throw std::runtime_error("fsolve(): function derivative does not evaluate numerically [2]");
1050 xx[side] += ex_to<numeric>(dx_);
1052 ex f_x = f.subs(x==xx[side]).evalf();
1053 if (!is_a<numeric>(f_x))
1054 throw std::runtime_error("fsolve(): function does not evaluate numerically [2]");
1055 fx[side] = ex_to<numeric>(f_x);
1057 if ((fx[side]<0 && fx[!side]<0) || (fx[side]>0 && fx[!side]>0)) {
1058 // Oops, the root isn't bracketed any more.
1059 // Restore, and perform a bisection!
1063 // Ah, the bisection! Bisections converge linearly. Unfortunately,
1064 // they occur pretty often when Newton-Raphson arrives at an x too
1065 // close to the result on one side of the interval and
1066 // f(x-f(x)/f'(x)) turns out to have the same sign as f(x) due to
1067 // precision errors! Recall that this function does not have a
1068 // precision goal as one of its arguments but instead relies on
1069 // x converging to a fixed point. We speed up the (safe but slow)
1070 // bisection method by mixing in a dash of the (unsafer but faster)
1071 // secant method: Instead of splitting the interval at the
1072 // arithmetic mean (bisection), we split it nearer to the root as
1073 // determined by the secant between the values xx[0] and xx[1].
1074 // Don't set the secant_weight to one because that could disturb
1075 // the convergence in some corner cases!
1076 static const double secant_weight = 0.984375; // == 63/64 < 1
1077 numeric xxmid = (1-secant_weight)*0.5*(xx[0]+xx[1])
1078 + secant_weight*(xx[0]+fx[0]*(xx[0]-xx[1])/(fx[1]-fx[0]));
1079 ex fxmid_ = f.subs(x == xxmid).evalf();
1080 if (!is_a<numeric>(fxmid_))
1081 throw std::runtime_error("fsolve(): function does not evaluate numerically [3]");
1082 numeric fxmid = ex_to<numeric>(fxmid_);
1083 if (fxmid.is_zero()) {
1087 if ((fxmid<0 && fx[side]>0) || (fxmid>0 && fx[side]<0)) {
1095 } while (xxprev!=xx[side]);
1100 /* Force inclusion of functions from inifcns_gamma and inifcns_zeta
1101 * for static lib (so ginsh will see them). */
1102 unsigned force_include_tgamma = tgamma_SERIAL::serial;
1103 unsigned force_include_zeta1 = zeta1_SERIAL::serial;
1105 } // namespace GiNaC