In [1]:
import sympy as sym
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from IPython.display import display,Math

$\int_a^b f(x) \: dx$

$\int_a^b [f(x) - 0] \: dx$

$\int_a^b [f(x) - g(x)] \: dx$

In [2]:
x = sym.symbols('x')

symf = x**2
symg = x

f = sym.lambdify(x,symf)
g = sym.lambdify(x,symg)

xx = np.linspace(-2,2,55)

# add patch
xpatch = np.linspace(0,1,100)
ypatch = np.vstack((g(xpatch),f(xpatch))).T
# print(ypatch)

fig,ax = plt.subplots()
ax.add_patch(Polygon(ypatch,facecolor='k',alpha=.3))

plt.plot(xx,f(xx))
plt.plot(xx,g(xx),'r')

plt.legend(['$f(x)=%s$'%sym.latex(symf), '$g(x)=%s$'%sym.latex(symg)])
plt.axis([-.25,1.25,-.5,1.5])
plt.show()

Computing the area between two functions

The area between two functions is given by the formula $A = \int_{a}^{b}f(x)-g(x) dx$

In our example, $f(x)=x^2$ and $g(x)=x$

Therefore, $A = \int_{a}^{b}(x^2-x)dx$

We will compute the area between the two crossing points, that is, where the two functions are equal. This is given by the two solutions to the equation $$x^2=x$$

The two solutions are $x=0$ and $x=1$. This gives the definite integral of $$A = \int_{0}^{1}(x^2-x)dx$$

In [3]:
x = sym.symbols('x')

symf = x**2
symg = x

fg_intersect = sym.solve(symf-symg)
print(fg_intersect)

# compute the are
A = sym.integrate(symf-symg,(x,fg_intersect[0],fg_intersect[1]))
print(A)

display(Math('f(x)\\text{ and } g(x)\\text{ intersect at } x=%g \\text{ and } %g' %(fg_intersect[0],fg_intersect[1])))
display(Math('\\text{The area between these functions is } %s' %A))
[0, 1]
-1/6
$\displaystyle f(x)\text{ and } g(x)\text{ intersect at } x=0 \text{ and } 1$
$\displaystyle \text{The area between these functions is } -1/6$