Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sympy: integrate() strange output

Tags:

python

sympy

I'm just learning how to use sympy and I have tried a simple integration of a sin function. When the argument of sin() has a constant phase constant the output of integrate() gives the same value whatever is the phase: 0

from sympy import *
w = 0.01
phi = 0.3
k1 = integrate(sin(w*x), (x, 0.0, 10.0))
k2 = integrate(sin(w*x + 0.13), (x, 0.0, 10.0))
k3 = integrate(sin(w*x + phi),(x, 0.0, 10.0))
k1, k2, k3

(0.499583472197429, 0, 0)

Can somebody explain me why ?

like image 440
user1259970 Avatar asked Jan 17 '16 20:01

user1259970


1 Answers

That seems to be a bug. A workaround solution could be to get a symbolic expression of your integral first (which seems to work fine), then evaluate it for each set of parameters at the upper and lower bound and calculate the difference:

import sympy as sp
x, w, phi = sp.symbols('x w phi')

# integrate function symbolically
func = sp.integrate(sp.sin(w * x  + phi), x)

# define your parameters
para = [{'w': 0.01, 'phi': 0., 'lb': 0., 'ub': 10., 'res': 0.},
        {'w': 0.01, 'phi': 0.13, 'lb': 0., 'ub': 10., 'res': 0.},
        {'w': 0.01, 'phi': 0.3, 'lb': 0., 'ub': 10., 'res': 0.}]

# evaluate your function for all parameters using the function subs
for parai in para:
    parai['res'] = func.subs({w: parai['w'], phi: parai['phi'], x: parai['ub']})
    -func.subs({w: parai['w'], phi: parai['phi'], x: parai['lb']})

After this, para looks then as follows:

[{'lb': 0.0, 'phi': 0.0, 'res': 0.499583472197429, 'ub': 10.0, 'w': 0.01},
 {'lb': 0.0, 'phi': 0.13, 'res': 1.78954987094131, 'ub': 10.0, 'w': 0.01},
 {'lb': 0.0, 'phi': 0.3, 'res': 3.42754951227208, 'ub': 10.0, 'w': 0.01}]

which seems to give reasonable results for the integration which are stored in res

like image 169
Cleb Avatar answered Sep 21 '22 22:09

Cleb