Lines 33
##### Keywords
Legendre polynomials (1) maths (2) numerics (5)
##### Permissions
Owner: Stou S.
Viewable by Everyone
Editable by All Siafoo Users

# Using sympy to generate C++ code for Legendre Polynomials 0

 In Brief A bit of code for generating sums of Legendre polynomials using the SymPy framework's C++ code generating facilities.
 Language Python
# '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)}131415def 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)}2627    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)))) 3132x = Symbol('x')3334P = [1, x]3536for 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)4142#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.