To Solve a Differential Equation Using Runge Kutta Method - C Data Structure

C examples for Data Structure:Algorithm

Description

To Solve a Differential Equation Using Runge Kutta Method

Demo Code

#include<stdio.h>

#define F(x,y) (2*x-y)/(x+y)/*from   ww  w . j a  v a2s  .  co m*/

int main(){
  int i, n;
  float x0, y0, h, xn, k1, k2, k3, k4, x, y, k;
  printf("\nEquation: y' = (2*x-y)/(x+y) ");
  
  x0 = 1.2;
  y0 = 1.4;
  xn = 3;
  h = 4;
  n = (xn - x0)/h;
  x = x0;
  y = y0;
  i = 0;
  while (i <= n) {
    k1 = h * F(x,y);
    k2 = h * F(x+h/2.0, y+k1/2.0);
    k3 = h * F(x+h/2.0, y+k2/2.0);
    k4 = h * F(x+h, y+k3);
    k = (k1 + (k2+k3) * 2.0 + k4) / 6.0;
    printf("\nX = %f  Y = %f", x, y);
    x = x + h;
    y = y + k;
    i = i + 1;
  }
}

Related Tutorials