Search code examples
pythonsympyderivative

How to find derivative in Python using SymPy


I want to find derivative of a certain function inputted by the user.

x = np.linspace(-5,5)

print('Options are:')
print('1. y = x')
print('2. y = ax^2')
print('3. y = k(x-a)(x-b)')
print('4. y = k(x-a)(x-b)(x-c)')

n = int(input('Your option is: '))

if n == 1:
    func = x
    plt.plot(x,func)
    n = input('Do you wanna find its derivative? (Y/N)')
    if n == 'Y':
        print('Derivative is 1')
    else:
        print('Done')

elif n == 2:
    a = int(input('Enter a value for a: '))
    func = a*x**2
    plt.plot(x,func)
    n = input('Do you wanna find its derivative? (Y/N)')
    if n == 'Y':
        x = sp.Symbol('x')
        print(sp.diff(func,x))
    else:
        print('Done')

When n == 2, i will need the user to input the 'a' value for the ax^2 function. The code will then plot the graph ax^2. Then proceeds to ask whether the user wants the derivative of the function. In this part I'm confused because with the syntax i used above, it doesnt show the derivative, but it instead shows a list of 0s like below.

1. y = x
2. y = ax^2
3. y = k(x-a)(x-b)
4. y = k(x-a)(x-b)(x-c)
Your option is: 2
Enter a value for a: 3
Do you wanna find its derivative? (Y/N)Y
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

How do i fix this problem?


Solution

  • You will need to define the Symbol x before defining the function func. For plotting you can use SymPy's plotting modules. Below is a possible solution.

    import sympy as sp
    import numpy as np
    from sympy.plotting import plot
    
    x = sp.Symbol('x')
    
    print('Options are:')
    print('1. y = x')
    print('2. y = ax^2')
    print('3. y = k(x-a)(x-b)')
    print('4. y = k(x-a)(x-b)(x-c)')
    
    n = int(input('Your option is: '))
    
    if n == 1:
        func = x
        plot(func)
    
        n = input('Do you wanna find its derivative? (Y/N)')
        if n == 'Y':
            print('Derivative is 1')
        else:
            print('Done')
    
    elif n == 2:
        a = int(input('Enter a value for a: '))
        func = a*x**2
        plot(func)
        n = input('Do you wanna find its derivative? (Y/N)')
        if n == 'Y':
            print(sp.diff(func,x))
        else:
            print('Done')