c++ - 为什么 rk4.do_step 在 C++ 中不输出初始条件?
问题描述
如果我使用 rk4 步进器,我的输出值是正确的,除了我在结果中没有初始条件,就像我使用积分或积分常量选项一样,我会将初始条件作为我的输出的一部分。这与我的 for 循环有关吗?
样本:
int main(int argc, char** argv)
{
state_type x = { 0, 895.1170, 16000, 0 }; // initial conditions
double t = 0.0;
double t1 = 10;
double dt = 1;
size_t nSteps = 1000;
//integrate(odeFunc, x, t, t1, dt, my_observer);
runge_kutta4<state_type>rk4;
ofstream myfile("data.txt");
if (myfile.is_open()){
for (int i = 0; i < 19; ++i) {
t += dt;
rk4.do_step(odeFunc, x, t, dt);
myfile << t << " " << x[2] << endl;
}
}
}
结果:
1 16001
2 16005.4
3 16015
4 16032
5 16058.5
6 16096.5
7 16148.4
8 16216.4
.
.
.
但我想拥有
1 16000
2 16001
3 16005.4
解决方案
我使用Integrate_const 函数解决了我的问题,并且还有一个观察者函数。我使用了static ofstream 以便它保持我的文件打开并且不会在每次迭代中覆盖。
void my_observer(const state_type& x, const double t)
{
static ofstream data("data.txt");
data << t << " " << x[2] << std::endl;
}
int main(int argc, char** argv)
{
state_type x = { 0, 895.1170, 16000, 0 }; // initial conditions
double t = 0.0;
double t1 = 19;
double dt = 1;
integrate_const(runge_kutta4<state_type>(), odeFunc, x, t, t1, dt, my_observer);}
推荐阅读
- java - Restrict the number of occurrence of . (dot) to 1 in following regular expression
- java - 如何在 Tomcat / Eclipse 中仅部署我的静态内容?
- vue.js - 异步 Vue 生命周期
- javascript - 使用 jQuery 或 javascript,我想知道 html 表的每列(1-4)中有多少个元素 500?我该怎么做?
- sql - Oracle 完全联接中的重复项
- c++ - 如何确保从文件流式传输的数据中正确缩进。看看我的代码,它没有给出想要的结果
- scala - 运行 Scala 脚本时的 Main 对象是什么?
- docker - ASP.Net Core 5.0 Docker - windows/amd64 10.0.17134 没有匹配的清单
- javascript - 如何在不使用“__dirname”或“import.meta.url”的情况下获取 Node.js 中当前模块的目录?
- javascript - 如何从字符串变量cardLabel中删除除{Group}和{Desc}之外的所有内容并在javascript中在它们之间添加空格?