gpt4 book ai didi

c++ - Runge-Kutta 四阶积分器出错

转载 作者:太空宇宙 更新时间:2023-11-04 11:41:25 25 4
gpt4 key购买 nike

我一直在研究四阶龙格-库塔求解器,但遇到了一些困难。我已经根据文章 on gafferongames 编写了求解器,但是当我运行一个包含的小例子时,我得到的错误比我用简单的欧拉积分得到的错误要糟糕得多,即使是简单的重力。我已将它整理成一个独立的示例(约 60 行代码,包括打印),但它需要 GLM 才能运行。
它完整​​地显示了我的问题。第 55 行打印出解析解和 RK4 解之间的差异。这应该是相对较小的,但即使在它走了 10 多步之后它也会爆炸。

#include <iostream>
#include <glm/glm.hpp>
struct State{
glm::vec3 position, velocity;
};
class Particle{
public:
glm::vec3 position, velocity, force;
float mass;

void solve(float dt);
glm::vec3 acceleration() const {return force/mass;}
State evalDerivative(float dt, const State& curr);
void analytic(float t, glm::vec3 a);
};
int main(int argc, char* argv[]){
Particle p;
p.position = glm::vec3(0.f);
p.mass = 1.0f;
for(int i = 1; i <= 10; i++) {
p.force = glm::vec3(0.f, -9.81f, 0.f);
p.solve(.016f);
p.analytic(i*.016f, glm::vec3(0.f, -9.81f, 0.f));
}
getchar();
return 0;
}
void Particle::solve(float dt){
State t;t.position = glm::vec3(0.f); t.velocity = glm::vec3(0.f);
State k1 = evalDerivative(0, t);
State k2 = evalDerivative(dt*.5f, k1);
State k3 = evalDerivative(dt*.5f, k2);
State k4 = evalDerivative(dt, k3);

position += (k1.position + 2.f*(k2.position + k3.position) + k4.position)/6.f;
velocity += (k1.velocity + 2.f*(k2.velocity + k3.velocity) + k4.velocity)/6.f;
force = glm::vec3(0.f);
}
State Particle::evalDerivative(float dt, const State& curr){
State s;
s.position = position + curr.position*dt;
s.velocity = velocity + curr.velocity*dt;

s.position = s.velocity;
s.velocity = acceleration();
return s;
}
void Particle::analytic(float t, glm::vec3 a){
glm::vec3 tPos = glm::vec3(0.f) + 0.5f*a*t*t;
glm::vec3 tVel = glm::vec3(0.f) + a*t;

glm::vec3 posdiff = tPos - position;
glm::vec3 veldiff = tVel - velocity;
std::cout << "POSITION: " << posdiff.x << ' ' << posdiff.y << ' ' << posdiff.z << std::endl;
std::cout << "VELOCITY: " << veldiff.x << ' ' << veldiff.y << ' ' << veldiff.z << std::endl << std::endl;
}

如果有人能帮我解决这个问题,我已经束手无策了。

最佳答案

好吧,我觉得自己很蠢。我已经为此工作了几个小时,但我错过了一小步:

position += (k1.position + 2.f*(k2.position + k3.position) + k4.position)/6.f;
velocity += (k1.velocity + 2.f*(k2.velocity + k3.velocity) + k4.velocity)/6.f;

应该是

position += (k1.position + 2.f*(k2.position + k3.position) + k4.position)*dt/6.f;
velocity += (k1.velocity + 2.f*(k2.velocity + k3.velocity) + k4.velocity)*dt/6.f;

关于c++ - Runge-Kutta 四阶积分器出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21246781/

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