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?
Answer
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}
Comments
Post a Comment