所以我正在尝试制作一个程序来为第二顺序ODE做4阶Runge-Kutta。我的for循环中存在一个问题。 v和x的值不会从初始值改变,我不确定如何修复它。
double dv (double v, double x)
{
double r = -4/5*v-x;
return r;
}
double dx (double v)
{
return v;
}
int main()
{
double kx1, kx2, kx3, kx4;
double kv1, kv2, kv3, kv4;
double tf = 10;
int n;
double h;
cout << "Number of iterations: ";
cin >> n;
// Create two vectors to store the iteration values
vector<double> x;
vector<double> v;
vector<double> t;
// Initialize the vectors
x.push_back(0.3);
v.push_back(0);
t.push_back(0);
h = tf/n;
for(int i=0; i<n; i++)
{
// Establish all the k values
kx1 = dx(v[i]);
kv1 = dv(x[i],v[i]);
kx2 = dx(v[i]+h/2*kx1);
kv2 = dv(x[i]+h/2*kx1,v[i]+h/2*kv1);
kx3 = dx(v[i]+h/2*kx2);
kv3 = dv(x[i]+h/2*kx2,v[i]+h/2*kv2);
kx4 = dx(v[i]+h*kx3);
kv4 = dv(x[i]+h*kx3,v[i]+h*kv3);
double fx = x[i] + h/6*(kx1+2*kx1+2*kx3+kx4);
double fv = v[i] + h/6*(kv1+2*kv1+2*kv3+kv4);
x.push_back(fx);
v.push_back(fv);
}
system("pause");
return 0;
}
答案 0 :(得分:3)
你的错误在于功能dv。 4/5执行整数除法,结果为0.更改
double dv (double v, double x)
{
double r = -4/5*v-x;
return r;
}
到
double dv (double v, double x)
{
double r = (-4.0/5.0)*v-x;
return r;
}