Gráfica de una función definida a trozos con sympy y spb

Uno de los problemas que no encontraba como resolver de forma fácil es el de representar una función definida a trozos con python. Ese fue el motivo de comenzar a trabajar con Sympy Plotting Backends’s. Con Geogebra es fácil hacerlas, pero mi idea era la de poder seguir usando solo sympy y su enorme potencial para la elaboración de actividades de matemáticas. Lo que se muestra en esta entrada es solo un ejemplo de cómo poder usar la función plot_piecewise de psb.

Para ello se crea una función definida a trozos del tipo:

\begin{equation*} f(x)=\begin{cases} \frac{32}{x^{2}} & \text{si}\:x<-4\\ 1 & \text{si}\:-4\leq x\leq-1\\ -\frac{3}{x-2} & \text{si}\:-1<x<2\\ \frac{x-4}{x-2} & \text{si}\:2\leq x<4\\ 2 & \text{si}\:x=4\\ \left(4-x\right)\left(x-8\right) & \text{si}\:x>4 \end{cases} \end{equation*}

y se obtiene una tabla de valores para ella, su gráfica, su derivada y su gráfica y su integral y su gráfica.

El código usado es:

\begin{sympycode}
#Para que pythontex ponga ln en vez de log
pytex.set_sympy_latex('text',ln_notation=True)
pytex.set_sympy_latex('display',ln_notation=True)

from spb import *
#Para hacer la tabla de valores
import pandas as pd
#Para modificar algunas cuestiones de los gráficos
import matplotlib.pyplot as plt
plt.rc('font', size=11)
plt.rc('text', usetex = True)
plt.rc('text.latex', preamble=r'\usepackage{amsmath}')
#Grosor líneas de la función
plt.rc('lines',linewidth=3)
plt.rcParams["yaxis.labellocation"]="top"
#Grosor de línea de la asíntota
plt.rc('contour',linewidth=1.5)
#Tamaño
plt.rcParams["figure.figsize"]=(5,5)

x,y=symbols('x y',real=True)

#Dominio para representar la función
xa=-9.5
xb=9.5
#Imagen
y0=-6
y1=10

#Funciones de la función a trozos
#Valores de ruptura del dominio
x1=-4
x2=-1
x3=2
x4=4
#Funciones
f1=(32/x**2,x<x1)
f2=(1,x<=x2)
f3=(-3/(x-x3),x<x3)
f4=((x-x4)/(x-x3),x<x4)
f5=(2,Eq(x,x4))
f6=(-(x-x4)*(x-(x4+3)-1),x>x4)

#Función a trozos
f=Piecewise(f1,f2,f3,f4,f5,f6)
#Derivada
df=Derivative(f,x).doit()
#Integral
intf=Integral(f,x)
intfc=Integral(f,x).doit()

#Gráficos
#Título del gráfico no lo pongo
#titulo=r"$f(x)=%s$" % latex(f)
#Representamos la función
func=plot_piecewise(f,(x,xa,xb),ylim=(y0,y1),aspect=(1,1), show=False,axis_center=(0,0))

#Representamos la asíntota vertical
avert=plot_implicit(x - x3, (x,xa,xb),(y,y0,y1),aspect=(1,1),show=False,axis_center=(0,0))
#"Juntamos" las dos gráficas
graf=(func+avert)
#Quitamos la leyenda
graf.legend=False
graf.save('piecewise.svg')

#Representamos la derivada de la función
dfunc=plot_piecewise(df,(x,xa,xb),ylim=(y0,y1),aspect=(1,1), ylabel="f'(x)" ,show=False,axis_center=(0,0))
dgraf=(dfunc+avert)
#Quitamos la leyenda
dgraf.legend=False
dgraf.save('dpiecewise.svg')

#Representamos la integral de la función
ifunc=plot_piecewise(intfc,(x,xa,xb),ylim=(0,2*y1),ylabel='${\displaystyle\int{f(x) dx}}$',aspect=(1,1), show=False,axis_center=(0,0))
igraf=(ifunc)
#Quitamos la leyenda
igraf.legend=False
igraf.save('ipiecewise.svg')

#Tabla de valores
#lista de valores
lista=[(i,f.subs(x,i)) for i in range(int(xa),int(xb))]
#funcion='$f(x)='+latex(f)+'$'
funcion='$f(x)$'
tabla=pd.DataFrame(lista,columns=['x',funcion])
tablaL=tabla.to_latex(index=False,escape = False,column_format='rr',caption="Tabla de valores",longtable=True).replace('zoo','')

\end{sympycode}

y se obtiene de resultado:

Función

\begin{equation*} f(x)=\begin{cases} \frac{32}{x^{2}} & \text{for}\:x<-4\\ 1 & \text{for}\:x\leq-1\\ -\frac{3}{x-2} & \text{for}\:x<2\\ \frac{x-4}{x-2} & \text{for}\:x<4\\ 2 & \text{for}\:x=4\\ \left(4-x\right)\left(x-8\right) & \text{for}\:x>4 \end{cases} \end{equation*}
Tabla de valores
x \(f(x)\)
-9 32/81
-8 1/2
-7 32/49
-6 8/9
-5 32/25
-4 1
-3 1
-2 1
-1 1
0 3/2
1 3
2  
3 -1
4 2
5 3
6 4
7 3
8 0

image

Derivada

\begin{equation*} f'(x)=\begin{cases} -\frac{64}{x^{3}} & \text{for}\:x<-4\\ 0 & \text{for}\:x\leq-1\\ \frac{3}{\left(x-2\right)^{2}} & \text{for}\:x<2\\ -\frac{x-4}{\left(x-2\right)^{2}}+\frac{1}{x-2} & \text{for}\:x<4\\ 0 & \text{for}\:x=4\\ 12-2x & \text{for}\:x>4 \end{cases} \end{equation*}

image1

Integral

\begin{equation*} \int f(x)\,{\textstyle dx}=\begin{cases} -\frac{32}{x} & \text{for}\:x<-4\\ x+12 & \text{for}\:x\leq-1\\ -3\ln{\left(x-2\right)}+3\ln{\left(3\right)}+11+3i\pi & \text{for}\:x<2\\ x-2\ln{\left(x-2\right)} & \text{for}\:x<4\\ -\frac{x^{3}}{3}+6x^{2}-32x-2\ln{\left(2\right)}+\frac{172}{3} & \text{otherwise} \end{cases} \end{equation*}

image2

Fichero fuente y el pdf final de una posible compilación.