]> www.ginac.de Git - ginac.git/blob - ginac/inifcns.cpp
1144ce1997e14eed7911a6b6004a18fcc008b1a4
[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-2011 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 "inifcns.h"
24 #include "ex.h"
25 #include "constant.h"
26 #include "lst.h"
27 #include "matrix.h"
28 #include "mul.h"
29 #include "power.h"
30 #include "operators.h"
31 #include "relational.h"
32 #include "pseries.h"
33 #include "symbol.h"
34 #include "symmetry.h"
35 #include "utils.h"
36
37 #include <stdexcept>
38 #include <vector>
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 static ex conjugate_real_part(const ex & arg)
70 {
71         return arg.real_part();
72 }
73
74 static ex conjugate_imag_part(const ex & arg)
75 {
76         return -arg.imag_part();
77 }
78
79 static bool func_arg_info(const ex & arg, unsigned inf)
80 {
81         // for some functions we can return the info() of its argument
82         // (think of conjugate())
83         switch (inf) {
84                 case info_flags::polynomial:
85                 case info_flags::integer_polynomial:
86                 case info_flags::cinteger_polynomial:
87                 case info_flags::rational_polynomial:
88                 case info_flags::real:
89                 case info_flags::rational:
90                 case info_flags::integer:
91                 case info_flags::crational:
92                 case info_flags::cinteger:
93                 case info_flags::even:
94                 case info_flags::odd:
95                 case info_flags::prime:
96                 case info_flags::crational_polynomial:
97                 case info_flags::rational_function:
98                 case info_flags::algebraic:
99                 case info_flags::positive:
100                 case info_flags::negative:
101                 case info_flags::nonnegative:
102                 case info_flags::posint:
103                 case info_flags::negint:
104                 case info_flags::nonnegint:
105                 case info_flags::has_indices:
106                         return arg.info(inf);
107         }
108         return false;
109 }
110
111 static bool conjugate_info(const ex & arg, unsigned inf)
112 {
113         return func_arg_info(arg, inf);
114 }
115
116 REGISTER_FUNCTION(conjugate_function, eval_func(conjugate_eval).
117                                       evalf_func(conjugate_evalf).
118                                       info_func(conjugate_info).
119                                       print_func<print_latex>(conjugate_print_latex).
120                                       conjugate_func(conjugate_conjugate).
121                                       real_part_func(conjugate_real_part).
122                                       imag_part_func(conjugate_imag_part).
123                                       set_name("conjugate","conjugate"));
124
125 //////////
126 // real part
127 //////////
128
129 static ex real_part_evalf(const ex & arg)
130 {
131         if (is_exactly_a<numeric>(arg)) {
132                 return ex_to<numeric>(arg).real();
133         }
134         return real_part_function(arg).hold();
135 }
136
137 static ex real_part_eval(const ex & arg)
138 {
139         return arg.real_part();
140 }
141
142 static void real_part_print_latex(const ex & arg, const print_context & c)
143 {
144         c.s << "\\Re"; arg.print(c); c.s << "";
145 }
146
147 static ex real_part_conjugate(const ex & arg)
148 {
149         return real_part_function(arg).hold();
150 }
151
152 static ex real_part_real_part(const ex & arg)
153 {
154         return real_part_function(arg).hold();
155 }
156
157 static ex real_part_imag_part(const ex & arg)
158 {
159         return 0;
160 }
161
162 REGISTER_FUNCTION(real_part_function, eval_func(real_part_eval).
163                                       evalf_func(real_part_evalf).
164                                       print_func<print_latex>(real_part_print_latex).
165                                       conjugate_func(real_part_conjugate).
166                                       real_part_func(real_part_real_part).
167                                       imag_part_func(real_part_imag_part).
168                                       set_name("real_part","real_part"));
169
170 //////////
171 // imag part
172 //////////
173
174 static ex imag_part_evalf(const ex & arg)
175 {
176         if (is_exactly_a<numeric>(arg)) {
177                 return ex_to<numeric>(arg).imag();
178         }
179         return imag_part_function(arg).hold();
180 }
181
182 static ex imag_part_eval(const ex & arg)
183 {
184         return arg.imag_part();
185 }
186
187 static void imag_part_print_latex(const ex & arg, const print_context & c)
188 {
189         c.s << "\\Im"; arg.print(c); c.s << "";
190 }
191
192 static ex imag_part_conjugate(const ex & arg)
193 {
194         return imag_part_function(arg).hold();
195 }
196
197 static ex imag_part_real_part(const ex & arg)
198 {
199         return imag_part_function(arg).hold();
200 }
201
202 static ex imag_part_imag_part(const ex & arg)
203 {
204         return 0;
205 }
206
207 REGISTER_FUNCTION(imag_part_function, eval_func(imag_part_eval).
208                                       evalf_func(imag_part_evalf).
209                                       print_func<print_latex>(imag_part_print_latex).
210                                       conjugate_func(imag_part_conjugate).
211                                       real_part_func(imag_part_real_part).
212                                       imag_part_func(imag_part_imag_part).
213                                       set_name("imag_part","imag_part"));
214
215 //////////
216 // absolute value
217 //////////
218
219 static ex abs_evalf(const ex & arg)
220 {
221         if (is_exactly_a<numeric>(arg))
222                 return abs(ex_to<numeric>(arg));
223         
224         return abs(arg).hold();
225 }
226
227 static ex abs_eval(const ex & arg)
228 {
229         if (is_exactly_a<numeric>(arg))
230                 return abs(ex_to<numeric>(arg));
231
232         if (arg.info(info_flags::nonnegative))
233                 return arg;
234
235         if (is_ex_the_function(arg, abs))
236                 return arg;
237
238         if (is_ex_the_function(arg, exp))
239                 return exp(arg.op(0).real_part());
240
241         if (is_exactly_a<power>(arg)) {
242                 const ex& base = arg.op(0);
243                 const ex& exponent = arg.op(1);
244                 if (base.info(info_flags::positive) || exponent.info(info_flags::real))
245                         return pow(abs(base), exponent.real_part());
246         }
247
248         if (is_ex_the_function(arg, conjugate_function))
249                 return abs(arg.op(0));
250
251         if (is_ex_the_function(arg, step))
252                 return arg;
253
254         return abs(arg).hold();
255 }
256
257 static void abs_print_latex(const ex & arg, const print_context & c)
258 {
259         c.s << "{|"; arg.print(c); c.s << "|}";
260 }
261
262 static void abs_print_csrc_float(const ex & arg, const print_context & c)
263 {
264         c.s << "fabs("; arg.print(c); c.s << ")";
265 }
266
267 static ex abs_conjugate(const ex & arg)
268 {
269         return abs(arg).hold();
270 }
271
272 static ex abs_real_part(const ex & arg)
273 {
274         return abs(arg).hold();
275 }
276
277 static ex abs_imag_part(const ex& arg)
278 {
279         return 0;
280 }
281
282 static ex abs_power(const ex & arg, const ex & exp)
283 {
284         if (arg.is_equal(arg.conjugate()) && ((is_a<numeric>(exp) && ex_to<numeric>(exp).is_even())
285                                                 || exp.info(info_flags::even)))
286                 return power(arg, exp);
287         else
288                 return power(abs(arg), exp).hold();
289 }
290
291 bool abs_info(const ex & arg, unsigned inf)
292 {
293         switch (inf) {
294                 case info_flags::integer:
295                 case info_flags::even:
296                 case info_flags::odd:
297                 case info_flags::prime:
298                         return arg.info(inf);
299                 case info_flags::nonnegint:
300                         return arg.info(info_flags::integer);
301                 case info_flags::nonnegative:
302                 case info_flags::real:
303                         return true;
304                 case info_flags::negative:
305                         return false;
306                 case info_flags::positive:
307                         return arg.info(info_flags::positive) || arg.info(info_flags::negative);
308                 case info_flags::has_indices: {
309                         if (arg.info(info_flags::has_indices))
310                                 return true;
311                         else
312                                 return false;
313                 }
314         }
315         return false;
316 }
317
318 REGISTER_FUNCTION(abs, eval_func(abs_eval).
319                        evalf_func(abs_evalf).
320                        info_func(abs_info).
321                        print_func<print_latex>(abs_print_latex).
322                        print_func<print_csrc_float>(abs_print_csrc_float).
323                        print_func<print_csrc_double>(abs_print_csrc_float).
324                        conjugate_func(abs_conjugate).
325                        real_part_func(abs_real_part).
326                        imag_part_func(abs_imag_part).
327                        power_func(abs_power));
328
329 //////////
330 // Step function
331 //////////
332
333 static ex step_evalf(const ex & arg)
334 {
335         if (is_exactly_a<numeric>(arg))
336                 return step(ex_to<numeric>(arg));
337         
338         return step(arg).hold();
339 }
340
341 static ex step_eval(const ex & arg)
342 {
343         if (is_exactly_a<numeric>(arg))
344                 return step(ex_to<numeric>(arg));
345         
346         else if (is_exactly_a<mul>(arg) &&
347                  is_exactly_a<numeric>(arg.op(arg.nops()-1))) {
348                 numeric oc = ex_to<numeric>(arg.op(arg.nops()-1));
349                 if (oc.is_real()) {
350                         if (oc > 0)
351                                 // step(42*x) -> step(x)
352                                 return step(arg/oc).hold();
353                         else
354                                 // step(-42*x) -> step(-x)
355                                 return step(-arg/oc).hold();
356                 }
357                 if (oc.real().is_zero()) {
358                         if (oc.imag() > 0)
359                                 // step(42*I*x) -> step(I*x)
360                                 return step(I*arg/oc).hold();
361                         else
362                                 // step(-42*I*x) -> step(-I*x)
363                                 return step(-I*arg/oc).hold();
364                 }
365         }
366         
367         return step(arg).hold();
368 }
369
370 static ex step_series(const ex & arg,
371                       const relational & rel,
372                       int order,
373                       unsigned options)
374 {
375         const ex arg_pt = arg.subs(rel, subs_options::no_pattern);
376         if (arg_pt.info(info_flags::numeric)
377             && ex_to<numeric>(arg_pt).real().is_zero()
378             && !(options & series_options::suppress_branchcut))
379                 throw (std::domain_error("step_series(): on imaginary axis"));
380         
381         epvector seq;
382         seq.push_back(expair(step(arg_pt), _ex0));
383         return pseries(rel,seq);
384 }
385
386 static ex step_conjugate(const ex& arg)
387 {
388         return step(arg).hold();
389 }
390
391 static ex step_real_part(const ex& arg)
392 {
393         return step(arg).hold();
394 }
395
396 static ex step_imag_part(const ex& arg)
397 {
398         return 0;
399 }
400
401 REGISTER_FUNCTION(step, eval_func(step_eval).
402                         evalf_func(step_evalf).
403                         series_func(step_series).
404                         conjugate_func(step_conjugate).
405                         real_part_func(step_real_part).
406                         imag_part_func(step_imag_part));
407
408 //////////
409 // Complex sign
410 //////////
411
412 static ex csgn_evalf(const ex & arg)
413 {
414         if (is_exactly_a<numeric>(arg))
415                 return csgn(ex_to<numeric>(arg));
416         
417         return csgn(arg).hold();
418 }
419
420 static ex csgn_eval(const ex & arg)
421 {
422         if (is_exactly_a<numeric>(arg))
423                 return csgn(ex_to<numeric>(arg));
424         
425         else if (is_exactly_a<mul>(arg) &&
426                  is_exactly_a<numeric>(arg.op(arg.nops()-1))) {
427                 numeric oc = ex_to<numeric>(arg.op(arg.nops()-1));
428                 if (oc.is_real()) {
429                         if (oc > 0)
430                                 // csgn(42*x) -> csgn(x)
431                                 return csgn(arg/oc).hold();
432                         else
433                                 // csgn(-42*x) -> -csgn(x)
434                                 return -csgn(arg/oc).hold();
435                 }
436                 if (oc.real().is_zero()) {
437                         if (oc.imag() > 0)
438                                 // csgn(42*I*x) -> csgn(I*x)
439                                 return csgn(I*arg/oc).hold();
440                         else
441                                 // csgn(-42*I*x) -> -csgn(I*x)
442                                 return -csgn(I*arg/oc).hold();
443                 }
444         }
445         
446         return csgn(arg).hold();
447 }
448
449 static ex csgn_series(const ex & arg,
450                       const relational & rel,
451                       int order,
452                       unsigned options)
453 {
454         const ex arg_pt = arg.subs(rel, subs_options::no_pattern);
455         if (arg_pt.info(info_flags::numeric)
456             && ex_to<numeric>(arg_pt).real().is_zero()
457             && !(options & series_options::suppress_branchcut))
458                 throw (std::domain_error("csgn_series(): on imaginary axis"));
459         
460         epvector seq;
461         seq.push_back(expair(csgn(arg_pt), _ex0));
462         return pseries(rel,seq);
463 }
464
465 static ex csgn_conjugate(const ex& arg)
466 {
467         return csgn(arg).hold();
468 }
469
470 static ex csgn_real_part(const ex& arg)
471 {
472         return csgn(arg).hold();
473 }
474
475 static ex csgn_imag_part(const ex& arg)
476 {
477         return 0;
478 }
479
480 static ex csgn_power(const ex & arg, const ex & exp)
481 {
482         if (is_a<numeric>(exp) && exp.info(info_flags::positive) && ex_to<numeric>(exp).is_integer()) {
483                 if (ex_to<numeric>(exp).is_odd())
484                         return csgn(arg).hold();
485                 else
486                         return power(csgn(arg), _ex2).hold();
487         } else
488                 return power(csgn(arg), exp).hold();
489 }
490
491
492 REGISTER_FUNCTION(csgn, eval_func(csgn_eval).
493                         evalf_func(csgn_evalf).
494                         series_func(csgn_series).
495                         conjugate_func(csgn_conjugate).
496                         real_part_func(csgn_real_part).
497                         imag_part_func(csgn_imag_part).
498                         power_func(csgn_power));
499
500
501 //////////
502 // Eta function: eta(x,y) == log(x*y) - log(x) - log(y).
503 // This function is closely related to the unwinding number K, sometimes found
504 // in modern literature: K(z) == (z-log(exp(z)))/(2*Pi*I).
505 //////////
506
507 static ex eta_evalf(const ex &x, const ex &y)
508 {
509         // It seems like we basically have to replicate the eval function here,
510         // since the expression might not be fully evaluated yet.
511         if (x.info(info_flags::positive) || y.info(info_flags::positive))
512                 return _ex0;
513
514         if (x.info(info_flags::numeric) &&      y.info(info_flags::numeric)) {
515                 const numeric nx = ex_to<numeric>(x);
516                 const numeric ny = ex_to<numeric>(y);
517                 const numeric nxy = ex_to<numeric>(x*y);
518                 int cut = 0;
519                 if (nx.is_real() && nx.is_negative())
520                         cut -= 4;
521                 if (ny.is_real() && ny.is_negative())
522                         cut -= 4;
523                 if (nxy.is_real() && nxy.is_negative())
524                         cut += 4;
525                 return evalf(I/4*Pi)*((csgn(-imag(nx))+1)*(csgn(-imag(ny))+1)*(csgn(imag(nxy))+1)-
526                                       (csgn(imag(nx))+1)*(csgn(imag(ny))+1)*(csgn(-imag(nxy))+1)+cut);
527         }
528
529         return eta(x,y).hold();
530 }
531
532 static ex eta_eval(const ex &x, const ex &y)
533 {
534         // trivial:  eta(x,c) -> 0  if c is real and positive
535         if (x.info(info_flags::positive) || y.info(info_flags::positive))
536                 return _ex0;
537
538         if (x.info(info_flags::numeric) &&      y.info(info_flags::numeric)) {
539                 // don't call eta_evalf here because it would call Pi.evalf()!
540                 const numeric nx = ex_to<numeric>(x);
541                 const numeric ny = ex_to<numeric>(y);
542                 const numeric nxy = ex_to<numeric>(x*y);
543                 int cut = 0;
544                 if (nx.is_real() && nx.is_negative())
545                         cut -= 4;
546                 if (ny.is_real() && ny.is_negative())
547                         cut -= 4;
548                 if (nxy.is_real() && nxy.is_negative())
549                         cut += 4;
550                 return (I/4)*Pi*((csgn(-imag(nx))+1)*(csgn(-imag(ny))+1)*(csgn(imag(nxy))+1)-
551                                  (csgn(imag(nx))+1)*(csgn(imag(ny))+1)*(csgn(-imag(nxy))+1)+cut);
552         }
553         
554         return eta(x,y).hold();
555 }
556
557 static ex eta_series(const ex & x, const ex & y,
558                      const relational & rel,
559                      int order,
560                      unsigned options)
561 {
562         const ex x_pt = x.subs(rel, subs_options::no_pattern);
563         const ex y_pt = y.subs(rel, subs_options::no_pattern);
564         if ((x_pt.info(info_flags::numeric) && x_pt.info(info_flags::negative)) ||
565             (y_pt.info(info_flags::numeric) && y_pt.info(info_flags::negative)) ||
566             ((x_pt*y_pt).info(info_flags::numeric) && (x_pt*y_pt).info(info_flags::negative)))
567                         throw (std::domain_error("eta_series(): on discontinuity"));
568         epvector seq;
569         seq.push_back(expair(eta(x_pt,y_pt), _ex0));
570         return pseries(rel,seq);
571 }
572
573 static ex eta_conjugate(const ex & x, const ex & y)
574 {
575         return -eta(x, y).hold();
576 }
577
578 static ex eta_real_part(const ex & x, const ex & y)
579 {
580         return 0;
581 }
582
583 static ex eta_imag_part(const ex & x, const ex & y)
584 {
585         return -I*eta(x, y).hold();
586 }
587
588 REGISTER_FUNCTION(eta, eval_func(eta_eval).
589                        evalf_func(eta_evalf).
590                        series_func(eta_series).
591                        latex_name("\\eta").
592                        set_symmetry(sy_symm(0, 1)).
593                        conjugate_func(eta_conjugate).
594                        real_part_func(eta_real_part).
595                        imag_part_func(eta_imag_part));
596
597
598 //////////
599 // dilogarithm
600 //////////
601
602 static ex Li2_evalf(const ex & x)
603 {
604         if (is_exactly_a<numeric>(x))
605                 return Li2(ex_to<numeric>(x));
606         
607         return Li2(x).hold();
608 }
609
610 static ex Li2_eval(const ex & x)
611 {
612         if (x.info(info_flags::numeric)) {
613                 // Li2(0) -> 0
614                 if (x.is_zero())
615                         return _ex0;
616                 // Li2(1) -> Pi^2/6
617                 if (x.is_equal(_ex1))
618                         return power(Pi,_ex2)/_ex6;
619                 // Li2(1/2) -> Pi^2/12 - log(2)^2/2
620                 if (x.is_equal(_ex1_2))
621                         return power(Pi,_ex2)/_ex12 + power(log(_ex2),_ex2)*_ex_1_2;
622                 // Li2(-1) -> -Pi^2/12
623                 if (x.is_equal(_ex_1))
624                         return -power(Pi,_ex2)/_ex12;
625                 // Li2(I) -> -Pi^2/48+Catalan*I
626                 if (x.is_equal(I))
627                         return power(Pi,_ex2)/_ex_48 + Catalan*I;
628                 // Li2(-I) -> -Pi^2/48-Catalan*I
629                 if (x.is_equal(-I))
630                         return power(Pi,_ex2)/_ex_48 - Catalan*I;
631                 // Li2(float)
632                 if (!x.info(info_flags::crational))
633                         return Li2(ex_to<numeric>(x));
634         }
635         
636         return Li2(x).hold();
637 }
638
639 static ex Li2_deriv(const ex & x, unsigned deriv_param)
640 {
641         GINAC_ASSERT(deriv_param==0);
642         
643         // d/dx Li2(x) -> -log(1-x)/x
644         return -log(_ex1-x)/x;
645 }
646
647 static ex Li2_series(const ex &x, const relational &rel, int order, unsigned options)
648 {
649         const ex x_pt = x.subs(rel, subs_options::no_pattern);
650         if (x_pt.info(info_flags::numeric)) {
651                 // First special case: x==0 (derivatives have poles)
652                 if (x_pt.is_zero()) {
653                         // method:
654                         // The problem is that in d/dx Li2(x==0) == -log(1-x)/x we cannot 
655                         // simply substitute x==0.  The limit, however, exists: it is 1.
656                         // We also know all higher derivatives' limits:
657                         // (d/dx)^n Li2(x) == n!/n^2.
658                         // So the primitive series expansion is
659                         // Li2(x==0) == x + x^2/4 + x^3/9 + ...
660                         // and so on.
661                         // We first construct such a primitive series expansion manually in
662                         // a dummy symbol s and then insert the argument's series expansion
663                         // for s.  Reexpanding the resulting series returns the desired
664                         // result.
665                         const symbol s;
666                         ex ser;
667                         // manually construct the primitive expansion
668                         for (int i=1; i<order; ++i)
669                                 ser += pow(s,i) / pow(numeric(i), *_num2_p);
670                         // substitute the argument's series expansion
671                         ser = ser.subs(s==x.series(rel, order), subs_options::no_pattern);
672                         // maybe that was terminating, so add a proper order term
673                         epvector nseq;
674                         nseq.push_back(expair(Order(_ex1), order));
675                         ser += pseries(rel, nseq);
676                         // reexpanding it will collapse the series again
677                         return ser.series(rel, order);
678                         // NB: Of course, this still does not allow us to compute anything
679                         // like sin(Li2(x)).series(x==0,2), since then this code here is
680                         // not reached and the derivative of sin(Li2(x)) doesn't allow the
681                         // substitution x==0.  Probably limits *are* needed for the general
682                         // cases.  In case L'Hospital's rule is implemented for limits and
683                         // basic::series() takes care of this, this whole block is probably
684                         // obsolete!
685                 }
686                 // second special case: x==1 (branch point)
687                 if (x_pt.is_equal(_ex1)) {
688                         // method:
689                         // construct series manually in a dummy symbol s
690                         const symbol s;
691                         ex ser = zeta(_ex2);
692                         // manually construct the primitive expansion
693                         for (int i=1; i<order; ++i)
694                                 ser += pow(1-s,i) * (numeric(1,i)*(I*Pi+log(s-1)) - numeric(1,i*i));
695                         // substitute the argument's series expansion
696                         ser = ser.subs(s==x.series(rel, order), subs_options::no_pattern);
697                         // maybe that was terminating, so add a proper order term
698                         epvector nseq;
699                         nseq.push_back(expair(Order(_ex1), order));
700                         ser += pseries(rel, nseq);
701                         // reexpanding it will collapse the series again
702                         return ser.series(rel, order);
703                 }
704                 // third special case: x real, >=1 (branch cut)
705                 if (!(options & series_options::suppress_branchcut) &&
706                         ex_to<numeric>(x_pt).is_real() && ex_to<numeric>(x_pt)>1) {
707                         // method:
708                         // This is the branch cut: assemble the primitive series manually
709                         // and then add the corresponding complex step function.
710                         const symbol &s = ex_to<symbol>(rel.lhs());
711                         const ex point = rel.rhs();
712                         const symbol foo;
713                         epvector seq;
714                         // zeroth order term:
715                         seq.push_back(expair(Li2(x_pt), _ex0));
716                         // compute the intermediate terms:
717                         ex replarg = series(Li2(x), s==foo, order);
718                         for (size_t i=1; i<replarg.nops()-1; ++i)
719                                 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));
720                         // append an order term:
721                         seq.push_back(expair(Order(_ex1), replarg.nops()-1));
722                         return pseries(rel, seq);
723                 }
724         }
725         // all other cases should be safe, by now:
726         throw do_taylor();  // caught by function::series()
727 }
728
729 static ex Li2_conjugate(const ex & x)
730 {
731         // conjugate(Li2(x))==Li2(conjugate(x)) unless on the branch cuts which
732         // run along the positive real axis beginning at 1.
733         if (x.info(info_flags::negative)) {
734                 return Li2(x).hold();
735         }
736         if (is_exactly_a<numeric>(x) &&
737             (!x.imag_part().is_zero() || x < *_num1_p)) {
738                 return Li2(x.conjugate());
739         }
740         return conjugate_function(Li2(x)).hold();
741 }
742
743 REGISTER_FUNCTION(Li2, eval_func(Li2_eval).
744                        evalf_func(Li2_evalf).
745                        derivative_func(Li2_deriv).
746                        series_func(Li2_series).
747                        conjugate_func(Li2_conjugate).
748                        latex_name("\\mathrm{Li}_2"));
749
750 //////////
751 // trilogarithm
752 //////////
753
754 static ex Li3_eval(const ex & x)
755 {
756         if (x.is_zero())
757                 return x;
758         return Li3(x).hold();
759 }
760
761 REGISTER_FUNCTION(Li3, eval_func(Li3_eval).
762                        latex_name("\\mathrm{Li}_3"));
763
764 //////////
765 // Derivatives of Riemann's Zeta-function  zetaderiv(0,x)==zeta(x)
766 //////////
767
768 static ex zetaderiv_eval(const ex & n, const ex & x)
769 {
770         if (n.info(info_flags::numeric)) {
771                 // zetaderiv(0,x) -> zeta(x)
772                 if (n.is_zero())
773                         return zeta(x).hold();
774         }
775         
776         return zetaderiv(n, x).hold();
777 }
778
779 static ex zetaderiv_deriv(const ex & n, const ex & x, unsigned deriv_param)
780 {
781         GINAC_ASSERT(deriv_param<2);
782         
783         if (deriv_param==0) {
784                 // d/dn zeta(n,x)
785                 throw(std::logic_error("cannot diff zetaderiv(n,x) with respect to n"));
786         }
787         // d/dx psi(n,x)
788         return zetaderiv(n+1,x);
789 }
790
791 REGISTER_FUNCTION(zetaderiv, eval_func(zetaderiv_eval).
792                                  derivative_func(zetaderiv_deriv).
793                                  latex_name("\\zeta^\\prime"));
794
795 //////////
796 // factorial
797 //////////
798
799 static ex factorial_evalf(const ex & x)
800 {
801         return factorial(x).hold();
802 }
803
804 static ex factorial_eval(const ex & x)
805 {
806         if (is_exactly_a<numeric>(x))
807                 return factorial(ex_to<numeric>(x));
808         else
809                 return factorial(x).hold();
810 }
811
812 static void factorial_print_dflt_latex(const ex & x, const print_context & c)
813 {
814         if (is_exactly_a<symbol>(x) ||
815             is_exactly_a<constant>(x) ||
816                 is_exactly_a<function>(x)) {
817                 x.print(c); c.s << "!";
818         } else {
819                 c.s << "("; x.print(c); c.s << ")!";
820         }
821 }
822
823 static ex factorial_conjugate(const ex & x)
824 {
825         return factorial(x).hold();
826 }
827
828 static ex factorial_real_part(const ex & x)
829 {
830         return factorial(x).hold();
831 }
832
833 static ex factorial_imag_part(const ex & x)
834 {
835         return 0;
836 }
837
838 REGISTER_FUNCTION(factorial, eval_func(factorial_eval).
839                              evalf_func(factorial_evalf).
840                              print_func<print_dflt>(factorial_print_dflt_latex).
841                              print_func<print_latex>(factorial_print_dflt_latex).
842                              conjugate_func(factorial_conjugate).
843                              real_part_func(factorial_real_part).
844                              imag_part_func(factorial_imag_part));
845
846 //////////
847 // binomial
848 //////////
849
850 static ex binomial_evalf(const ex & x, const ex & y)
851 {
852         return binomial(x, y).hold();
853 }
854
855 static ex binomial_sym(const ex & x, const numeric & y)
856 {
857         if (y.is_integer()) {
858                 if (y.is_nonneg_integer()) {
859                         const unsigned N = y.to_int();
860                         if (N == 0) return _ex1;
861                         if (N == 1) return x;
862                         ex t = x.expand();
863                         for (unsigned i = 2; i <= N; ++i)
864                                 t = (t * (x + i - y - 1)).expand() / i;
865                         return t;
866                 } else
867                         return _ex0;
868         }
869
870         return binomial(x, y).hold();
871 }
872
873 static ex binomial_eval(const ex & x, const ex &y)
874 {
875         if (is_exactly_a<numeric>(y)) {
876                 if (is_exactly_a<numeric>(x) && ex_to<numeric>(x).is_integer())
877                         return binomial(ex_to<numeric>(x), ex_to<numeric>(y));
878                 else
879                         return binomial_sym(x, ex_to<numeric>(y));
880         } else
881                 return binomial(x, y).hold();
882 }
883
884 // At the moment the numeric evaluation of a binomail function always
885 // gives a real number, but if this would be implemented using the gamma
886 // function, also complex conjugation should be changed (or rather, deleted).
887 static ex binomial_conjugate(const ex & x, const ex & y)
888 {
889         return binomial(x,y).hold();
890 }
891
892 static ex binomial_real_part(const ex & x, const ex & y)
893 {
894         return binomial(x,y).hold();
895 }
896
897 static ex binomial_imag_part(const ex & x, const ex & y)
898 {
899         return 0;
900 }
901
902 REGISTER_FUNCTION(binomial, eval_func(binomial_eval).
903                             evalf_func(binomial_evalf).
904                             conjugate_func(binomial_conjugate).
905                             real_part_func(binomial_real_part).
906                             imag_part_func(binomial_imag_part));
907
908 //////////
909 // Order term function (for truncated power series)
910 //////////
911
912 static ex Order_eval(const ex & x)
913 {
914         if (is_exactly_a<numeric>(x)) {
915                 // O(c) -> O(1) or 0
916                 if (!x.is_zero())
917                         return Order(_ex1).hold();
918                 else
919                         return _ex0;
920         } else if (is_exactly_a<mul>(x)) {
921                 const mul &m = ex_to<mul>(x);
922                 // O(c*expr) -> O(expr)
923                 if (is_exactly_a<numeric>(m.op(m.nops() - 1)))
924                         return Order(x / m.op(m.nops() - 1)).hold();
925         }
926         return Order(x).hold();
927 }
928
929 static ex Order_series(const ex & x, const relational & r, int order, unsigned options)
930 {
931         // Just wrap the function into a pseries object
932         epvector new_seq;
933         GINAC_ASSERT(is_a<symbol>(r.lhs()));
934         const symbol &s = ex_to<symbol>(r.lhs());
935         new_seq.push_back(expair(Order(_ex1), numeric(std::min(x.ldegree(s), order))));
936         return pseries(r, new_seq);
937 }
938
939 static ex Order_conjugate(const ex & x)
940 {
941         return Order(x).hold();
942 }
943
944 static ex Order_real_part(const ex & x)
945 {
946         return Order(x).hold();
947 }
948
949 static ex Order_imag_part(const ex & x)
950 {
951         if(x.info(info_flags::real))
952                 return 0;
953         return Order(x).hold();
954 }
955
956 // Differentiation is handled in function::derivative because of its special requirements
957
958 REGISTER_FUNCTION(Order, eval_func(Order_eval).
959                          series_func(Order_series).
960                          latex_name("\\mathcal{O}").
961                          conjugate_func(Order_conjugate).
962                          real_part_func(Order_real_part).
963                          imag_part_func(Order_imag_part));
964
965 //////////
966 // Solve linear system
967 //////////
968
969 ex lsolve(const ex &eqns, const ex &symbols, unsigned options)
970 {
971         // solve a system of linear equations
972         if (eqns.info(info_flags::relation_equal)) {
973                 if (!symbols.info(info_flags::symbol))
974                         throw(std::invalid_argument("lsolve(): 2nd argument must be a symbol"));
975                 const ex sol = lsolve(lst(eqns),lst(symbols));
976                 
977                 GINAC_ASSERT(sol.nops()==1);
978                 GINAC_ASSERT(is_exactly_a<relational>(sol.op(0)));
979                 
980                 return sol.op(0).op(1); // return rhs of first solution
981         }
982         
983         // syntax checks
984         if (!eqns.info(info_flags::list)) {
985                 throw(std::invalid_argument("lsolve(): 1st argument must be a list or an equation"));
986         }
987         for (size_t i=0; i<eqns.nops(); i++) {
988                 if (!eqns.op(i).info(info_flags::relation_equal)) {
989                         throw(std::invalid_argument("lsolve(): 1st argument must be a list of equations"));
990                 }
991         }
992         if (!symbols.info(info_flags::list)) {
993                 throw(std::invalid_argument("lsolve(): 2nd argument must be a list or a symbol"));
994         }
995         for (size_t i=0; i<symbols.nops(); i++) {
996                 if (!symbols.op(i).info(info_flags::symbol)) {
997                         throw(std::invalid_argument("lsolve(): 2nd argument must be a list of symbols"));
998                 }
999         }
1000         
1001         // build matrix from equation system
1002         matrix sys(eqns.nops(),symbols.nops());
1003         matrix rhs(eqns.nops(),1);
1004         matrix vars(symbols.nops(),1);
1005         
1006         for (size_t r=0; r<eqns.nops(); r++) {
1007                 const ex eq = eqns.op(r).op(0)-eqns.op(r).op(1); // lhs-rhs==0
1008                 ex linpart = eq;
1009                 for (size_t c=0; c<symbols.nops(); c++) {
1010                         const ex co = eq.coeff(ex_to<symbol>(symbols.op(c)),1);
1011                         linpart -= co*symbols.op(c);
1012                         sys(r,c) = co;
1013                 }
1014                 linpart = linpart.expand();
1015                 rhs(r,0) = -linpart;
1016         }
1017         
1018         // test if system is linear and fill vars matrix
1019         for (size_t i=0; i<symbols.nops(); i++) {
1020                 vars(i,0) = symbols.op(i);
1021                 if (sys.has(symbols.op(i)))
1022                         throw(std::logic_error("lsolve: system is not linear"));
1023                 if (rhs.has(symbols.op(i)))
1024                         throw(std::logic_error("lsolve: system is not linear"));
1025         }
1026         
1027         matrix solution;
1028         try {
1029                 solution = sys.solve(vars,rhs,options);
1030         } catch (const std::runtime_error & e) {
1031                 // Probably singular matrix or otherwise overdetermined system:
1032                 // It is consistent to return an empty list
1033                 return lst();
1034         }
1035         GINAC_ASSERT(solution.cols()==1);
1036         GINAC_ASSERT(solution.rows()==symbols.nops());
1037         
1038         // return list of equations of the form lst(var1==sol1,var2==sol2,...)
1039         lst sollist;
1040         for (size_t i=0; i<symbols.nops(); i++)
1041                 sollist.append(symbols.op(i)==solution(i,0));
1042         
1043         return sollist;
1044 }
1045
1046 //////////
1047 // Find real root of f(x) numerically
1048 //////////
1049
1050 const numeric
1051 fsolve(const ex& f_in, const symbol& x, const numeric& x1, const numeric& x2)
1052 {
1053         if (!x1.is_real() || !x2.is_real()) {
1054                 throw std::runtime_error("fsolve(): interval not bounded by real numbers");
1055         }
1056         if (x1==x2) {
1057                 throw std::runtime_error("fsolve(): vanishing interval");
1058         }
1059         // xx[0] == left interval limit, xx[1] == right interval limit.
1060         // fx[0] == f(xx[0]), fx[1] == f(xx[1]).
1061         // We keep the root bracketed: xx[0]<xx[1] and fx[0]*fx[1]<0.
1062         numeric xx[2] = { x1<x2 ? x1 : x2,
1063                           x1<x2 ? x2 : x1 };
1064         ex f;
1065         if (is_a<relational>(f_in)) {
1066                 f = f_in.lhs()-f_in.rhs();
1067         } else {
1068                 f = f_in;
1069         }
1070         const ex fx_[2] = { f.subs(x==xx[0]).evalf(),
1071                             f.subs(x==xx[1]).evalf() };
1072         if (!is_a<numeric>(fx_[0]) || !is_a<numeric>(fx_[1])) {
1073                 throw std::runtime_error("fsolve(): function does not evaluate numerically");
1074         }
1075         numeric fx[2] = { ex_to<numeric>(fx_[0]),
1076                           ex_to<numeric>(fx_[1]) };
1077         if (!fx[0].is_real() || !fx[1].is_real()) {
1078                 throw std::runtime_error("fsolve(): function evaluates to complex values at interval boundaries");
1079         }
1080         if (fx[0]*fx[1]>=0) {
1081                 throw std::runtime_error("fsolve(): function does not change sign at interval boundaries");
1082         }
1083
1084         // The Newton-Raphson method has quadratic convergence!  Simply put, it
1085         // replaces x with x-f(x)/f'(x) at each step.  -f/f' is the delta:
1086         const ex ff = normal(-f/f.diff(x));
1087         int side = 0;  // Start at left interval limit.
1088         numeric xxprev;
1089         numeric fxprev;
1090         do {
1091                 xxprev = xx[side];
1092                 fxprev = fx[side];
1093                 ex dx_ = ff.subs(x == xx[side]).evalf();
1094                 if (!is_a<numeric>(dx_))
1095                         throw std::runtime_error("fsolve(): function derivative does not evaluate numerically");
1096                 xx[side] += ex_to<numeric>(dx_);
1097                 // Now check if Newton-Raphson method shot out of the interval 
1098                 bool bad_shot = (side == 0 && xx[0] < xxprev) || 
1099                                 (side == 1 && xx[1] > xxprev) || xx[0] > xx[1];
1100                 if (!bad_shot) {
1101                         // Compute f(x) only if new x is inside the interval.
1102                         // The function might be difficult to compute numerically
1103                         // or even ill defined outside the interval. Also it's
1104                         // a small optimization. 
1105                         ex f_x = f.subs(x == xx[side]).evalf();
1106                         if (!is_a<numeric>(f_x))
1107                                 throw std::runtime_error("fsolve(): function does not evaluate numerically");
1108                         fx[side] = ex_to<numeric>(f_x);
1109                 }
1110                 if (bad_shot) {
1111                         // Oops, Newton-Raphson method shot out of the interval.
1112                         // Restore, and try again with the other side instead!
1113                         xx[side] = xxprev;
1114                         fx[side] = fxprev;
1115                         side = !side;
1116                         xxprev = xx[side];
1117                         fxprev = fx[side];
1118
1119                         ex dx_ = ff.subs(x == xx[side]).evalf();
1120                         if (!is_a<numeric>(dx_))
1121                                 throw std::runtime_error("fsolve(): function derivative does not evaluate numerically [2]");
1122                         xx[side] += ex_to<numeric>(dx_);
1123
1124                         ex f_x = f.subs(x==xx[side]).evalf();
1125                         if (!is_a<numeric>(f_x))
1126                                 throw std::runtime_error("fsolve(): function does not evaluate numerically [2]");
1127                         fx[side] = ex_to<numeric>(f_x);
1128                 }
1129                 if ((fx[side]<0 && fx[!side]<0) || (fx[side]>0 && fx[!side]>0)) {
1130                         // Oops, the root isn't bracketed any more.
1131                         // Restore, and perform a bisection!
1132                         xx[side] = xxprev;
1133                         fx[side] = fxprev;
1134
1135                         // Ah, the bisection! Bisections converge linearly. Unfortunately,
1136                         // they occur pretty often when Newton-Raphson arrives at an x too
1137                         // close to the result on one side of the interval and
1138                         // f(x-f(x)/f'(x)) turns out to have the same sign as f(x) due to
1139                         // precision errors! Recall that this function does not have a
1140                         // precision goal as one of its arguments but instead relies on
1141                         // x converging to a fixed point. We speed up the (safe but slow)
1142                         // bisection method by mixing in a dash of the (unsafer but faster)
1143                         // secant method: Instead of splitting the interval at the
1144                         // arithmetic mean (bisection), we split it nearer to the root as
1145                         // determined by the secant between the values xx[0] and xx[1].
1146                         // Don't set the secant_weight to one because that could disturb
1147                         // the convergence in some corner cases!
1148                         static const double secant_weight = 0.984375;  // == 63/64 < 1
1149                         numeric xxmid = (1-secant_weight)*0.5*(xx[0]+xx[1])
1150                             + secant_weight*(xx[0]+fx[0]*(xx[0]-xx[1])/(fx[1]-fx[0]));
1151                         ex fxmid_ = f.subs(x == xxmid).evalf();
1152                         if (!is_a<numeric>(fxmid_))
1153                                 throw std::runtime_error("fsolve(): function does not evaluate numerically [3]");
1154                         numeric fxmid = ex_to<numeric>(fxmid_);
1155                         if (fxmid.is_zero()) {
1156                                 // Luck strikes...
1157                                 return xxmid;
1158                         }
1159                         if ((fxmid<0 && fx[side]>0) || (fxmid>0 && fx[side]<0)) {
1160                                 side = !side;
1161                         }
1162                         xxprev = xx[side];
1163                         fxprev = fx[side];
1164                         xx[side] = xxmid;
1165                         fx[side] = fxmid;
1166                 }
1167         } while (xxprev!=xx[side]);
1168         return xxprev;
1169 }
1170
1171
1172 /* Force inclusion of functions from inifcns_gamma and inifcns_zeta
1173  * for static lib (so ginsh will see them). */
1174 unsigned force_include_tgamma = tgamma_SERIAL::serial;
1175 unsigned force_include_zeta1 = zeta1_SERIAL::serial;
1176
1177 } // namespace GiNaC