pythonplotjupyter-notebooksympydifferentiation

How is it possible to define a equation, differentiate and plot it, using Sympy in Jupyter Nootebook?


In Jupyter Notebook i would like to define a equation, differentiate and plot the equation.

import sympy as sp
from IPython.display import display
sp.init_printing()
import matplotlib.pyplot as plt
import numpy as np

x = sp.symbols('x')

def func(x):
    a= sp.sympify("4/5")
    return (x**3+a*x**2)
display(func(x))

def dfunc(x):
    a = sp.diff(func(x),x)
    return a
display(dfunc(x))


x = np.linspace(-10,10,20)


plt.plot(x,func(x))
plt.plot(x,dfunc(x))      # doesn't work

display(dfunc(x)) shows the wanted function but plt.plot(x,dfunc(x)) returns the error message ValueError: cannot derive by this array

Does anyone know how to get the plot?

(It also doesn't work with sp.integrate(func(x),x) instead of sp.diff(func(x),x). Just another error message is returned ValueError: Invalid limits given: ...)

Many thanks in advance.

Matthias


Solution

  • You can use the SymPy plot function rather than the matplotlib one. The matplotlib plot function expects arrays as inputs whereas the sympy one accepts sympy expressions (and then calculates values to make the arrays for matplotlib):

    In [36]: import sympy as sym
    
    In [37]: a = sym.Rational(4, 5)
    
    In [38]: x = sym.Symbol('x')
    
    In [39]: f = x**3 + a*x**2
    
    In [40]: f
    Out[40]: 
            2
     3   4⋅x 
    x  + ────
          5  
    
    In [41]: f.diff(x)
    Out[41]: 
       2   8⋅x
    3⋅x  + ───
            5 
    
    In [42]: sym.plot(f.diff(x))