Search code examples
pythonscipysympyode

How to solve for an ordinary differential equation variable value using Python


I'm new to the SciPy.org maths libraries, so this may be a fairly basic question for those familiar with them.

For this ODE:

y'(t) - 0.05y(t) = d, y(0) = 10

how do I calculate the value of 'd' if y(10) = 100?

I can solve for y(t) this way:

import sympy as sym
y = sym.Function('y')
t, d = sym.symbols('t d')
y1 = sym.Derivative(y(t), t)
eqdiff = y1 - 0.05*y(t) - d
sol = sym.dsolve(eqdiff, y(t), ics={y(0): '10'})
sol

y(t)= −20.0d + (20.0d + 10.0)e^(0.05t)

Whether "sol" is usable to solve for d when y(10) = 100 is unknown to me (SymPy may not be the library of choice for this).

I've looked at numerous web pages such as these for ideas but haven't found a way forward:

https://docs.sympy.org/latest/modules/solvers/ode.html

Converting sympy expression to numpy expression before solving with fsolve( )

https://apmonitor.com/pdc/index.php/Main/SolveDifferentialEquations

I'm aware there are graphical ways to address the problem, but I want a numeric result.

Thanks in advance for helpful advice.


Solution

  • You can substitute the values and use solve:

    In [5]: sol.subs(t, 10)
    Out[5]: y(10) = 12.9744254140026⋅d + 16.4872127070013
    
    In [6]: sol.subs(t, 10).subs(y(10), 100)
    Out[6]: 100 = 12.9744254140026⋅d + 16.4872127070013
    
    In [7]: solve(sol.subs(t, 10).subs(y(10), 100), d)
    Out[7]: [6.43672337141557]
    

    https://docs.sympy.org/latest/modules/solvers/solvers.html#sympy.solvers.solvers.solve