0
$\begingroup$

Imagine I'm trying to add some value $r$ to each element in a very large array $L$. Take for example:

L = Table[RandomReal[{0,1}],{q,1,10^7}];
r = 0.0032;

I can effectively add $r$ to each element in $L$ by writing:

L = Table[L[[q]]+r,{q,1,Length[L]}];

This operation takes about $\approx 322$ milliseconds. However, is there a better / faster way to proceed?

$\endgroup$
2
$\begingroup$

Take advantage of listability -- meaning that you do not have to loop through the list, just add r to the list.

Timing[L1 = Table[L[[q]] + r, {q, 1, Length[L]}];]
(* {1.288042, Null} *)

faster listable alternative:

Timing[L2 = L + r;]
(* {0.339668, Null} *)

L1 == L2
(* True  *)

Timings on old Mac running V8.

$\endgroup$
1
$\begingroup$

This can speeded up even more by eliminating Table as well as using listability. Here are timings from my system.

r = 0.0032;
SeedRandom[42]; 
Timing[t1 = Table[RandomReal[{0, 1}], {q, 1, 10^7}];
  t2 = Table[t1[[q]] + r, {q, 1, Length[t1]}];]

{1.331451, Null}

SeedRandom[42];
Timing[tbl = RandomReal[1., 10^7] + r;]

{0.243818, Null}

tbl == t2

True

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.