Having trouble while using scipy.integrate.odeint

2020-02-11 11:20发布

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):
    f=1.05e-8*eta*x**(1.5)*np.exp(13.6/x)
    return (np.sqrt(1.+4*f)-1)/2./f
x=np.arange(0,1,0.001)
y=odeint(fun,x,0)[0]
plt.plot(x,y)
plt.plot(x,x)
plt.show()

It the two curves are the same, which is obviously wrong. If I plot the function, it will looks like a step function, which is very very small before about 0.3 and exponentially goes to 1. Can you help me figure out what's wrong with it? Thank you!

标签: python scipy
1条回答
The star\"
2楼-- · 2020-02-11 12:05

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


def fun(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:

plot generated by the example

More complicated examples of the use of odeint can be found in the SciPy Cookbook (scroll down to the bullet labeled "Ordinary differential equations").

查看更多
登录 后发表回答