0
$\begingroup$

I have an integral of a sum of many terms:

$\int \int S_y^2 a a^\dagger f_1(t_1)f_2(t_2)^* + ...$

For example

Integrate[Integrate[(-I)*a*h*Sy^2*Conjugate[f[2, t2]]*f[1, t1] + (I/2)*a*h^3*Sy^2*Conjugate[f[2, t2]]*f[1, t1] - ... ,{t2, 0, t1}], {t1, 0, t}]

where the only time dependence is f which is undefined. And my replacement rule is simple:

outrules = {Integrate[f_ + g_, it : {x_Symbol, __}] :> 
    Integrate[f, it] + Integrate[g, it], 
   Integrate[c_ f_, it : {x_Symbol, __}] :> 
    c Integrate[f, it] /; FreeQ[c, x]};

I want to replace the integral of a sum of terms into a sum of integrals, and pull all constants out of each integral. My rule seems to work for smaller sums but takes forever on longer ones, how can I speed it up?

$\endgroup$
1
  • $\begingroup$ Please provide also en example of your expression with integrals. $\endgroup$
    – Domen
    Nov 7, 2023 at 17:05

1 Answer 1

2
$\begingroup$

I believe the code is slow because Integrate will try to evaluate the intermediate expressions before they are fully resolved. You may try using Inactivate, and do the replacement on the Inactive[Integrate], activating them only at the end.

Also, you probably want to do ReplaceRepeated (//.) instead of ReplaceAll (/.).

outrules = {Integrate[f_+g_, it : {x_Symbol, __}] :> Integrate[f, it] + Integrate[g, it], 
   Integrate[c_ f_, it : {x_Symbol, __}] :> c Integrate[f, it] /; FreeQ[c, x]};

expr = Integrate[Integrate[Sum[RandomInteger[{-50, 50}] h^i Conjugate[
       f[RandomInteger[{-3, 3}], t2]]*f[1, t1], {i, 5}], {t2, 0, t1}], {t1, 0, t}];


(expr //. outrules) // AbsoluteTiming // First
(* 15 seconds *)


exprInactive = Inactivate[Evaluate[expr], Integrate];
outrulesInactive = Inactivate[Evaluate[outrules], Integrate];

((exprInactive //. outrulesInactive) // Activate) // AbsoluteTiming // First
(* 2 seconds *)
$\endgroup$
1
  • $\begingroup$ Thank you so much!!!!!!! $\endgroup$
    – Luca
    Nov 7, 2023 at 21:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.