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