3
$\begingroup$

I've gotten unexpected (at least to my novice eyes) application of a list of values to a Sum expression where the variable for imax is also used in the expression summed. For example:

n={10,100,1000,10000}

N[Sum[(i+1)/n^2,{i,1,n}]]

yields:

{{0.65, 51.5, 5015., 500150.}, {0.0065, 0.515, 50.15,5001.5}, 
{0.000065, 0.00515, 0.5015, 50.015}, {6.5*10^-7, 0.0000515,0.005015, 0.50015}}

when I was expecting:

{0.65, 0.515, 0.5015, 0.50015}

The two workarounds I've found to get my expected solution were to

(1) create a function for the summation and SetAttributes to Listable, eg.

f[x_]:=N[Sum[(i+1)/n^2,{i,1,n}]];
SetAttributes[f,Listable]

or

(2) first evaluate the expression to be summed symbolically, then apply the list

b=Sum[(i+1)/n^2,{i,1,n}]

(3 + n)/(2 n)

n={10,100,1000,10000}

N[b]
{0.65, 0.515, 0.5015, 0.50015}

Is it normal for Mathematica to apply the list as initially shown? If so, why, and is there a better way to achieve my solution than the two ways I've found?

$\endgroup$
  • 1
    $\begingroup$ Yes, this is the expected behavior. Try to write 1/{1,2,3,4,5} and see what the result is. Then try {1,2,3,4,5}+{6,7,8,9,10}. These two examples show why the result is what it is in your care. $\endgroup$ – C. E. Apr 9 '15 at 22:20
  • $\begingroup$ @Pickett Thanks for the response. However, both your examples give me the response I expect, applying each value in the list once. But applying a list to the Sum function seems to iterate the list values across the Sum function. It's not clear to me why it's doing that. $\endgroup$ – BCott Apr 10 '15 at 17:15
  • $\begingroup$ @Shutao Tang Thanks for the answer, particularly showing the use of the Tr function. $\endgroup$ – BCott Apr 10 '15 at 17:28
  • $\begingroup$ @BCott, You are welcome. $\endgroup$ – xyz Apr 11 '15 at 6:23
1
$\begingroup$

You can use the Map function directly:

f[n_] := N[Sum[(i + 1)/n^2, {i, 1, n}]];
n= {10, 100, 1000, 10000};
f /@ n(**or Map[f, n])
{0.65, 0.515, 0.5015, 0.50015}

Or

Tr[
  N[Sum[(i+1)/n^2,{i,1,n}]],List]
{0.65, 0.515, 0.5015, 0.50015}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.