I have a
list
of pairs of numbers and I'd like to change the sign of the second element in each pair i.e. $(a,b)\rightarrow (a,-b)$.
I'm sure there are many ways to do this. Starting from an example list the ways I know are
list = Table[{j, j}, {j, 200}];
Table[{list[[s, 1]], -list[[s, 2]]}, {s, 1, Length[list], 1}]
Partition[Riffle[Transpose[list][[1]], -1 Transpose[list][[2]]], 2]
{#1, -#2} & @@@ list
They all produce the same output and I expected the final method to be the fastest as it utilises Mathematica's functional programming abilities. More generally I expected the timings for each method to be constant upon repetition, meaning if I executed the same code many times I'd get the same answer.
However when I timed them for 10 runs of 1000 executions each I get the following
Table[Timing[
Do[Table[{list[[s, 1]], -list[[s, 2]]}, {s, 1, Length[list],
1}], {1000}]][[1]], {10}]
(*{0.344, 0.281, 0.312, 0.313, 0.265, 0.297, 0.328, 0.375, 0.297, 0.297}*)
Table[Timing[
Do[Partition[Riffle[Transpose[list][[1]], -1 Transpose[list][[2]]],
2], {1000}]][[1]], {10}]
(*{0.11, 0.093, 0.125, 0.11, 0.109, 0.094, 0.109, 0.094, 0.109, 0.125}*)
Table[Timing[Do[{#1, -#2} & @@@ list, {1000}]][[1]], {10}]
(*{0.219, 0.219, 0.219, 0.25, 0.218, 0.219, 0.25, 0.188, 0.234, 0.312}*)
and it seems I was wrong on both of my expectations. Variable timings and @@@
came in second place. Partition[Riffle.....
was approx twice as fast as the others.
Could someone explain the reasons for (a) the variable timing and (b) why the Partition[Riffle.....
method is more efficient than the @@@
method when I would have guessed it has more computational steps?
AbsoluteTiming
? $\endgroup$list . {{1, 0}, {0, -1}}
. For larger lists, the advantage grows to many orders of magnitude. $\endgroup$list.{1,-1}
. It didn't work so I started with the above. Looking back now the dimensions are obviously wrong but ya you're right that is more natural method to do it though. Thanks. $\endgroup$