I have two functions, one of which calls the other. I need to do some calculations but I was unable to optimize my code to do it efficiently.
In search I came across the memoization technique, which improved my code significantly, but still not enough.
Below is my code:
Clear[function1,function2]
function1[i_,j_]:=function1[i,j]=
Which[
i >= 40, 1.0,
j >= 40, 0.0,
FractionalPart[j] >= 0.40, 0.0,
True, 0.18*0.45*(1 - function2[j, i+1]) + 0.66*0.45*(1 - function2[j, i+2]) + 0.16*0.45*(1 - function2[j, i+3]) + (1 - 0.18*0.45 - 0.66*0.45 - 0.16*0.45)*(1 - function2[j, i])
];
function2[j_,i_]:=function2[j,i]=
Which[
j >= 40, 1.0,
i >= 40, 0.0,
True, 0.18*0.55*(1 - function1[i, j+1]) + 0.66*0.55*(1 - function1[i, j+2]) + 0.16*0.55*(1 - function1[i, j+3]) + (1 - 0.18*0.55 - 0.66*0.55 - 0.16*0.55)*(1 - function1[i, j+0.01])
];
And my timings:
function1[0, 0]//AbsoluteTiming
(* Out: {8.56012,0.218588} *)
Any idea how to improve speed? I am positive that my approach is just too amateur, as I am not experienced with Mathematica. Thank you in advance.