Ways to speed up numerical integration
Let NDSolve do the job one time (instead of Integrate many times)
Edit Make it faster. AbsouteTiming for all calculations == 0.015 seconds.
(tpw[t_] = Total@pulses;
gsol = g /.
First@NDSolve[{g'[t] == tpw[t], g[0] == 0}, g, {t, 0, 250}];
norm = gsol[250] ;(*11.*)
{t05 = t /. First@FindRoot[gsol[t] == .05 norm, {t, 0, 150}],
t95 = t /. First@FindRoot[gsol[t] == .95 norm, {t, 0, 150}]}
) // AbsoluteTiming
(* {0.0155646, {4.06347, 128.699}} *)
NIntegrate[Total@pulses, {t, 0, t05}]/norm
(* 0.05 *)
NIntegrate[Total@pulses, {t, 0, t95}]/norm
(* 0.95 *)
Plot[{1, .05, .95, gsol[t]/norm}, {t, 0, 150}]
Should be a bit faster... Long story short: Supply the Jacobian
of your equation to FindRoot
, too.
ϕ = t \[Function] Evaluate[Total@pulses];
ClearAll[Φ];
Φ[x_?NumericQ] := NIntegrate[ϕ[t], {t, 0., x}, PrecisionGoal -> 8];
rhs = 0.05 Φ[tmax];
(*An approximate inverse of Φ*)
tlist = Subdivide[0., tmax, 100];
Ψ = Quiet[
Interpolation[
Transpose[{Accumulate[N[ϕ /@ tlist]], tlist}],
InterpolationOrder -> 1]
];
(*Initial guess:*)
x0 = Ψ[rhs];
(*Using Newton's method.The Jacobian of Φ is easy enough to compute!;)*)
sol = FindRoot[Φ[x] == rhs , {x, x0},
Jacobian :> {{ϕ[x]}}]; // AbsoluteTiming // First
0.056017
Test:
Φ[x] - rhs /. sol
-1.11022*10^-16
Btw.: There is no point in enforcing 100(!) digits of precision with PrecisionGoal -> 100
if FindRoot
's default PrecisionGoal
is used (it's about 8, isn't it?).