将 scipy.integrate.odeint 与 python 一起使用时遇到问题 [英] Having trouble while using scipy.integrate.odeint with python

查看:51
本文介绍了将 scipy.integrate.odeint 与 python 一起使用时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用 odeint 来解决问题.我的代码如下:

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()

如果两条曲线是一样的,这显然是错误的.如果我绘制该函数,它将看起来像一个阶跃函数,它在大约 0.3 之前非常非常小并且以指数方式变为 1.你能帮我弄清楚它有什么问题吗?谢谢!

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!

推荐答案

您的代码有几个问题,如果您阅读 odeint 的文档字符串更仔细.

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.

为了帮助您入门,以下是一个使用 odeint 求解标量微分方程的简单示例.我将使用一个非常简单的公式,而不是试图理解(并可能调试)您的函数.我将求解方程 dy/dt = a * y,初始条件为 y(0) = 100.一旦你让这个例子工作,你可以修改 fun 来解决你的问题.

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()

情节如下:

更复杂的 odeint 使用示例可以在 SciPy Cookbook(向下滚动到标有常微分方程"的项目符号).

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

这篇关于将 scipy.integrate.odeint 与 python 一起使用时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆