Using Sympy for Analytical Maths

This is an example of how i would use sympy to evaluate a set of analytical questions, for example:

Find \(\forall a \in [0,12,24,30,99]\) and \(b=100\):

Where \(\alpha = 2.341\), \(\beta = e^x\)

First we need to import the library (and start the printing for nice easy to read stuff):

import sympy as sp

Now create the eqn above so we can evaluate it

a, b, alpha, beta, x = sp.symbols('a b \\alpha \\beta x')
expr = (alpha*x**3 - sp.sin(2*x)) * (1/sp.sqrt(beta*sp.E**x))

This like the integrand we hav above. Now theres a few things we can do, if we know \(\alpha\) and \(\beta\), which we do, we can sub them in. then we will have a more simple expression:

expr2 = expr.subs({alpha: 2.341, beta:sp.E**x})

If we wanted we could now evaluate this using the .subs() command again (this time with a value for x such as .subs(x,3)), but we’re asked to evalue the integral:

integral = sp.integrate(expr2, (x,a,b))

Now we need to calculate all the values of this expression for every combination of \(a \in [0,12,24,30,99]\) and \(b=100\). We can do this by starting with lambdifying the expression into a callable function:

my_callable = sp.lambdify((a, b), integral)
my_callable(1,2) # this will sub in a=1 and b=2 to the above.

Now we just loop over the varable s for a and we can print out the values:

for a in [0,12,24,30,99]:
    print("a =",a)
a = 0

a = 12

a = 24

a = 30

a = 99

This decreasing sequence is expected as were taking essentially taking area slices of the below plot, moving further left each time as a starting point.

%matplotlib inline
import matplotlib.pyplot as plt
X = [x for x in range(0,101)]
expr2_callable = sp.lambdify(x, expr2)
plt.plot(X,[expr2_callable(x) for in_x in X])
[<matplotlib.lines.Line2D at 0x24a166e8668>]


And we’re done!