Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sympy unable to take simple integral

I'm trying to take the following integral using sympy and it won't take it:

>>> from sympy import *
>>> integrate(x*exp(-(x-x0)**2), (x, 0, k))

If I 'help' it by adding and subtracting the same expression, it works fine:

>>> sp.integrate((x-x0)*sp.exp(-(x-x0)**2)+x0*sp.exp(-(x-x0)**2), (x, 0, k))

Is there any way to automate this process?

Wolfram Alpha takes it easily without any hints from user's side: enter image description here

like image 547
Antony Hatchkins Avatar asked Oct 23 '25 03:10

Antony Hatchkins


1 Answers

You might suspect a change of variables will help by removing the complicated parts from the exponent:

from sympy import *
var('x y x0 k')
i=Integral(x*exp(-(x-x0)**2), (x, 0, k))
>>> i.transform(x-x0,y).doit()
sqrt(pi)*x0*erf(x0)/2 + sqrt(pi)*x0*erf(k - x0)/2 - exp(-(k - x0)**2)/2 + exp(-x0**2)/2

How to automate? You can look for functions/exp that have more free variables than the variable of integration

>>> [a.args[0] for a in i.atoms(exp) if a.args[0].free_symbols - {x}]
[-(x - x0)**2]

Notes on Integral.transform indicate:

    The mappings, F(x) or f(u), must lead to a unique integral. Linear
    or rational linear expression, ``2*x``, ``1/x`` and ``sqrt(x)``, will
    always work; quadratic expressions like ``x**2 - 1`` are acceptable
    as long as the resulting integrand does not depend on the sign of
    the solutions (see examples).

In this case you have a linear transform and all is well.

like image 159
smichr Avatar answered Oct 27 '25 01:10

smichr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!