Search code examples
pythonsympydifferential-equations

Substituting the expression of a lower order derivative in the expression for the higher order derivative


I have the following differential equation:

dy/dx = sin(x+y)/x

I'm trying to find the second derivative of y with respect to x. The expected result is as follows:

second derivative of y wrt x

I'm trying to use sympy to give me the above expression. This is what I've tried:

from sympy import *

x = symbols('x')
y = Function('y')


#initial value condition: y(1) = 0.5

# first derivative represented as d1 

d1 = sin(x+y(x))/x

# second derivative represented as d2

d2 = diff(d1,x)

The result for d2 is:

d2

This is where I'm stuck; how do I substitute the (d/dx)(y(x)) term with the expression d1?

Thank you for your help.


Solution

  • You can use subs to substitute for the derivative:

    In [13]: d1.diff(x).subs(y(x).diff(x), d1)
    Out[13]: 
    ⎛    sin(x + y(x))⎞                              
    ⎜1 + ─────────────⎟⋅cos(x + y(x))                
    ⎝          x      ⎠                 sin(x + y(x))
    ───────────────────────────────── - ─────────────
                    x                          2     
                                              x