ODEINT输出到txt文件而不是控制台

时间:2015-12-23 03:11:03

标签: c++ differential-equations numerical-integration odeint

有没有办法将此示例的t和x的输出写入txt文件而不是控制台。谢谢!

这是我从Odeint网站复制的例子。

#include <iostream>
#include <boost/numeric/odeint.hpp>


using namespace std;
using namespace boost::numeric::odeint;


/* we solve the simple ODE x' = 3/(2t^2) + x/(2t)
 * with initial condition x(1) = 0.
 * Analytic solution is x(t) = sqrt(t) - 1/t
 */

void rhs( const double x , double &dxdt , const double t )
{
    dxdt = 3.0/(2.0*t*t) + x/(2.0*t);
}

void write_cout( const double &x , const double t )
{
    cout << t << '\t' << x << endl;
}

// state_type = double
typedef runge_kutta_dopri5< double > stepper_type;

int main()
{
    double x = 0.0;    
    integrate_adaptive( make_controlled( 1E-12 , 1E-12 , stepper_type() ) ,
                        rhs , x , 1.0 , 10.0 , 0.1 , write_cout );
}

2 个答案:

答案 0 :(得分:2)

您只需将此示例的输出通过管道传输到文本文件

即可
$ ./lorenz > data.txt

否则,您可以使用C ++ ofstreams将输出直接写入文件,例如在那里描述:http://www.cplusplus.com/doc/tutorial/files/

答案 1 :(得分:1)

将cout替换为ofstream的对象。

#include <iostream>
#include <fstream>
#include <boost/numeric/odeint.hpp>


using namespace std;
using namespace boost::numeric::odeint;

ofstream data("data.txt");
/* we solve the simple ODE x' = 3/(2t^2) + x/(2t)
* with initial condition x(1) = 0.
* Analytic solution is x(t) = sqrt(t) - 1/t
*/



void rhs(const double x, double &dxdt, const double t)
{
    dxdt = 3.0 / (2.0*t*t) + x / (2.0*t);
}

void write_cout(const double &x, const double t)
{
    data << t << '\t' << x << endl;
}

// state_type = double
typedef runge_kutta_dopri5< double > stepper_type;

int main()
{
    double x = 0.0;
    integrate_adaptive(make_controlled(1E-12, 1E-12, stepper_type()),
        rhs, x, 1.0, 10.0, 0.1, write_cout);
}
相关问题