Search code examples
c++numerical-methodsoderunge-kutta

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


I tried to write a code to solve a 2nd order ODE but somehow it did not work as I intended.

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

The final answer will be y(x) = 3-4x << edit this is wrong

therefore y(1) = -1 and y'(1) = -4

But the program output is y(1) = 0.81414 y'(1) = -1.03727 << correct

Please help!

Thank you!

#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;
}

Solution

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

    has characteristic roots that are solutions of

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

    so that the solution is

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

    so that B = 2 and A = 1 which gives

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

    which is about what you got.