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