Can Riemann sum rectangles be plotted with Python 3?

I already plotted the graph of the equation x * * 2 with Jupyter with the Code:

from sympy.plotting import plot
from sympy.abc import x
eq=x**2
plot(eq,(x,-2,2),ylim=(-1,2),line_color="g")

That gives us the image:

enter the description of the image here

But it is also necessary to draw rectangles that approximate the area as Riemann sums in an interval of the X-axis, for example [0,1], something like this:

funcion_graficada

Does anyone know if it can be done with Python 3?

 5
Author: Robby, 2016-10-16

1 answers

Of course you can, with Python the sky is the limit... XD.

Jokes aside, you don't specify which Riemann sum you want to apply (right, left, maximum, minimum). I'm going to use the left sum according to your example:

For the graph I use matplotlib and NumPy for arrays:

import numpy as np
import matplotlib.pyplot as plt


def riemannplot(f, a, b, ra, rb, n):
    # f es la función 
    # a y b son los limites del eje x para graficar la funcion f
    # ra y rb son los limites del intervalo en el eje x del que queremos calcular la suma
    # n es el numero de rectangulos que calcularemos

    atenuacion = (b-a)/100
    x = np.arange(a, b+atenuacion, atenuacion)
    plt.plot(x, f(x), color='green')

    delta_x = (rb-ra)/n
    riemannx = np.arange(ra, rb, delta_x)
    riemanny = f(riemannx)
    riemann_sum = sum(riemanny*delta_x)

    plt.bar(riemannx,riemanny,width=delta_x,alpha=0.5,facecolor='orange')
    plt.xlabel('x')
    plt.ylabel('f(x)')
    plt.title('Suma izquierda de Riemann para f(x)')
    plt.figtext(0.1,0.02, "Suma de Riemann: " + str(riemann_sum), color='r')
    plt.show()



def f(x):
    return x**2

riemannplot(f, 0, 1.1, 0, 1, 10)

I don't know if you have to do it with SymPy necessarily or not. However, the basic idea is the same use the method you use to plot:

Dividir divide the interval In n equal parts, obtaining the values of x that separate each rectangle.

❷ for each triangle calculate its height, for which it is enough to pass each value of x obtained before to the function.

❸ now it remains only to plot the histogram using the heights and width of each bar which is the increment of x (length of interval/n)

The graph that creates us is this:

enter the description of the image here

If you don't want to use an auxiliary function you can pass your function as a string to riemannplot() using SymPy to do this:

import numpy as np
import matplotlib.pyplot as plt
from sympy import S, symbols
from sympy.utilities.lambdify import lambdify


def riemannplot(f, a, b, ra, rb, n):
    x = symbols('x')
    f = lambdify(x, S(f),'numpy')

    atenuacion = (b-a)/100
    xs = np.arange(a, b+atenuacion, atenuacion)
    plt.plot(xs, f(xs), color='green')

    delta_x = (rb-ra)/n
    riemannx = np.arange(ra, rb, delta_x)
    riemanny = f(riemannx)
    riemann_sum = sum(riemanny*delta_x)

    plt.bar(riemannx,riemanny,width=delta_x,alpha=0.5,facecolor='orange')
    plt.xlabel('x')
    plt.ylabel('f(x)')
    plt.title('Suma izquierda de Riemann para f(x)')
    plt.figtext(0.1,0.02, "Suma de Riemann: " + str(riemann_sum), color='r')
    plt.show()

Now you can call riemannplot() like this:

riemannplot('x**2', 0, 1.1, 0, 1, 10)
 6
Author: FJSevilla, 2016-10-16 19:30:41