License Public Domain
Lines 33
Keywords
Legendre polynomials (1) maths (2) numerical computing (8) numerics (5)
Permissions
Owner: Stou S.
Viewable by Everyone
Editable by All Siafoo Users
Hide
Siafoo is here to make coding less frustrating and to save you time. Join Siafoo Now or Learn More

Using sympy to generate C++ code for Legendre Polynomials Atom Feed 0

In Brief A bit of code for generating sums of Legendre polynomials using the SymPy framework's C++ code generating facilities.
# 's
 1# legendre.py - Generate C++ code for Legendre Polynomials
2#
3# Author: stou@icapsid.net
4# License: Public Domain
5
6from sympy import *
7
8
9def render_function(n, P_n):
10 print ''' template<typename T> T P_%(n)i(T x){
11 return %(code)s;
12 }''' % {'n':n, 'code':printing.ccode(P_n)}
13
14
15def render_functors(Ps):
16
17 print '#include <cmath>'
18 print 'Polynomial LPolynomials[%i];' % len(Ps);
19
20 for n, P_n in enumerate(Ps):
21 print '''template<typename T> struct P_%(n)i {
22 T operator()(T x) {
23 return %(code)s;
24 }
25};''' % {'n':n, 'code':printing.ccode(P_n)}
26
27 for n in range(len(Ps)):
28 print 'LPolynomials[%(n)i] = (Polynomial) P_%(n)i<double>();' % {'n':n}
29
30# {%s};' % (', '.join('P_%i<double>()' %i for i in range(len(Ps))))
31
32x = Symbol('x')
33
34P = [1, x]
35
36for n in range(1, 3):
37 P_new = ((2*n+1)*x*P[n] - n * P[n-1])/(n+1)
38 P.append(P_new)
39
40render_functors(P)
41
42#for i, P_n in enumerate(P):
43# render_function(i, P_n)

A bit of code for generating sums of Legendre polynomials using the SymPy framework's C++ code generating facilities.