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