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