I'm trying to parallelize a simple routine inside a "for" loop. Essentially, I need to compute the roots of a function $f(x)$ that depends on the discrete parameters $d$ and $R_0$. However, I also need to impose conditions on the results using an "if" statement. How can I parallelize this code to make it more efficient?

Here is the original code without parallelization:

ld = {};
Quiet[For[i = 0.1, i <= 30, i = i + 0.01,
  Clear[x, d, sole];
  d = i*R0;
  sole = FindRoot[f[x,d], {x, 0}];
  x = x /. sole[[1]] // Chop;
  If[Abs[x] < 10^(-6), AppendTo[ld, {d, 0}], 
   AppendTo[ld, {d, x}]]]]

Can you help me to parallelize it?



2 Answers 2


Use ParallelTable instead of Do + AppendTo. In general, better never use AppendTo; it was super inefficient in older Mathematica versions; and I think it would still break the parallelization.

ld = ParallelTable[
    d = i*R0;
    sole = FindRoot[f[x, d], {x, 0}];
    x = x /. sole[[1]] // Chop;
    If[Abs[x] < 10^(-6), {d, 0}, {d, x}]
  , {i, 0.1, 30, 0.01}]

Define a function that generates what you need: what you write can be simplified to a single Chop call with a tolerance of $10^{-6}$,

s[d_?NumericQ] := {d, Chop[x /. FindRoot[f[x, d], {x, 0}], 10^-6]};

Make a table, possibly parallelized:

ParallelTable[s[i*R0], {i, 0.1, 30, 0.01}]

For added versatility you may want to memoize the results of the function s instead of storing them in a table:

s[d_?NumericQ] := s[d] = {d, Chop[x /. FindRoot[f[x, d[i]], {x, 0}], 10^-6]};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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