gpt4 book ai didi

c++ - ofstream Odeint输出到txt文件

转载 作者:行者123 更新时间:2023-11-28 05:50:08 39 4
gpt4 key购买 nike

我尝试从 ODEINT 库运行这个示例来求解 ODE。它运行良好,但我不想将结果输出到屏幕上,而是想将它们写入文件。我将这个 ofstream 添加到 write_cout 函数下的代码中,但它只将最后一行结果写入文件而不是全部。你有什么想法吗?谢谢

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

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


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;
cout<<"alo"<<endl;

ofstream buckyFile ("tuna.txt");
buckyFile<<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 );
}

最佳答案

甚至更好

struct stream_writer
{
std::ostream& m_out;
stream_writer( std::ostream& out ) : m_out( out ) {}
void operator()( const double &x , const double t )
{
m_out << t << "\t" << x << "\n";
}
};

int main()
{
double x = 0.0;
ofstream fout( "tuna.txt" );
integrate_adaptive( make_controlled( 1E-12 , 1E-12 , stepper_type() ) ,
rhs , x , 1.0 , 10.0 , 0.1 , stream_writer( fout ) );
}

关于c++ - ofstream Odeint输出到txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35425102/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com