       Re: Help please: Summing a list

• To: mathgroup at smc.vnet.net
• Subject: [mg13494] Re: [mg13480] Help please: Summing a list
• From: "Clemens Frey" <Clemens.Frey at uni-bayreuth.de>
• Date: Fri, 31 Jul 1998 04:33:14 -0400
• Sender: owner-wri-mathgroup at wolfram.com

```Rob:

I think you made three mistakes in PP[[i]]:=Sum[P[[n]],{n,0,i}];

1st:
you tried to make up a list by PP[[i]]= ..., but PP was not known by
Mathematica, so the you came up this error message

2nd:
part 0 of an expression is its head, so the range specification in Sum
is wrong, too. (e.g.: {1,2,3}[] gives List, the head of {1,2,3})

3nd:
you used a delayed set  (:=) instead of an immediate one (=). (more

So I have the correction and an advice: (where a definition of
P=Table[6,{x,0,110}];   is supposed)

CORRECTION:

PP =
le[
Sum[P[[n]],{n,1,i}],
{i,1,Length[P]}
];

PPP = Table[
Plus @@ Take[P,i],
{i,1,Length @ P}
];

where @@ is a shortcut for Apply[].
It is better to use the 2nd alternative since it is ten times faster and
yields an equal result, as the following shows:

Timing[
PP = Table[
Sum[P[[n]],{n,1,i}],
{i,1,Length @ P}
];
]

gives:
{0.44 Second, Null}

Timing[
PPP = Table[
Plus @@ Take[P,i],
{i,1,Length @ P}
];
]

gives:
{0.06 Second, Null}

and finally,

PP == PPP

yields True.

regards

Clemens
clemens.frey at uni-bayreuth.de

------------------------------------------------------------------------------------------
PS:
If you want to use a delayed set and thus define a function, use:

func[P_List] := Table[
Plus @@ Take[P,i],
{i,1,Length[P]}
];

and compare with the upper results:

func[P] == PPP == PP

True

```

• Prev by Date: Re:Help please: Summing a list
• Next by Date: GRTensorM