define diferential equation in python

To define a differential equation in Python, one can use the 'scipy.integrate' module. To illustrate this, let's define a simple differential equation:

main.py
y' = -2y
9 chars
2 lines

Here, y' represents the derivative of function y with respect to its independent variable (usually denoted as t). To solve this equation, we need to define a function that returns the derivative of y for a given value of y and t. In Python, we can define such a function as follows:

main.py
import numpy as np
from scipy.integrate import odeint

def dy_dt(y, t):
  # returns the derivative of y for a given value of y and t
  return -2 * y

# initial condition
y0 = 1

# 10 time points between 0 and 2
t = np.linspace(0, 2, 10)

# solve the differential equation
y = odeint(dy_dt, y0, t)

# print the solution
print(y)
328 chars
19 lines

In this code, we first import the necessary modules, numpy and scipy.integrate. We then define our function dy_dt which returns the derivative of y for a given value of y and t. We then define an initial condition y0 and a set of t values between 0 and 2. Finally, we solve the differential equation using odeint function in scipy, which returns the solution at each time point.

The output of this code is an array of values of y at each time point. By plotting these values against the corresponding t values, we can visualize the solution of the differential equation.

gistlibby LogSnag