0

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

M_Mueller
  • 3
  • 1
  • if you don't need analytic results, drop sympy and use numerics only. – anon01 Sep 17 '21 at 22:45
  • unfortunately i need the analytic results for further calulations. – M_Mueller Sep 17 '21 at 22:50
  • Careful. You first define `x` as a symbol. But then redefine it as a numpy array. `func` and `dfunc` should work with the symbol - test that. But I don't expect them to work with the array. Until you know what you are doing, don't mix sympy with numpy/scipy/matplotlib. Eventually you can use `sympy.lambdify`, but for now stick with sympy. – hpaulj Sep 17 '21 at 22:59
  • I just tried lambdify and it also works. Thank you. – M_Mueller Sep 20 '21 at 06:11

1 Answers1

0

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))
Oscar Benjamin
  • 12,649
  • 1
  • 12
  • 14