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