a8f82d8ea0413efaa02e63ea29d9a9919759f793
[ginac.git] / ginac / inifcns.cpp
1 /** @file inifcns.cpp
2  *
3  *  Implementation of GiNaC's initially known functions. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2005 Johannes Gutenberg University Mainz, Germany
7  *
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.
12  *
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.
17  *
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
21  */
22
23 #include <vector>
24 #include <stdexcept>
25
26 #include "inifcns.h"
27 #include "ex.h"
28 #include "constant.h"
29 #include "lst.h"
30 #include "matrix.h"
31 #include "mul.h"
32 #include "power.h"
33 #include "operators.h"
34 #include "relational.h"
35 #include "pseries.h"
36 #include "symbol.h"
37 #include "symmetry.h"
38 #include "utils.h"
39
40 namespace GiNaC {
41
42 //////////
43 // complex conjugate
44 //////////
45
46 static ex conjugate_evalf(const ex & arg)
47 {
48         if (is_exactly_a<numeric>(arg)) {
49                 return ex_to<numeric>(arg).conjugate();
50         }
51         return conjugate_function(arg).hold();
52 }
53
54 static ex conjugate_eval(const ex & arg)
55 {
56         return arg.conjugate();
57 }
58
59 static void conjugate_print_latex(const ex & arg, const print_context & c)
60 {
61         c.s << "\\bar{"; arg.print(c); c.s << "}";
62 }
63
64 static ex conjugate_conjugate(const ex & arg)
65 {
66         return arg;
67 }
68
69 REGISTER_FUNCTION(conjugate_function, eval_func(conjugate_eval).
70                                       evalf_func(conjugate_evalf).
71                                       print_func<print_latex>(conjugate_print_latex).
72                                       conjugate_func(conjugate_conjugate).
73                                       set_name("conjugate","conjugate"));
74
75 //////////
76 // absolute value
77 //////////
78
79 static ex abs_evalf(const ex & arg)
80 {
81         if (is_exactly_a<numeric>(arg))
82                 return abs(ex_to<numeric>(arg));
83         
84         return abs(arg).hold();
85 }
86
87 static ex abs_eval(const ex & arg)
88 {
89         if (is_exactly_a<numeric>(arg))
90                 return abs(ex_to<numeric>(arg));
91         else
92                 return abs(arg).hold();
93 }
94
95 static void abs_print_latex(const ex & arg, const print_context & c)
96 {
97         c.s << "{|"; arg.print(c); c.s << "|}";
98 }
99
100 static void abs_print_csrc_float(const ex & arg, const print_context & c)
101 {
102         c.s << "fabs("; arg.print(c); c.s << ")";
103 }
104
105 static ex abs_conjugate(const ex & arg)
106 {
107         return abs(arg);
108 }
109
110 static ex abs_power(const ex & arg, const ex & exp)
111 {
112         if (arg.is_equal(arg.conjugate()) && is_a<numeric>(exp) && ex_to<numeric>(exp).is_even())
113                 return power(arg, exp);
114         else
115                 return power(abs(arg), exp).hold();
116 }
117
118 REGISTER_FUNCTION(abs, eval_func(abs_eval).
119                        evalf_func(abs_evalf).
120                        print_func<print_latex>(abs_print_latex).
121                        print_func<print_csrc_float>(abs_print_csrc_float).
122                        print_func<print_csrc_double>(abs_print_csrc_float).
123                        conjugate_func(abs_conjugate).
124                        power_func(abs_power));
125
126 //////////
127 // Step function
128 //////////
129
130 static ex step_evalf(const ex & arg)
131 {
132         if (is_exactly_a<numeric>(arg))
133                 return step(ex_to<numeric>(arg));
134         
135         return step(arg).hold();
136 }
137
138 static ex step_eval(const ex & arg)
139 {
140         if (is_exactly_a<numeric>(arg))
141                 return step(ex_to<numeric>(arg));
142         
143         else if (is_exactly_a<mul>(arg) &&
144                  is_exactly_a<numeric>(arg.op(arg.nops()-1))) {
145                 numeric oc = ex_to<numeric>(arg.op(arg.nops()-1));
146                 if (oc.is_real()) {
147                         if (oc > 0)
148                                 // step(42*x) -> step(x)
149                                 return step(arg/oc).hold();
150                         else
151                                 // step(-42*x) -> step(-x)
152                                 return step(-arg/oc).hold();
153                 }
154                 if (oc.real().is_zero()) {
155                         if (oc.imag() > 0)
156                                 // step(42*I*x) -> step(I*x)
157                                 return step(I*arg/oc).hold();
158                         else
159                                 // step(-42*I*x) -> step(-I*x)
160                                 return step(-I*arg/oc).hold();
161                 }
162         }
163         
164         return step(arg).hold();
165 }
166
167 static ex step_series(const ex & arg,
168                       const relational & rel,
169                       int order,
170                       unsigned options)
171 {
172         const ex arg_pt = arg.subs(rel, subs_options::no_pattern);
173         if (arg_pt.info(info_flags::numeric)
174             && ex_to<numeric>(arg_pt).real().is_zero()
175             && !(options & series_options::suppress_branchcut))
176                 throw (std::domain_error("step_series(): on imaginary axis"));
177         
178         epvector seq;
179         seq.push_back(expair(step(arg_pt), _ex0));
180         return pseries(rel,seq);
181 }
182
183 static ex step_conjugate(const ex& arg)
184 {
185         return step(arg);
186 }
187
188 REGISTER_FUNCTION(step, eval_func(step_eval).
189                         evalf_func(step_evalf).
190                         series_func(step_series).
191                         conjugate_func(step_conjugate));
192
193 //////////
194 // Complex sign
195 //////////
196
197 static ex csgn_evalf(const ex & arg)
198 {
199         if (is_exactly_a<numeric>(arg))
200                 return csgn(ex_to<numeric>(arg));
201         
202         return csgn(arg).hold();
203 }
204
205 static ex csgn_eval(const ex & arg)
206 {
207         if (is_exactly_a<numeric>(arg))
208                 return csgn(ex_to<numeric>(arg));
209         
210         else if (is_exactly_a<mul>(arg) &&
211                  is_exactly_a<numeric>(arg.op(arg.nops()-1))) {
212                 numeric oc = ex_to<numeric>(arg.op(arg.nops()-1));
213                 if (oc.is_real()) {
214                         if (oc > 0)
215                                 // csgn(42*x) -> csgn(x)
216                                 return csgn(arg/oc).hold();
217                         else
218                                 // csgn(-42*x) -> -csgn(x)
219                                 return -csgn(arg/oc).hold();
220                 }
221                 if (oc.real().is_zero()) {
222                         if (oc.imag() > 0)
223                                 // csgn(42*I*x) -> csgn(I*x)
224                                 return csgn(I*arg/oc).hold();
225                         else
226                                 // csgn(-42*I*x) -> -csgn(I*x)
227                                 return -csgn(I*arg/oc).hold();
228                 }
229         }
230         
231         return csgn(arg).hold();
232 }
233
234 static ex csgn_series(const ex & arg,
235                       const relational & rel,
236                       int order,
237                       unsigned options)
238 {
239         const ex arg_pt = arg.subs(rel, subs_options::no_pattern);
240         if (arg_pt.info(info_flags::numeric)
241             && ex_to<numeric>(arg_pt).real().is_zero()
242             && !(options & series_options::suppress_branchcut))
243                 throw (std::domain_error("csgn_series(): on imaginary axis"));
244         
245         epvector seq;
246         seq.push_back(expair(csgn(arg_pt), _ex0));
247         return pseries(rel,seq);
248 }
249
250 static ex csgn_conjugate(const ex& arg)
251 {
252         return csgn(arg);
253 }
254
255 static ex csgn_power(const ex & arg, const ex & exp)
256 {
257         if (is_a<numeric>(exp) && exp.info(info_flags::positive) && ex_to<numeric>(exp).is_integer()) {
258                 if (ex_to<numeric>(exp).is_odd())
259                         return csgn(arg);
260                 else
261                         return power(csgn(arg), _ex2).hold();
262         } else
263                 return power(csgn(arg), exp).hold();
264 }
265
266
267 REGISTER_FUNCTION(csgn, eval_func(csgn_eval).
268                         evalf_func(csgn_evalf).
269                         series_func(csgn_series).
270                         conjugate_func(csgn_conjugate).
271                         power_func(csgn_power));
272
273
274 //////////
275 // Eta function: eta(x,y) == log(x*y) - log(x) - log(y).
276 // This function is closely related to the unwinding number K, sometimes found
277 // in modern literature: K(z) == (z-log(exp(z)))/(2*Pi*I).
278 //////////
279
280 static ex eta_evalf(const ex &x, const ex &y)
281 {
282         // It seems like we basically have to replicate the eval function here,
283         // since the expression might not be fully evaluated yet.
284         if (x.info(info_flags::positive) || y.info(info_flags::positive))
285                 return _ex0;
286
287         if (x.info(info_flags::numeric) &&      y.info(info_flags::numeric)) {
288                 const numeric nx = ex_to<numeric>(x);
289                 const numeric ny = ex_to<numeric>(y);
290                 const numeric nxy = ex_to<numeric>(x*y);
291                 int cut = 0;
292                 if (nx.is_real() && nx.is_negative())
293                         cut -= 4;
294                 if (ny.is_real() && ny.is_negative())
295                         cut -= 4;
296                 if (nxy.is_real() && nxy.is_negative())
297                         cut += 4;
298                 return evalf(I/4*Pi)*((csgn(-imag(nx))+1)*(csgn(-imag(ny))+1)*(csgn(imag(nxy))+1)-
299                                       (csgn(imag(nx))+1)*(csgn(imag(ny))+1)*(csgn(-imag(nxy))+1)+cut);
300         }
301
302         return eta(x,y).hold();
303 }
304
305 static ex eta_eval(const ex &x, const ex &y)
306 {
307         // trivial:  eta(x,c) -> 0  if c is real and positive
308         if (x.info(info_flags::positive) || y.info(info_flags::positive))
309                 return _ex0;
310
311         if (x.info(info_flags::numeric) &&      y.info(info_flags::numeric)) {
312                 // don't call eta_evalf here because it would call Pi.evalf()!
313                 const numeric nx = ex_to<numeric>(x);
314                 const numeric ny = ex_to<numeric>(y);
315                 const numeric nxy = ex_to<numeric>(x*y);
316                 int cut = 0;
317                 if (nx.is_real() && nx.is_negative())
318                         cut -= 4;
319                 if (ny.is_real() && ny.is_negative())
320                         cut -= 4;
321                 if (nxy.is_real() && nxy.is_negative())
322                         cut += 4;
323                 return (I/4)*Pi*((csgn(-imag(nx))+1)*(csgn(-imag(ny))+1)*(csgn(imag(nxy))+1)-
324                                  (csgn(imag(nx))+1)*(csgn(imag(ny))+1)*(csgn(-imag(nxy))+1)+cut);
325         }
326         
327         return eta(x,y).hold();
328 }
329
330 static ex eta_series(const ex & x, const ex & y,
331                      const relational & rel,
332                      int order,
333                      unsigned options)
334 {
335         const ex x_pt = x.subs(rel, subs_options::no_pattern);
336         const ex y_pt = y.subs(rel, subs_options::no_pattern);
337         if ((x_pt.info(info_flags::numeric) && x_pt.info(info_flags::negative)) ||
338             (y_pt.info(info_flags::numeric) && y_pt.info(info_flags::negative)) ||
339             ((x_pt*y_pt).info(info_flags::numeric) && (x_pt*y_pt).info(info_flags::negative)))
340                         throw (std::domain_error("eta_series(): on discontinuity"));
341         epvector seq;
342         seq.push_back(expair(eta(x_pt,y_pt), _ex0));
343         return pseries(rel,seq);
344 }
345
346 static ex eta_conjugate(const ex & x, const ex & y)
347 {
348         return -eta(x,y);
349 }
350
351 REGISTER_FUNCTION(eta, eval_func(eta_eval).
352                        evalf_func(eta_evalf).
353                        series_func(eta_series).
354                        latex_name("\\eta").
355                        set_symmetry(sy_symm(0, 1)).
356                        conjugate_func(eta_conjugate));
357
358
359 //////////
360 // dilogarithm
361 //////////
362
363 static ex Li2_evalf(const ex & x)
364 {
365         if (is_exactly_a<numeric>(x))
366                 return Li2(ex_to<numeric>(x));
367         
368         return Li2(x).hold();
369 }
370
371 static ex Li2_eval(const ex & x)
372 {
373         if (x.info(info_flags::numeric)) {
374                 // Li2(0) -> 0
375                 if (x.is_zero())
376                         return _ex0;
377                 // Li2(1) -> Pi^2/6
378                 if (x.is_equal(_ex1))
379                         return power(Pi,_ex2)/_ex6;
380                 // Li2(1/2) -> Pi^2/12 - log(2)^2/2
381                 if (x.is_equal(_ex1_2))
382                         return power(Pi,_ex2)/_ex12 + power(log(_ex2),_ex2)*_ex_1_2;
383                 // Li2(-1) -> -Pi^2/12
384                 if (x.is_equal(_ex_1))
385                         return -power(Pi,_ex2)/_ex12;
386                 // Li2(I) -> -Pi^2/48+Catalan*I
387                 if (x.is_equal(I))
388                         return power(Pi,_ex2)/_ex_48 + Catalan*I;
389                 // Li2(-I) -> -Pi^2/48-Catalan*I
390                 if (x.is_equal(-I))
391                         return power(Pi,_ex2)/_ex_48 - Catalan*I;
392                 // Li2(float)
393                 if (!x.info(info_flags::crational))
394                         return Li2(ex_to<numeric>(x));
395         }
396         
397         return Li2(x).hold();
398 }
399
400 static ex Li2_deriv(const ex & x, unsigned deriv_param)
401 {
402         GINAC_ASSERT(deriv_param==0);
403         
404         // d/dx Li2(x) -> -log(1-x)/x
405         return -log(_ex1-x)/x;
406 }
407
408 static ex Li2_series(const ex &x, const relational &rel, int order, unsigned options)
409 {
410         const ex x_pt = x.subs(rel, subs_options::no_pattern);
411         if (x_pt.info(info_flags::numeric)) {
412                 // First special case: x==0 (derivatives have poles)
413                 if (x_pt.is_zero()) {
414                         // method:
415                         // The problem is that in d/dx Li2(x==0) == -log(1-x)/x we cannot 
416                         // simply substitute x==0.  The limit, however, exists: it is 1.
417                         // We also know all higher derivatives' limits:
418                         // (d/dx)^n Li2(x) == n!/n^2.
419                         // So the primitive series expansion is
420                         // Li2(x==0) == x + x^2/4 + x^3/9 + ...
421                         // and so on.
422                         // We first construct such a primitive series expansion manually in
423                         // a dummy symbol s and then insert the argument's series expansion
424                         // for s.  Reexpanding the resulting series returns the desired
425                         // result.
426                         const symbol s;
427                         ex ser;
428                         // manually construct the primitive expansion
429                         for (int i=1; i<order; ++i)
430                                 ser += pow(s,i) / pow(numeric(i), *_num2_p);
431                         // substitute the argument's series expansion
432                         ser = ser.subs(s==x.series(rel, order), subs_options::no_pattern);
433                         // maybe that was terminating, so add a proper order term
434                         epvector nseq;
435                         nseq.push_back(expair(Order(_ex1), order));
436                         ser += pseries(rel, nseq);
437                         // reexpanding it will collapse the series again
438                         return ser.series(rel, order);
439                         // NB: Of course, this still does not allow us to compute anything
440                         // like sin(Li2(x)).series(x==0,2), since then this code here is
441                         // not reached and the derivative of sin(Li2(x)) doesn't allow the
442                         // substitution x==0.  Probably limits *are* needed for the general
443                         // cases.  In case L'Hospital's rule is implemented for limits and
444                         // basic::series() takes care of this, this whole block is probably
445                         // obsolete!
446                 }
447                 // second special case: x==1 (branch point)
448                 if (x_pt.is_equal(_ex1)) {
449                         // method:
450                         // construct series manually in a dummy symbol s
451                         const symbol s;
452                         ex ser = zeta(_ex2);
453                         // manually construct the primitive expansion
454                         for (int i=1; i<order; ++i)
455                                 ser += pow(1-s,i) * (numeric(1,i)*(I*Pi+log(s-1)) - numeric(1,i*i));
456                         // substitute the argument's series expansion
457                         ser = ser.subs(s==x.series(rel, order), subs_options::no_pattern);
458                         // maybe that was terminating, so add a proper order term
459                         epvector nseq;
460                         nseq.push_back(expair(Order(_ex1), order));
461                         ser += pseries(rel, nseq);
462                         // reexpanding it will collapse the series again
463                         return ser.series(rel, order);
464                 }
465                 // third special case: x real, >=1 (branch cut)
466                 if (!(options & series_options::suppress_branchcut) &&
467                         ex_to<numeric>(x_pt).is_real() && ex_to<numeric>(x_pt)>1) {
468                         // method:
469                         // This is the branch cut: assemble the primitive series manually
470                         // and then add the corresponding complex step function.
471                         const symbol &s = ex_to<symbol>(rel.lhs());
472                         const ex point = rel.rhs();
473                         const symbol foo;
474                         epvector seq;
475                         // zeroth order term:
476                         seq.push_back(expair(Li2(x_pt), _ex0));
477                         // compute the intermediate terms:
478                         ex replarg = series(Li2(x), s==foo, order);
479                         for (size_t i=1; i<replarg.nops()-1; ++i)
480                                 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));
481                         // append an order term:
482                         seq.push_back(expair(Order(_ex1), replarg.nops()-1));
483                         return pseries(rel, seq);
484                 }
485         }
486         // all other cases should be safe, by now:
487         throw do_taylor();  // caught by function::series()
488 }
489
490 REGISTER_FUNCTION(Li2, eval_func(Li2_eval).
491                        evalf_func(Li2_evalf).
492                        derivative_func(Li2_deriv).
493                        series_func(Li2_series).
494                        latex_name("\\mbox{Li}_2"));
495
496 //////////
497 // trilogarithm
498 //////////
499
500 static ex Li3_eval(const ex & x)
501 {
502         if (x.is_zero())
503                 return x;
504         return Li3(x).hold();
505 }
506
507 REGISTER_FUNCTION(Li3, eval_func(Li3_eval).
508                        latex_name("\\mbox{Li}_3"));
509
510 //////////
511 // Derivatives of Riemann's Zeta-function  zetaderiv(0,x)==zeta(x)
512 //////////
513
514 static ex zetaderiv_eval(const ex & n, const ex & x)
515 {
516         if (n.info(info_flags::numeric)) {
517                 // zetaderiv(0,x) -> zeta(x)
518                 if (n.is_zero())
519                         return zeta(x);
520         }
521         
522         return zetaderiv(n, x).hold();
523 }
524
525 static ex zetaderiv_deriv(const ex & n, const ex & x, unsigned deriv_param)
526 {
527         GINAC_ASSERT(deriv_param<2);
528         
529         if (deriv_param==0) {
530                 // d/dn zeta(n,x)
531                 throw(std::logic_error("cannot diff zetaderiv(n,x) with respect to n"));
532         }
533         // d/dx psi(n,x)
534         return zetaderiv(n+1,x);
535 }
536
537 REGISTER_FUNCTION(zetaderiv, eval_func(zetaderiv_eval).
538                                  derivative_func(zetaderiv_deriv).
539                                  latex_name("\\zeta^\\prime"));
540
541 //////////
542 // factorial
543 //////////
544
545 static ex factorial_evalf(const ex & x)
546 {
547         return factorial(x).hold();
548 }
549
550 static ex factorial_eval(const ex & x)
551 {
552         if (is_exactly_a<numeric>(x))
553                 return factorial(ex_to<numeric>(x));
554         else
555                 return factorial(x).hold();
556 }
557
558 static void factorial_print_dflt_latex(const ex & x, const print_context & c)
559 {
560         if (is_exactly_a<symbol>(x) ||
561             is_exactly_a<constant>(x) ||
562                 is_exactly_a<function>(x)) {
563                 x.print(c); c.s << "!";
564         } else {
565                 c.s << "("; x.print(c); c.s << ")!";
566         }
567 }
568
569 static ex factorial_conjugate(const ex & x)
570 {
571         return factorial(x);
572 }
573
574 REGISTER_FUNCTION(factorial, eval_func(factorial_eval).
575                              evalf_func(factorial_evalf).
576                              print_func<print_dflt>(factorial_print_dflt_latex).
577                              print_func<print_latex>(factorial_print_dflt_latex).
578                              conjugate_func(factorial_conjugate));
579
580 //////////
581 // binomial
582 //////////
583
584 static ex binomial_evalf(const ex & x, const ex & y)
585 {
586         return binomial(x, y).hold();
587 }
588
589 static ex binomial_sym(const ex & x, const numeric & y)
590 {
591         if (y.is_integer()) {
592                 if (y.is_nonneg_integer()) {
593                         const unsigned N = y.to_int();
594                         if (N == 0) return _ex0;
595                         if (N == 1) return x;
596                         ex t = x.expand();
597                         for (unsigned i = 2; i <= N; ++i)
598                                 t = (t * (x + i - y - 1)).expand() / i;
599                         return t;
600                 } else
601                         return _ex0;
602         }
603
604         return binomial(x, y).hold();
605 }
606
607 static ex binomial_eval(const ex & x, const ex &y)
608 {
609         if (is_exactly_a<numeric>(y)) {
610                 if (is_exactly_a<numeric>(x) && ex_to<numeric>(x).is_integer())
611                         return binomial(ex_to<numeric>(x), ex_to<numeric>(y));
612                 else
613                         return binomial_sym(x, ex_to<numeric>(y));
614         } else
615                 return binomial(x, y).hold();
616 }
617
618 // At the moment the numeric evaluation of a binomail function always
619 // gives a real number, but if this would be implemented using the gamma
620 // function, also complex conjugation should be changed (or rather, deleted).
621 static ex binomial_conjugate(const ex & x, const ex & y)
622 {
623         return binomial(x,y);
624 }
625
626 REGISTER_FUNCTION(binomial, eval_func(binomial_eval).
627                             evalf_func(binomial_evalf).
628                             conjugate_func(binomial_conjugate));
629
630 //////////
631 // Order term function (for truncated power series)
632 //////////
633
634 static ex Order_eval(const ex & x)
635 {
636         if (is_exactly_a<numeric>(x)) {
637                 // O(c) -> O(1) or 0
638                 if (!x.is_zero())
639                         return Order(_ex1).hold();
640                 else
641                         return _ex0;
642         } else if (is_exactly_a<mul>(x)) {
643                 const mul &m = ex_to<mul>(x);
644                 // O(c*expr) -> O(expr)
645                 if (is_exactly_a<numeric>(m.op(m.nops() - 1)))
646                         return Order(x / m.op(m.nops() - 1)).hold();
647         }
648         return Order(x).hold();
649 }
650
651 static ex Order_series(const ex & x, const relational & r, int order, unsigned options)
652 {
653         // Just wrap the function into a pseries object
654         epvector new_seq;
655         GINAC_ASSERT(is_a<symbol>(r.lhs()));
656         const symbol &s = ex_to<symbol>(r.lhs());
657         new_seq.push_back(expair(Order(_ex1), numeric(std::min(x.ldegree(s), order))));
658         return pseries(r, new_seq);
659 }
660
661 static ex Order_conjugate(const ex & x)
662 {
663         return Order(x);
664 }
665
666 // Differentiation is handled in function::derivative because of its special requirements
667
668 REGISTER_FUNCTION(Order, eval_func(Order_eval).
669                          series_func(Order_series).
670                          latex_name("\\mathcal{O}").
671                          conjugate_func(Order_conjugate));
672
673 //////////
674 // Solve linear system
675 //////////
676
677 ex lsolve(const ex &eqns, const ex &symbols, unsigned options)
678 {
679         // solve a system of linear equations
680         if (eqns.info(info_flags::relation_equal)) {
681                 if (!symbols.info(info_flags::symbol))
682                         throw(std::invalid_argument("lsolve(): 2nd argument must be a symbol"));
683                 const ex sol = lsolve(lst(eqns),lst(symbols));
684                 
685                 GINAC_ASSERT(sol.nops()==1);
686                 GINAC_ASSERT(is_exactly_a<relational>(sol.op(0)));
687                 
688                 return sol.op(0).op(1); // return rhs of first solution
689         }
690         
691         // syntax checks
692         if (!eqns.info(info_flags::list)) {
693                 throw(std::invalid_argument("lsolve(): 1st argument must be a list"));
694         }
695         for (size_t i=0; i<eqns.nops(); i++) {
696                 if (!eqns.op(i).info(info_flags::relation_equal)) {
697                         throw(std::invalid_argument("lsolve(): 1st argument must be a list of equations"));
698                 }
699         }
700         if (!symbols.info(info_flags::list)) {
701                 throw(std::invalid_argument("lsolve(): 2nd argument must be a list"));
702         }
703         for (size_t i=0; i<symbols.nops(); i++) {
704                 if (!symbols.op(i).info(info_flags::symbol)) {
705                         throw(std::invalid_argument("lsolve(): 2nd argument must be a list of symbols"));
706                 }
707         }
708         
709         // build matrix from equation system
710         matrix sys(eqns.nops(),symbols.nops());
711         matrix rhs(eqns.nops(),1);
712         matrix vars(symbols.nops(),1);
713         
714         for (size_t r=0; r<eqns.nops(); r++) {
715                 const ex eq = eqns.op(r).op(0)-eqns.op(r).op(1); // lhs-rhs==0
716                 ex linpart = eq;
717                 for (size_t c=0; c<symbols.nops(); c++) {
718                         const ex co = eq.coeff(ex_to<symbol>(symbols.op(c)),1);
719                         linpart -= co*symbols.op(c);
720                         sys(r,c) = co;
721                 }
722                 linpart = linpart.expand();
723                 rhs(r,0) = -linpart;
724         }
725         
726         // test if system is linear and fill vars matrix
727         for (size_t i=0; i<symbols.nops(); i++) {
728                 vars(i,0) = symbols.op(i);
729                 if (sys.has(symbols.op(i)))
730                         throw(std::logic_error("lsolve: system is not linear"));
731                 if (rhs.has(symbols.op(i)))
732                         throw(std::logic_error("lsolve: system is not linear"));
733         }
734         
735         matrix solution;
736         try {
737                 solution = sys.solve(vars,rhs,options);
738         } catch (const std::runtime_error & e) {
739                 // Probably singular matrix or otherwise overdetermined system:
740                 // It is consistent to return an empty list
741                 return lst();
742         }
743         GINAC_ASSERT(solution.cols()==1);
744         GINAC_ASSERT(solution.rows()==symbols.nops());
745         
746         // return list of equations of the form lst(var1==sol1,var2==sol2,...)
747         lst sollist;
748         for (size_t i=0; i<symbols.nops(); i++)
749                 sollist.append(symbols.op(i)==solution(i,0));
750         
751         return sollist;
752 }
753
754 //////////
755 // Find real root of f(x) numerically
756 //////////
757
758 const numeric
759 fsolve(const ex& f_in, const symbol& x, const numeric& x1, const numeric& x2)
760 {
761         if (!x1.is_real() || !x2.is_real()) {
762                 throw std::runtime_error("fsolve(): interval not bounded by real numbers");
763         }
764         if (x1==x2) {
765                 throw std::runtime_error("fsolve(): vanishing interval");
766         }
767         // xx[0] == left interval limit, xx[1] == right interval limit.
768         // fx[0] == f(xx[0]), fx[1] == f(xx[1]).
769         // We keep the root bracketed: xx[0]<xx[1] and fx[0]*fx[1]<0.
770         numeric xx[2] = { x1<x2 ? x1 : x2,
771                           x1<x2 ? x2 : x1 };
772         ex f;
773         if (is_a<relational>(f_in)) {
774                 f = f_in.lhs()-f_in.rhs();
775         } else {
776                 f = f_in;
777         }
778         const ex fx_[2] = { f.subs(x==xx[0]).evalf(),
779                             f.subs(x==xx[1]).evalf() };
780         if (!is_a<numeric>(fx_[0]) || !is_a<numeric>(fx_[1])) {
781                 throw std::runtime_error("fsolve(): function does not evaluate numerically");
782         }
783         numeric fx[2] = { ex_to<numeric>(fx_[0]),
784                           ex_to<numeric>(fx_[1]) };
785         if (!fx[0].is_real() || !fx[1].is_real()) {
786                 throw std::runtime_error("fsolve(): function evaluates to complex values at interval boundaries");
787         }
788         if (fx[0]*fx[1]>=0) {
789                 throw std::runtime_error("fsolve(): function does not change sign at interval boundaries");
790         }
791
792         // The Newton-Raphson method has quadratic convergence!  Simply put, it
793         // replaces x with x-f(x)/f'(x) at each step.  -f/f' is the delta:
794         const ex ff = normal(-f/f.diff(x));
795         int side = 0;  // Start at left interval limit.
796         numeric xxprev;
797         numeric fxprev;
798         do {
799                 xxprev = xx[side];
800                 fxprev = fx[side];
801                 xx[side] += ex_to<numeric>(ff.subs(x==xx[side]).evalf());
802                 fx[side] = ex_to<numeric>(f.subs(x==xx[side]).evalf());
803                 if ((side==0 && xx[0]<xxprev) || (side==1 && xx[1]>xxprev) || xx[0]>xx[1]) {
804                         // Oops, Newton-Raphson method shot out of the interval.
805                         // Restore, and try again with the other side instead!
806                         xx[side] = xxprev;
807                         fx[side] = fxprev;
808                         side = !side;
809                         xxprev = xx[side];
810                         fxprev = fx[side];
811                         xx[side] += ex_to<numeric>(ff.subs(x==xx[side]).evalf());
812                         fx[side] = ex_to<numeric>(f.subs(x==xx[side]).evalf());
813                 }
814                 if ((fx[side]<0 && fx[!side]<0) || (fx[side]>0 && fx[!side]>0)) {
815                         // Oops, the root isn't bracketed any more.
816                         // Restore, and perform a bisection!
817                         xx[side] = xxprev;
818                         fx[side] = fxprev;
819
820                         // Ah, the bisection! Bisections converge linearly. Unfortunately,
821                         // they occur pretty often when Newton-Raphson arrives at an x too
822                         // close to the result on one side of the interval and
823                         // f(x-f(x)/f'(x)) turns out to have the same sign as f(x) due to
824                         // precision errors! Recall that this function does not have a
825                         // precision goal as one of its arguments but instead relies on
826                         // x converging to a fixed point. We speed up the (safe but slow)
827                         // bisection method by mixing in a dash of the (unsafer but faster)
828                         // secant method: Instead of splitting the interval at the
829                         // arithmetic mean (bisection), we split it nearer to the root as
830                         // determined by the secant between the values xx[0] and xx[1].
831                         // Don't set the secant_weight to one because that could disturb
832                         // the convergence in some corner cases!
833                         static const double secant_weight = 0.984375;  // == 63/64 < 1
834                         numeric xxmid = (1-secant_weight)*0.5*(xx[0]+xx[1])
835                             + secant_weight*(xx[0]+fx[0]*(xx[0]-xx[1])/(fx[1]-fx[0]));
836                         numeric fxmid = ex_to<numeric>(f.subs(x==xxmid).evalf());
837                         if (fxmid.is_zero()) {
838                                 // Luck strikes...
839                                 return xxmid;
840                         }
841                         if ((fxmid<0 && fx[side]>0) || (fxmid>0 && fx[side]<0)) {
842                                 side = !side;
843                         }
844                         xxprev = xx[side];
845                         fxprev = fx[side];
846                         xx[side] = xxmid;
847                         fx[side] = fxmid;
848                 }
849         } while (xxprev!=xx[side]);
850         return xxprev;
851 }
852
853
854 /* Force inclusion of functions from inifcns_gamma and inifcns_zeta
855  * for static lib (so ginsh will see them). */
856 unsigned force_include_tgamma = tgamma_SERIAL::serial;
857 unsigned force_include_zeta1 = zeta1_SERIAL::serial;
858
859 } // namespace GiNaC