MATHEMATICS

Sabtu, 14 Mei 2011

Sum of a list in Mathematica

Problem: We want to calculate the sum of the elements of a list of numbers. Suppose this list is named l and has been assigned the value {1,2, ..., 20}

Method 1: ( Use the Mathematica function to total the values in a list. )
Total[l]

Method 2: ( Use the formula for the sum of an arithmetic sequence, with l[[1]] being the first element, l[[Length[l]]] being the last element and Length[l] the number of elements.)
(l[[1]] + l[[Length[l]]])*Length[l]/2

Method 3: ( Go through all the elements from the first to the last and add them to a running total. )
Sum[l[[k]], {k, 1, Length[l]}]

Method 4: ( Recursively define the total of a list. )
s[{}] := 0
s[l_] := First[l] + s[Rest[l]]

Method 5: ( Use some intricate method of the Mathematica language. )
Fold[#1 + #2 &, 0, l]

All five methods give the same result 210.


Set l := Array[#&,20];

Or use the following to test the commands.

Total[Array[#&,20]]

(Array[#&,20][[1]] + Array[#&,20][[Length[Array[#&,20]]]])*Length[Array[#&,20]]/2

Sum[Array[#&,20][[k]], {k, 1, Length[Array[#&,20]]}]

s[{}] := 0
s[l_] := First[l] + s[Rest[l]]
s[Array[#&,20]]

Fold[#1 + #2 &, 0, Array[#&,20]]

Tidak ada komentar:

Posting Komentar