I know there are a lot of questions on this site regarding the use of For loops and how to avoid them in Mathematica. However, in my case I believe it is justified, as I will show below. My issue is that for very large amount of iterations, the kernel crashes, and so I am looking for a more Mathematica-style solution to my problem.

The aim of my code is to compute successive values of an integral between two points a and b in a cumulative way, i.e., feed back the value of the previous integral into the new value and perform some calculations with the intermediate value. Here is a short code snippet that illustrates my situation:

MyIntegral[a_, b_]:= ...;

For[i=0, i<numericalLimit, i++,

    (* ... some computations with myIntermediateValue *)


    (* ... some computations with myCumulatedValue *)

So as you can see, I need the iterative nature of the For loop in order to work with my cumulated value. Needless to say, as it has been reiterated before on this website (pun not intended), For loops are evil. Moreover, for very large values of numericalLimit the kernel crashes. So my questions are:

  • How can I make this code more Mathematica-like?
  • How can I optimize the computations so that my kernel does not crash for large values of numericalLimit?

Other answers on this website suggest using Table in similar situations, but I fear that it will actually be less efficient when considering $10^{20}$ copies, moreover I don't see how I will be able to cumulate my intermediary results.

Any help is appreciated.

  • 2
    $\begingroup$ You can check Nest, NestList, and Fold commands. All though sometimes trying to find the Mathematica way of doing things make it much more slower. $\endgroup$ – user59583 Dec 19 '18 at 8:56
  • 1
    $\begingroup$ If it's such a simple function like this check out Compile and your function performance might improve by a few orders of magnitude. $\endgroup$ – b3m2a1 Dec 19 '18 at 9:08
  • 2
    $\begingroup$ My "No" means I think personally For and Mathematica-style are mutual exclusive. But all roads lead to Rome, so one can achieve the same thing by other methods. $\endgroup$ – Αλέξανδρος Ζεγγ Dec 19 '18 at 9:09
  • 1
    $\begingroup$ For iterative statements like this, it is almost always better to use Do instead of For. For more specific advice, knowledge of the nature of the commented calculations would be useful. For example what needs to happen with the output of those calculations? Given the number of iterations, preventing any memoryleak issues will be important. $\endgroup$ – mmeent Dec 19 '18 at 9:21
  • 2
    $\begingroup$ @Klangen sure: reference.wolfram.com/language/ref/Compile.html#Examples $\endgroup$ – b3m2a1 Dec 19 '18 at 9:56

Your Answer

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

Browse other questions tagged or ask your own question.