Having Trouble While Using Scipy.integrate.odeint With Python
I was trying to use odeint to solve a problem. My code is as below: import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint eta=1.24e-9/2 def fun(x):
Solution 1:
There are several problems with your code, most of which you might be able to solve yourself if you read the docstring for odeint
more carefully.
To get you started, the following is a simple example of solving a scalar differential equation with odeint
. Instead of trying to understand (and possibly debug) your function, I'll use a very simple equation. I'll solve the equation dy/dt = a * y, with initial condition y(0) = 100. Once you have this example working, you can modify fun
to solve your problem.
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
deffun(y, t, a):
"""Define the right-hand side of equation dy/dt = a*y"""
f = a * y
return f
# Initial condition
y0 = 100.0# Times at which the solution is to be computed.
t = np.linspace(0, 1, 51)
# Parameter value to use in `fun`.
a = -2.5# Solve the equation.
y = odeint(fun, y0, t, args=(a,))
# Plot the solution. `odeint` is generally used to solve a system# of equations, so it returns an array with shape (len(t), len(y0)).# In this case, len(y0) is 1, so y[:,0] gives us the solution.
plt.plot(t, y[:,0])
plt.xlabel('t')
plt.ylabel('y')
plt.show()
Here's the plot:
More complicated examples of the use of odeint
can be found in the SciPy Cookbook (scroll down to the bullet labeled "Ordinary differential equations").
Post a Comment for "Having Trouble While Using Scipy.integrate.odeint With Python"