I have a math problem that I have solved analytically. I now want to generate a number of graphs based on different parameter values. My problem is threefold:
- It takes a couple of minutes to produce a single graph.
I am wasting time waiting until one graph is finished so that I can start the next one for different parameter values, or one for e.g. different domain and range of the plot.
My code seems generally badly designed.
What I'd like is:
Make the computation much more efficient, and maybe less messy in terms of code.
More importantly: Make it so that I can generate an arbitrary amount of graphs for different settings very easily, and wait until the computer finishes them all. An make it so that after the computation is done, I can easily change the range and domain of the graph, and its design, without the computer having to redo the underlying computations.
Generally improve the design of the code.
Here is the mathematical problem (the code is given below):
The heaviest part of the computation seems to be in finding $t$.
I have taken as a first example, $$A(i)= \begin{cases} 0 &\text { if } i<a\\ tech\cdot(i-a) &\text { if } i\geq a\end{cases}$$ For some real number $tech$.
I use the following code to compute this problem:
ClearAll[x, A, i, L, K, phi, t, intA]
A[i_, tech_] := If[i > a, tech*(i - a), 0];
intA[t_?NumericQ, tech_] :=
NIntegrate[A[i, tech]^(phi/(1 - phi)), {i, Max[a, t], 1}];
t[LK_, tech_] :=
t[LK, tech] =
x /. FindRoot[A[x, tech] - ((LK/x)*intA[x, tech])^(1 - phi),
{x, (a + 1)/2}]
L = 5;
K = 5;
phi = -0.5;
a = 0.5;
tech = 20;
cL[L_, K_, tech_] := L/t[L/K, tech];
cK[L_, K_, tech_] := K/intA[t[L/K, tech], tech];
Lab[i_, L_, K_, tech_] := If[i > t[L/K, tech], 0, cL[L, K, tech]];
Kap[i_, L_, K_, tech_] :=
If[i > t[L/K, tech], (cK[L, K, tech])*(A[i, tech])^(phi/(1 - phi)),
0];
Plot[{Lab[i, L, K, tech], Kap[i, L, K, tech]*A[i, tech],
A[i, tech]}, {i, 0, 1}, PlotRange -> All]
tildeF[L_, K_, tech_] :=
tildeF[L, K, tech] =
NIntegrate[(Lab[i, L, K, tech] + A[i, tech]*Kap[i, L, K, tech])^
phi, {i, 0, 1}];
F[L_, K_, tech_] := tildeF[L, K, tech]^(1/phi);
F[5, 5, 30]
Plot3D[{F[L, K, tech]}, {L, 0, 10}, {K, 0, 10}]
It is especially the Plot3D that is taking most of the computation time.