使用 C++ 求解二阶 ODE 的 Runge-Kutta 四阶

Runge-Kutta 4th order to solve 2nd order ODE using C++

我尝试编写代码来求解二阶 ODE,但不知何故它没有按我的预期工作。

等式是 2y" + 5y' +3y = 0 ,y(0) = 3 和 y'(0) = -4

最终答案将是 y(x) = 3-4x << 编辑这是错误的

因此 y(1) = -1 且 y'(1) = -4

但程序输出是 y(1) = 0.81414 y'(1) = -1.03727 << 正确

请帮忙!

谢谢!

#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <math.h> 

double ddx(double x,double y,double z)
{
    double dx = (-5*z-3*y)/2;
    return dx;
}

double test2ndorder(double x0, double y0, double z0, double xt, double h)
{
    int n = (int)((xt - x0) / h);
    double k1, k2, k3, k4;
    double l1, l2, l3, l4;

    double x = x0;
    double y = y0;
    double z = z0;

    for (int i = 1; i <= n; i++)
    {

        k1 = h * z;
        l1 = h * ddx(x, y, z);
        k2 = h * (z + 0.5*l1);
        l2 = h * ddx(x + 0.5*h, y + 0.5*k1, z + 0.5*l1);
        k3 = h * (z + 0.5*l2);
        l3 = h * ddx(x + 0.5*h, y + 0.5*k2, z + 0.5*l2);
        k4 = h * (z + l3);
        l4 = h * ddx(x + h, y + k3, z + l3);

        y = y + (1.0 / 6.0)*(k1 + 2 * k2 + 2 * k3 + k4);
        z = z + (1.0 / 6.0)*(l1 + 2 * l2 + 2 * l3 + l4);
        x = x + h;
        std::cout << y << "    ";
        std::cout << z << "\n";
    }
    return y;
}

int main()
{
    double x0, y0, z0, x, y, z,h;
    x0 = 0;
    x = 1;
    y0 = 3;
    z0 = -4;
    h =0.01;

    y = test2ndorder(x0, y0, z0, x, h);
    std::cout << y;
}

test2ndorder 的 for 循环中,您使用常量 x0y0z0 值,因此每次迭代中计算的值不会改变。您还为 y 计算了一个新值并且从不使用它。

看来您应该改用 xyz

2y" + 5y' +3y = 0 ,y(0) = 3 and y'(0) = -4

的特征根是

的解
(2r)^2 + 5*(2r) + 6 = 0  <==>  r = -1 or r = -1.5

所以解决方案是

y(x) = A*exp(-x)+B*exp(-1.5*x)
 3 = y(0)  =  A +     B
-4 = y'(0) = -A - 1.5*B

所以 B = 2A = 1 给出

y(1)  =  0.814139761468302 
y'(1) = -1.03726992161673

这就是你所得到的。