Alternating Series Construct
- To: mathgroup at christensen.cybernetics.net
- Subject: [mg348] Alternating Series Construct
- From: Xah Y Lee <xyl10060 at fhda.edu>
- Date: Wed, 21 Dec 1994 05:51:50 -0800 (PST)
> Here's an elementary question that has me partially > stumped. I often have occasion to convert mylist = > {a1,a2,a3,...} into an alternating sum, a1-a2+a3-a4+... Hi, Mathematica fans. Here's the summary of various methods. The number in the comment indicate the number of seconds it took on my machine. The output of each methods are assigned to b1, b2, b3..etc, so at the end we can test b1==b2==b3... to see if they all work. mylistS is a list of the form {a1,a2,a3,...,a601}. mylistN is {1,2,3,...,4000}. -- mylistS = Table[ ToExpression@ StringJoin["a", ToString[i] ], {i, 1, 601} ]; mylistN = Range[4000]; -- mylist = mylistN; (* or mylist = mylistS *) -- (*.93 symbolic , 2.97 numerical*) xlist = Transpose@ { Table[1,{Length[mylist]/2}], Table[-1,{Length[mylist]/2}] }; b1 = mylist . Flatten@ If[ EvenQ @ Length @ mylist, xlist, Append[xlist, 1] ]; -- (* 1.22 symbolic , 4.67 numerical*) xlist = Plus@@Apply[Subtract,Partition[mylist,2],{1}]; b2 = If[ EvenQ @ Length @ mylist, xlist, xlist + Last @ mylist ]; -- (* 1.8 symbolic , 7.3 numerical*) b3 = Sum[ Part[mylist,i], {i, 1, Length[mylist], 2} ] - Sum[ Part[mylist,i], {i, 2, Length[mylist], 2} ]; -- (* 2.5 symbolic , 15.02 numerical *) b4 = -Sum[ (-1)^(i) Part[mylist,i], {i, 1, Length[mylist]} ]; -- (* 2.9 symbolic , 20.52 numerical *) sign = -1; b5 = Plus@@(( sign *=-1; sign #)& /@ mylist ); -- (*142 symbolic, 11.82 numerical *) b6 = Fold[ (#2-#1)& , 0, Reverse@mylist]; -- (* n/a symbolic, 204 numerical*) b7 = Head[ 0 @@ mylist //. sum_[odd_, even_:0, rest___] -> (sum + odd - even)[rest] ]; -- b1==b2==b3==b4==b5==b6 (* == b7 *) Xah Lee Venus & Xah Love Factory xyl10060 at tiptoe.fhda.edu No sexual solicitation please. Mathematical solicitation OK.