Execute this by installing SymEngine into Sage and launching Jupyter:
$ ./sage -i ~/Downloads/curl-7.43.0.spkg
$ ./sage -i ~/Downloads/cmake-3.2.3.spkg
$ ./sage -i ~/Downloads/symengine-0.1.spkg
$ ./sage --notebook=ipython
import symengine
Create Sage expression:
var("x y z")
n = 15
e = (x+y+z+1)**n
f = e*(e+1)
f, type(f)
(((x + y + z + 1)^15 + 1)*(x + y + z + 1)^15, <type 'sage.symbolic.expression.Expression'>)
Convert it to SymEngine:
f2 = symengine.sympify(f)
f2, type(f2)
((1 + (1 + x + y + z)**15)*(1 + x + y + z)**15, <type 'symengine.lib.symengine_wrapper.Mul'>)
Benchmark it:
%time g = f.expand()
CPU times: user 3.19 s, sys: 2.14 ms, total: 3.19 s Wall time: 3.2 s
%time g2 = f2.expand()
CPU times: user 1.41 s, sys: 3.67 ms, total: 1.41 s Wall time: 1.41 s
See how long it takes to get list of terms (though the timing will reflect if the terms are sorted or not):
%time len(g.operands())
CPU times: user 39.3 ms, sys: 0 ns, total: 39.3 ms Wall time: 39.4 ms
5456
%time len(g2.args)
CPU times: user 17.4 ms, sys: 0 ns, total: 17.4 ms Wall time: 17.5 ms
5456
print g.operands()[:10]
print g2.args[:10]
[x^30, 30*x^29*y, 435*x^28*y^2, 4060*x^27*y^3, 27405*x^26*y^4, 142506*x^25*y^5, 593775*x^24*y^6, 2035800*x^23*y^7, 5852925*x^22*y^8, 14307150*x^21*y^9] (2, 45*x, z**30, 30*y*z**29, 45*y, 1080*x*y, 540*y**2, 4515*y**3, 28770*y**4, 13545*x*y**2)
Sage:
def fact(n):
if n in [0, 1]:
return 1
else:
return n*fact(n-1)
def diff(e, x, n):
for i in range(n):
e = e.diff(x)
return e
def legendre(n, x):
e = Integer(1)/(Integer(2)**n * fact(Integer(n))) * diff((x**2-1)**n, x, n)
return e.expand()
var("x")
for n in range(10):
print n, legendre(n, x)
0 1 1 x 2 3/2*x^2 - 1/2 3 5/2*x^3 - 3/2*x 4 35/8*x^4 - 15/4*x^2 + 3/8 5 63/8*x^5 - 35/4*x^3 + 15/8*x 6 231/16*x^6 - 315/16*x^4 + 105/16*x^2 - 5/16 7 429/16*x^7 - 693/16*x^5 + 315/16*x^3 - 35/16*x 8 6435/128*x^8 - 3003/32*x^6 + 3465/64*x^4 - 315/32*x^2 + 35/128 9 12155/128*x^9 - 6435/32*x^7 + 9009/64*x^5 - 1155/32*x^3 + 315/128*x
%time e = legendre(500, x)
CPU times: user 4.62 s, sys: 155 ms, total: 4.78 s Wall time: 4.18 s
SymEngine:
def fact(n):
if n in [0, 1]:
return 1
else:
return n*fact(n-1)
def diff(e, x, n):
for i in range(n):
e = e.diff(x)
return e
def legendre(n, x):
e = symengine.Integer(1)/(symengine.Integer(2)**n * fact(symengine.Integer(n))) * diff((x**2-1)**n, x, n)
return e.expand()
symengine.var("x")
for n in range(10):
print n, legendre(n, x)
0 1 1 x 2 -1/2 + (3/2)*x**2 3 (-3/2)*x + (5/2)*x**3 4 3/8 + (-15/4)*x**2 + (35/8)*x**4 5 (15/8)*x + (-35/4)*x**3 + (63/8)*x**5 6 -5/16 + (105/16)*x**2 + (-315/16)*x**4 + (231/16)*x**6 7 (-35/16)*x + (315/16)*x**3 + (-693/16)*x**5 + (429/16)*x**7 8 35/128 + (-315/32)*x**2 + (3465/64)*x**4 + (-3003/32)*x**6 + (6435/128)*x**8 9 (315/128)*x + (-1155/32)*x**3 + (9009/64)*x**5 + (-6435/32)*x**7 + (12155/128)*x**9
%time e = legendre(500, x)
CPU times: user 1.29 s, sys: 0 ns, total: 1.29 s Wall time: 1.28 s