Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integration with sympy

I'm trying to perform the following integration using sympy;

x = Symbol('x')
expr = (x+3)**5
integrate(expr)

The answer that I'm expecting is:

enter image description here

But what's being returned is:

enter image description here

The following code works in MATLAB:

syms x
y = (x+3)^5;
int(y)

I'm unsure what I'm doing wrong in order to perform this using sympy.

like image 591
baxx Avatar asked Mar 15 '23 01:03

baxx


1 Answers

This is actually a common problem seen in Calculus where for these kinds of polynomial expressions, you do get two answers. The coefficients for each of the powers of x exist but the constant factor is missing between them.

As such, there are two methods you can use to find the indefinite integral of this expression.

  1. The first method is to perform a substitution where u = x+3, then integrate with respect to u. Then, the indefinite integral would be (1/6)*(x + 3)^6 + C as you expect.

  2. The second method is to fully expand out the polynomial and integrate each term individually.


MATLAB elects to find the integral the first way:

>> syms x;
>> out = int((x+3)^5)

out =

(x + 3)^6/6

Something to note for later is that if we expand out this polynomial expression, we get:

>> expand(out)

ans =

x^6/6 + 3*x^5 + (45*x^4)/2 + 90*x^3 + (405*x^2)/2 + 243*x + 243/2

sympy elects to find the integral the second way:

In [20]: from sympy import *

In [21]: x = sym.Symbol('x')

In [22]: expr = (x+3)**5

In [23]: integrate(expr)
Out[23]: x**6/6 + 3*x**5 + 45*x**4/2 + 90*x**3 + 405*x**2/2 + 243*x

You'll notice that the answer is the same between both environments, but the constant factor is missing. Because the constant factor is missing, there is no neat way to factor this into the neat polynomial that you are expecting from your output seen in MATLAB.

As a final note, if you would like to reproduce what sympy generates, expand out the polynomial, then integrate. We get what sympy generates:

>> syms x;
>> out = expand((x+3)^5)

out =

x^5 + 15*x^4 + 90*x^3 + 270*x^2 + 405*x + 243

>> int(out)

ans =

x^6/6 + 3*x^5 + (45*x^4)/2 + 90*x^3 + (405*x^2)/2 + 243*x

The constant factor though shouldn't worry you. In the end, what you are mostly concerned with is a definite integral, and so the subtraction of these constant factors will happen, which won't affect the final result.


Side Note

Thanks to DSM, if you specify the manual=True flag for integrate, this will attempt to mimic performing integration by hand, which will give you the answer you're expecting:

In [26]: from sympy import *

In [27]: x = sym.Symbol('x')

In [28]: expr = (x+3)**5

In [29]: integrate(expr, manual=True)
Out[29]: (x + 3)**6/6
like image 65
rayryeng Avatar answered Mar 21 '23 08:03

rayryeng