Search code examples
pythonsympysymbolic-integration

Speeding up integration by Sympy integrate


There are two functions expFun1 and expFun2 that I try to integrate from t to s with respect to u.

import sympy as sym

# It returns a symbolic function where u is the only symbol in the function
def expFun1(X1,X2,a1,a2,T,u):        
    fx= X1*sym.exp(-a1*(T-u))+X2*sym.exp(-a2*(T-u))
    return fx

# Squared version of expFun1
def expFun2(X1,X2,a1,a2,T,u):        
    fx= (X1*sym.exp(-a1*(T-u))+X2*sym.exp(-a2*(T-u))) **2
    return fx

I pass the following arguments into the functions, where u is the only symbolised variable.

u = sym.symbols('u')
t=0
s=1
T=1.2
X1, X2, a1, a2= [0.5, 0.3, 2, 0.1] 

Fx1=sym.integrate(expFun1(X1,X2,a1,a2,T,u), (u,t,s))
Fx2=sym.integrate(expFun2(X1,X2,a1,a2,T,u), (u,t,s))

Computation time for Fx1 is approx 0.09 seconds. However, it is approx 30 seconds for Fx2. In the actual application I need to loop through different values for the non-symbolic arguments, and the integration for expFun2 takes forever.

What would be the best way to speed up the computation time given the functional form of expFun2?


Solution

  • Having @Oscar Benjamin's comments, I have updated the solution as follows.

    import sympy as sym
    
    X1, X2, a1, a2= sym.symbols('X1, X2, a1, a2')
    t,s,T,u=sym.symbols('t,s,T,u')
    fx= (X1*sym.exp(-a1*(T-u))+X2*sym.exp(-a2*(T-u))) **2
    fx=sym.expand(fx)    
    Fx=sym.integrate(fx,(u,t,s))
    
    ans=float(Fx.subs({X1:0.5, X2: 0.3, a1:2, a2:0.1, T:1.2, t:0, s:1}))