# How to expand an symbolic expression.

With Maple I can write

T := proc(f,n,x)
local v;
end:


and then

T(f,4,x)


f(1)+4*f(2)*x+6*f(3)*x^2+4*f(4)*x^3+f(5)*x^4.


If I write the same with Sage

def T(f,n,x):
return add(binomial(n,v)*f(v+1)*(x)^v for v in (0..n))
var('f')
T(f,4,x)


then I will get the answer

5*x^4 + 16*x^3 + 18*x^2 + 8*x + 1.


How do I have to proceed to get Maple's answer?

edit retag close merge delete

The answer, as indicated by burcin, simply is: Replace in your code "var('f')" by "f=function('f')".

( 2012-01-24 00:38:34 -0500 )edit

Sort by Ā» oldest newest most voted
f=function('f')
def T(f,n,x):
ans=0
for v in range(n+1):
ans=ans+binomial(n,v)*f(v+1)*(x)^v
return ans

print T(f,4,x)


gives:

x^4*f(5) + 4*x^3*f(4) + 6*x^2*f(3) + 4*x*f(2) + f(1)

more

This should do the job.

f=function('f')
def T(f,n,x):
ans=0
for v in range(n+1):
ans=ans+binomial(n,v)*f(v+1)*(x)^v
return ans

print T(f,4,x)

more

This gives the answer 16*x^3 + 18*x^2 + 8*x + 1.

( 2012-01-23 22:44:21 -0500 )edit

I made a couple of changes to fix the code above. Declared f as a symbolic function, removed redundant var('ans'), and fixed the bounds for range().

( 2012-01-23 23:18:35 -0500 )edit

burcin, changing an answer is not a good way to edit. It makes my comment ridiculousĀ  and gives credit for the right answer to the wrong person. Please give your own answer. I will accept it then.

( 2012-01-24 00:38:40 -0500 )edit

I would have voted Shashank's answer down (if I had >100 points), not because it was wrong, but because Shashank obviously did not even verify his answer by testing it at least once.

( 2012-01-24 01:44:15 -0500 )edit