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_]:= ...;
numericalLimit:=10^20;
For[i=0, i<numericalLimit, i++,
(
myIntermediateValue=MyIntegral[i,i+1];
(* ... some computations with myIntermediateValue *)
myCumulatedValue+=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.