蟒:当一个条件被满足
问题描述:
我使用odeint函数从scipy.integrate包中断odeint:蟒:当一个条件被满足
r0 = np.array([1,2,3,4])
t=np.linspace(0,1,20)
def drdt(r,t):
return r # or whatever else
r = odeint(drdt,r0,t)
R0是包含一定数量的点的初始位置的numpy的阵列。 在脚本结尾处,如预期的那样,我得到了20步时间点的位置。
现在我想在满足r条件时停止odeint求解器。特别是我想在这些点中的2个点比某个阈值更接近时停止odeint,对r向量进行一些更改,然后继续使用新的初始位置进行odeint求解。 有没有一种方法来实现这一点?
我一直在想的一个可能的解决方案是运行odeint到最后,然后检查是否满足条件,但这当然不是很有效。
谢谢大家的帮助下, 尼古拉
答
我对C++的答案。这可能不是发布它的最佳地点,但它可能仍然是有趣的。 (我没有找到一个更好的地方放置它,这是我在寻找C++解决方案时着陆的地方)。
下面是一个C++示例,当变量的值等于或低于零时停止集成。
#include <iostream>
#include <boost/range/algorithm.hpp>
#include <boost/numeric/odeint.hpp>
using namespace std;
using namespace boost::numeric::odeint;
typedef double state_type;
typedef runge_kutta_cash_karp54<state_type> error_stepper_type;
class Myode{
public:
void operator()(const state_type& x, state_type& dxdt, const double t){dxdt=-1-x;}
static bool done(const state_type &x){return x<=0.0;}
};
int main(int argc, char* argv[]){
Myode ode;
state_type x=10.0;
auto stepper = make_controlled<error_stepper_type>(1.0e-10 , 1.0e-6);
auto iter= boost::find_if(make_adaptive_range(stepper,ode,x, 0.0 , 20.0 , 0.01),
Myode::done);
cout<<"integration stopped at"<<x<<endl;
return 1;
}
积分在第一次达到值x小于或等于零时停止(请参阅done函数)。因此,根据您当前的步长大小,它可能远远低于零。
请注意,这使用C++ 11结构,所以你需要在你的编译器上启用它。在我的情况下(gcc 4.4),它是通过向编译命令添加-std = gnu ++ 0x来实现的。