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