Abdullah,
The more "Mathematica" way to do this is with a table and to do the write at the end rather than append to the file.
First, Lets define a function:
func2[x_Real, y_Real] := Sin[x]*Sin[y]
I use the _Real to make sure that Mathematica does not first do a symbolic integral.
your way:
AbsoluteTiming[
For[i = 30, i <= 40, i = i + 1,
PutAppend[NIntegrate[func2[x, y], {x, 30, i}, {y, 0, i}],
"FileToSaveTo.csv"]]]
I get about 19 seconds
The table approach and write at the end:
AbsoluteTiming[
Export["FileToSaveTo2.csv",
Table[NIntegrate[func2[x, y], {x, 30, i}, {y, 0, i}], {i, 30, 40}]]]
I get about 18 seconds for a modest savings.(although the savings will grow with problem size)
To really get some savings in time you should realize that you are computing the same areas over and over again (integrating from 0 to 30, then 0 to 31, etc.).
If we save our most recent calculation and add on the small additional piece, we can get extreme computation savings. I make a function integral2[x,y,delta] which is my integral at {x,y} and I pass delta so the function knows my step size (in my example case, delta =1 )
ClearAll[integral2];
integral2[nx_, ny_, delta_] :=
integral2[nx, ny, delta] =
integral2[nx - delta, ny - delta, delta] +
NIntegrate[func2[x, y], {x, 30, nx - delta}, {y, ny - delta, ny}] +
NIntegrate[func2[x, y], {x, nx - delta, nx}, {y, 0, ny}]
integral2[30, 30, 1] = 0;
The integral2[] function saves the last answer by assigning it to integral2[] using this construct in the definition:
integral2[nx, ny, delta] = ...
Using this approach we solve the problem and write the answer to a file in 0.9 seconds!!
AbsoluteTiming[
Export["FileToSaveToFast.csv",
Table[integral2[i, i, 1], {i, 31, 40}]]]
and because all the answers are now cached, running it a second time does the computation in 0.002 seconds! to see the cached answers type this:
?integral2
I hope this helps,
Regards,
Neil