Question

I wanted to calculate the power sum S_p(x) = 1^p + 2^p + 3^p + ... + x^p using the code

powersum[x_,p_]:=sum=0;For[i=1,i<x,i++,sum=sum+i^p];sum

but it seems to output 0 every time. Why does it do that?

Was it helpful?

Solution 2

Often it is preferable to use Module[]:

 powersum[x_,p_]:=Module[{sum},sum=0;For[i=1,i<x,i++,sum=sum+i^p];sum]

or

 powersum[x_,p_]:=Module[{sum=0},For[i=1,i<x,i++,sum=sum+i^p];sum]

this is essentially the same as wrapping in () except sum is protected in a local context.

of course for this example you could as well use :

 powersum[x_,p_]:=Sum[i^p,{i,1,x-1}]

or

 powersum[x_, p_] := Range[x - 1]^p // Total

OTHER TIPS

As written, Mathematica is parsing your expression like this:

 powersum[x_,p_]:=sum=0;  (*Definition ended here*)
 For[i=1,i<x,i++,sum=sum+i^p];
 sum

You need to use to wrap your expression in parenthesis to make them all part of the function definition.

powersum[x_,p_]:=(sum=0;For[i=1,i<x,i++,sum=sum+i^p];sum)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top