]> www.ginac.de Git - ginac.git/blob - ginac/inifcns.cpp
synced to 1.1
[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-2003 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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 // absolute value
44 //////////
45
46 static ex abs_evalf(const ex & arg)
47 {
48         if (is_exactly_a<numeric>(arg))
49                 return abs(ex_to<numeric>(arg));
50         
51         return abs(arg).hold();
52 }
53
54 static ex abs_eval(const ex & arg)
55 {
56         if (is_exactly_a<numeric>(arg))
57                 return abs(ex_to<numeric>(arg));
58         else
59                 return abs(arg).hold();
60 }
61
62 static void abs_print_latex(const ex & arg, const print_context & c)
63 {
64         c.s << "{|"; arg.print(c); c.s << "|}";
65 }
66
67 static void abs_print_csrc_float(const ex & arg, const print_context & c)
68 {
69         c.s << "fabs("; arg.print(c); c.s << ")";
70 }
71
72 REGISTER_FUNCTION(abs, eval_func(abs_eval).
73                        evalf_func(abs_evalf).
74                        print_func<print_latex>(abs_print_latex).
75                        print_func<print_csrc_float>(abs_print_csrc_float).
76                        print_func<print_csrc_double>(abs_print_csrc_float));
77
78
79 //////////
80 // Complex sign
81 //////////
82
83 static ex csgn_evalf(const ex & arg)
84 {
85         if (is_exactly_a<numeric>(arg))
86                 return csgn(ex_to<numeric>(arg));
87         
88         return csgn(arg).hold();
89 }
90
91 static ex csgn_eval(const ex & arg)
92 {
93         if (is_exactly_a<numeric>(arg))
94                 return csgn(ex_to<numeric>(arg));
95         
96         else if (is_exactly_a<mul>(arg) &&
97                  is_exactly_a<numeric>(arg.op(arg.nops()-1))) {
98                 numeric oc = ex_to<numeric>(arg.op(arg.nops()-1));
99                 if (oc.is_real()) {
100                         if (oc > 0)
101                                 // csgn(42*x) -> csgn(x)
102                                 return csgn(arg/oc).hold();
103                         else
104                                 // csgn(-42*x) -> -csgn(x)
105                                 return -csgn(arg/oc).hold();
106                 }
107                 if (oc.real().is_zero()) {
108                         if (oc.imag() > 0)
109                                 // csgn(42*I*x) -> csgn(I*x)
110                                 return csgn(I*arg/oc).hold();
111                         else
112                                 // csgn(-42*I*x) -> -csgn(I*x)
113                                 return -csgn(I*arg/oc).hold();
114                 }
115         }
116         
117         return csgn(arg).hold();
118 }
119
120 static ex csgn_series(const ex & arg,
121                       const relational & rel,
122                       int order,
123                       unsigned options)
124 {
125         const ex arg_pt = arg.subs(rel, subs_options::no_pattern);
126         if (arg_pt.info(info_flags::numeric)
127             && ex_to<numeric>(arg_pt).real().is_zero()
128             && !(options & series_options::suppress_branchcut))
129                 throw (std::domain_error("csgn_series(): on imaginary axis"));
130         
131         epvector seq;
132         seq.push_back(expair(csgn(arg_pt), _ex0));
133         return pseries(rel,seq);
134 }
135
136 REGISTER_FUNCTION(csgn, eval_func(csgn_eval).
137                         evalf_func(csgn_evalf).
138                         series_func(csgn_series));
139
140
141 //////////
142 // Eta function: eta(x,y) == log(x*y) - log(x) - log(y).
143 // This function is closely related to the unwinding number K, sometimes found
144 // in modern literature: K(z) == (z-log(exp(z)))/(2*Pi*I).
145 //////////
146
147 static ex eta_evalf(const ex &x, const ex &y)
148 {
149         // It seems like we basically have to replicate the eval function here,
150         // since the expression might not be fully evaluated yet.
151         if (x.info(info_flags::positive) || y.info(info_flags::positive))
152                 return _ex0;
153
154         if (x.info(info_flags::numeric) &&      y.info(info_flags::numeric)) {
155                 const numeric nx = ex_to<numeric>(x);
156                 const numeric ny = ex_to<numeric>(y);
157                 const numeric nxy = ex_to<numeric>(x*y);
158                 int cut = 0;
159                 if (nx.is_real() && nx.is_negative())
160                         cut -= 4;
161                 if (ny.is_real() && ny.is_negative())
162                         cut -= 4;
163                 if (nxy.is_real() && nxy.is_negative())
164                         cut += 4;
165                 return evalf(I/4*Pi)*((csgn(-imag(nx))+1)*(csgn(-imag(ny))+1)*(csgn(imag(nxy))+1)-
166                                       (csgn(imag(nx))+1)*(csgn(imag(ny))+1)*(csgn(-imag(nxy))+1)+cut);
167         }
168
169         return eta(x,y).hold();
170 }
171
172 static ex eta_eval(const ex &x, const ex &y)
173 {
174         // trivial:  eta(x,c) -> 0  if c is real and positive
175         if (x.info(info_flags::positive) || y.info(info_flags::positive))
176                 return _ex0;
177
178         if (x.info(info_flags::numeric) &&      y.info(info_flags::numeric)) {
179                 // don't call eta_evalf here because it would call Pi.evalf()!
180                 const numeric nx = ex_to<numeric>(x);
181                 const numeric ny = ex_to<numeric>(y);
182                 const numeric nxy = ex_to<numeric>(x*y);
183                 int cut = 0;
184                 if (nx.is_real() && nx.is_negative())
185                         cut -= 4;
186                 if (ny.is_real() && ny.is_negative())
187                         cut -= 4;
188                 if (nxy.is_real() && nxy.is_negative())
189                         cut += 4;
190                 return (I/4)*Pi*((csgn(-imag(nx))+1)*(csgn(-imag(ny))+1)*(csgn(imag(nxy))+1)-
191                                  (csgn(imag(nx))+1)*(csgn(imag(ny))+1)*(csgn(-imag(nxy))+1)+cut);
192         }
193         
194         return eta(x,y).hold();
195 }
196
197 static ex eta_series(const ex & x, const ex & y,
198                      const relational & rel,
199                      int order,
200                      unsigned options)
201 {
202         const ex x_pt = x.subs(rel, subs_options::no_pattern);
203         const ex y_pt = y.subs(rel, subs_options::no_pattern);
204         if ((x_pt.info(info_flags::numeric) && x_pt.info(info_flags::negative)) ||
205             (y_pt.info(info_flags::numeric) && y_pt.info(info_flags::negative)) ||
206             ((x_pt*y_pt).info(info_flags::numeric) && (x_pt*y_pt).info(info_flags::negative)))
207                         throw (std::domain_error("eta_series(): on discontinuity"));
208         epvector seq;
209         seq.push_back(expair(eta(x_pt,y_pt), _ex0));
210         return pseries(rel,seq);
211 }
212
213 REGISTER_FUNCTION(eta, eval_func(eta_eval).
214                        evalf_func(eta_evalf).
215                        series_func(eta_series).
216                        latex_name("\\eta").
217                        set_symmetry(sy_symm(0, 1)));
218
219
220 //////////
221 // dilogarithm
222 //////////
223
224 static ex Li2_evalf(const ex & x)
225 {
226         if (is_exactly_a<numeric>(x))
227                 return Li2(ex_to<numeric>(x));
228         
229         return Li2(x).hold();
230 }
231
232 static ex Li2_eval(const ex & x)
233 {
234         if (x.info(info_flags::numeric)) {
235                 // Li2(0) -> 0
236                 if (x.is_zero())
237                         return _ex0;
238                 // Li2(1) -> Pi^2/6
239                 if (x.is_equal(_ex1))
240                         return power(Pi,_ex2)/_ex6;
241                 // Li2(1/2) -> Pi^2/12 - log(2)^2/2
242                 if (x.is_equal(_ex1_2))
243                         return power(Pi,_ex2)/_ex12 + power(log(_ex2),_ex2)*_ex_1_2;
244                 // Li2(-1) -> -Pi^2/12
245                 if (x.is_equal(_ex_1))
246                         return -power(Pi,_ex2)/_ex12;
247                 // Li2(I) -> -Pi^2/48+Catalan*I
248                 if (x.is_equal(I))
249                         return power(Pi,_ex2)/_ex_48 + Catalan*I;
250                 // Li2(-I) -> -Pi^2/48-Catalan*I
251                 if (x.is_equal(-I))
252                         return power(Pi,_ex2)/_ex_48 - Catalan*I;
253                 // Li2(float)
254                 if (!x.info(info_flags::crational))
255                         return Li2(ex_to<numeric>(x));
256         }
257         
258         return Li2(x).hold();
259 }
260
261 static ex Li2_deriv(const ex & x, unsigned deriv_param)
262 {
263         GINAC_ASSERT(deriv_param==0);
264         
265         // d/dx Li2(x) -> -log(1-x)/x
266         return -log(_ex1-x)/x;
267 }
268
269 static ex Li2_series(const ex &x, const relational &rel, int order, unsigned options)
270 {
271         const ex x_pt = x.subs(rel, subs_options::no_pattern);
272         if (x_pt.info(info_flags::numeric)) {
273                 // First special case: x==0 (derivatives have poles)
274                 if (x_pt.is_zero()) {
275                         // method:
276                         // The problem is that in d/dx Li2(x==0) == -log(1-x)/x we cannot 
277                         // simply substitute x==0.  The limit, however, exists: it is 1.
278                         // We also know all higher derivatives' limits:
279                         // (d/dx)^n Li2(x) == n!/n^2.
280                         // So the primitive series expansion is
281                         // Li2(x==0) == x + x^2/4 + x^3/9 + ...
282                         // and so on.
283                         // We first construct such a primitive series expansion manually in
284                         // a dummy symbol s and then insert the argument's series expansion
285                         // for s.  Reexpanding the resulting series returns the desired
286                         // result.
287                         const symbol s;
288                         ex ser;
289                         // manually construct the primitive expansion
290                         for (int i=1; i<order; ++i)
291                                 ser += pow(s,i) / pow(numeric(i), _num2);
292                         // substitute the argument's series expansion
293                         ser = ser.subs(s==x.series(rel, order), subs_options::no_pattern);
294                         // maybe that was terminating, so add a proper order term
295                         epvector nseq;
296                         nseq.push_back(expair(Order(_ex1), order));
297                         ser += pseries(rel, nseq);
298                         // reexpanding it will collapse the series again
299                         return ser.series(rel, order);
300                         // NB: Of course, this still does not allow us to compute anything
301                         // like sin(Li2(x)).series(x==0,2), since then this code here is
302                         // not reached and the derivative of sin(Li2(x)) doesn't allow the
303                         // substitution x==0.  Probably limits *are* needed for the general
304                         // cases.  In case L'Hospital's rule is implemented for limits and
305                         // basic::series() takes care of this, this whole block is probably
306                         // obsolete!
307                 }
308                 // second special case: x==1 (branch point)
309                 if (x_pt.is_equal(_ex1)) {
310                         // method:
311                         // construct series manually in a dummy symbol s
312                         const symbol s;
313                         ex ser = zeta(_ex2);
314                         // manually construct the primitive expansion
315                         for (int i=1; i<order; ++i)
316                                 ser += pow(1-s,i) * (numeric(1,i)*(I*Pi+log(s-1)) - numeric(1,i*i));
317                         // substitute the argument's series expansion
318                         ser = ser.subs(s==x.series(rel, order), subs_options::no_pattern);
319                         // maybe that was terminating, so add a proper order term
320                         epvector nseq;
321                         nseq.push_back(expair(Order(_ex1), order));
322                         ser += pseries(rel, nseq);
323                         // reexpanding it will collapse the series again
324                         return ser.series(rel, order);
325                 }
326                 // third special case: x real, >=1 (branch cut)
327                 if (!(options & series_options::suppress_branchcut) &&
328                         ex_to<numeric>(x_pt).is_real() && ex_to<numeric>(x_pt)>1) {
329                         // method:
330                         // This is the branch cut: assemble the primitive series manually
331                         // and then add the corresponding complex step function.
332                         const symbol &s = ex_to<symbol>(rel.lhs());
333                         const ex point = rel.rhs();
334                         const symbol foo;
335                         epvector seq;
336                         // zeroth order term:
337                         seq.push_back(expair(Li2(x_pt), _ex0));
338                         // compute the intermediate terms:
339                         ex replarg = series(Li2(x), s==foo, order);
340                         for (size_t i=1; i<replarg.nops()-1; ++i)
341                                 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));
342                         // append an order term:
343                         seq.push_back(expair(Order(_ex1), replarg.nops()-1));
344                         return pseries(rel, seq);
345                 }
346         }
347         // all other cases should be safe, by now:
348         throw do_taylor();  // caught by function::series()
349 }
350
351 REGISTER_FUNCTION(Li2, eval_func(Li2_eval).
352                        evalf_func(Li2_evalf).
353                        derivative_func(Li2_deriv).
354                        series_func(Li2_series).
355                        latex_name("\\mbox{Li}_2"));
356
357 //////////
358 // trilogarithm
359 //////////
360
361 static ex Li3_eval(const ex & x)
362 {
363         if (x.is_zero())
364                 return x;
365         return Li3(x).hold();
366 }
367
368 REGISTER_FUNCTION(Li3, eval_func(Li3_eval).
369                        latex_name("\\mbox{Li}_3"));
370
371 //////////
372 // factorial
373 //////////
374
375 static ex factorial_evalf(const ex & x)
376 {
377         return factorial(x).hold();
378 }
379
380 static ex factorial_eval(const ex & x)
381 {
382         if (is_exactly_a<numeric>(x))
383                 return factorial(ex_to<numeric>(x));
384         else
385                 return factorial(x).hold();
386 }
387
388 REGISTER_FUNCTION(factorial, eval_func(factorial_eval).
389                              evalf_func(factorial_evalf));
390
391 //////////
392 // binomial
393 //////////
394
395 static ex binomial_evalf(const ex & x, const ex & y)
396 {
397         return binomial(x, y).hold();
398 }
399
400 static ex binomial_eval(const ex & x, const ex &y)
401 {
402         if (is_exactly_a<numeric>(x) && is_exactly_a<numeric>(y))
403                 return binomial(ex_to<numeric>(x), ex_to<numeric>(y));
404         else
405                 return binomial(x, y).hold();
406 }
407
408 REGISTER_FUNCTION(binomial, eval_func(binomial_eval).
409                             evalf_func(binomial_evalf));
410
411 //////////
412 // Order term function (for truncated power series)
413 //////////
414
415 static ex Order_eval(const ex & x)
416 {
417         if (is_exactly_a<numeric>(x)) {
418                 // O(c) -> O(1) or 0
419                 if (!x.is_zero())
420                         return Order(_ex1).hold();
421                 else
422                         return _ex0;
423         } else if (is_exactly_a<mul>(x)) {
424                 const mul &m = ex_to<mul>(x);
425                 // O(c*expr) -> O(expr)
426                 if (is_exactly_a<numeric>(m.op(m.nops() - 1)))
427                         return Order(x / m.op(m.nops() - 1)).hold();
428         }
429         return Order(x).hold();
430 }
431
432 static ex Order_series(const ex & x, const relational & r, int order, unsigned options)
433 {
434         // Just wrap the function into a pseries object
435         epvector new_seq;
436         GINAC_ASSERT(is_a<symbol>(r.lhs()));
437         const symbol &s = ex_to<symbol>(r.lhs());
438         new_seq.push_back(expair(Order(_ex1), numeric(std::min(x.ldegree(s), order))));
439         return pseries(r, new_seq);
440 }
441
442 // Differentiation is handled in function::derivative because of its special requirements
443
444 REGISTER_FUNCTION(Order, eval_func(Order_eval).
445                          series_func(Order_series).
446                          latex_name("\\mathcal{O}"));
447
448 //////////
449 // Solve linear system
450 //////////
451
452 ex lsolve(const ex &eqns, const ex &symbols, unsigned options)
453 {
454         // solve a system of linear equations
455         if (eqns.info(info_flags::relation_equal)) {
456                 if (!symbols.info(info_flags::symbol))
457                         throw(std::invalid_argument("lsolve(): 2nd argument must be a symbol"));
458                 const ex sol = lsolve(lst(eqns),lst(symbols));
459                 
460                 GINAC_ASSERT(sol.nops()==1);
461                 GINAC_ASSERT(is_exactly_a<relational>(sol.op(0)));
462                 
463                 return sol.op(0).op(1); // return rhs of first solution
464         }
465         
466         // syntax checks
467         if (!eqns.info(info_flags::list)) {
468                 throw(std::invalid_argument("lsolve(): 1st argument must be a list"));
469         }
470         for (size_t i=0; i<eqns.nops(); i++) {
471                 if (!eqns.op(i).info(info_flags::relation_equal)) {
472                         throw(std::invalid_argument("lsolve(): 1st argument must be a list of equations"));
473                 }
474         }
475         if (!symbols.info(info_flags::list)) {
476                 throw(std::invalid_argument("lsolve(): 2nd argument must be a list"));
477         }
478         for (size_t i=0; i<symbols.nops(); i++) {
479                 if (!symbols.op(i).info(info_flags::symbol)) {
480                         throw(std::invalid_argument("lsolve(): 2nd argument must be a list of symbols"));
481                 }
482         }
483         
484         // build matrix from equation system
485         matrix sys(eqns.nops(),symbols.nops());
486         matrix rhs(eqns.nops(),1);
487         matrix vars(symbols.nops(),1);
488         
489         for (size_t r=0; r<eqns.nops(); r++) {
490                 const ex eq = eqns.op(r).op(0)-eqns.op(r).op(1); // lhs-rhs==0
491                 ex linpart = eq;
492                 for (size_t c=0; c<symbols.nops(); c++) {
493                         const ex co = eq.coeff(ex_to<symbol>(symbols.op(c)),1);
494                         linpart -= co*symbols.op(c);
495                         sys(r,c) = co;
496                 }
497                 linpart = linpart.expand();
498                 rhs(r,0) = -linpart;
499         }
500         
501         // test if system is linear and fill vars matrix
502         for (size_t i=0; i<symbols.nops(); i++) {
503                 vars(i,0) = symbols.op(i);
504                 if (sys.has(symbols.op(i)))
505                         throw(std::logic_error("lsolve: system is not linear"));
506                 if (rhs.has(symbols.op(i)))
507                         throw(std::logic_error("lsolve: system is not linear"));
508         }
509         
510         matrix solution;
511         try {
512                 solution = sys.solve(vars,rhs,options);
513         } catch (const std::runtime_error & e) {
514                 // Probably singular matrix or otherwise overdetermined system:
515                 // It is consistent to return an empty list
516                 return lst();
517         }
518         GINAC_ASSERT(solution.cols()==1);
519         GINAC_ASSERT(solution.rows()==symbols.nops());
520         
521         // return list of equations of the form lst(var1==sol1,var2==sol2,...)
522         lst sollist;
523         for (size_t i=0; i<symbols.nops(); i++)
524                 sollist.append(symbols.op(i)==solution(i,0));
525         
526         return sollist;
527 }
528
529 /* Force inclusion of functions from inifcns_gamma and inifcns_zeta
530  * for static lib (so ginsh will see them). */
531 unsigned force_include_tgamma = tgamma_SERIAL::serial;
532 unsigned force_include_zeta1 = zeta1_SERIAL::serial;
533
534 } // namespace GiNaC