Runge | Java program to implement Runge Kutta method ; A sample differential equation " dy / dx ▁ = ▁ ( x ▁ - ▁ y ) /2" ; Finds value of y for a given x using step size h and initial value y0 at x0 . ; Count number of iterations using step size or step height h ; Iterate for number of iterations ; Apply Runge Kutta Formulas to find next value of y ; Update next value of y ; Update next value of x ; Driver Code
class GFG { static double dydx ( double x , double y ) { return ( x + y - 2 ) ; } static double rungeKutta ( double x0 , double y0 , double x , double h ) { int n = ( int ) ( ( x - x0 ) / h ) ; double k1 , k2 ; double y = y0 ; for ( int i = 1 ; i <= n ; i ++ ) { k1 = h * dydx ( x0 , y ) ; k2 = h * dydx ( x0 + 0.5 * h , y + 0.5 * k1 ) ; y = y + ( 1.0 / 6.0 ) * ( k1 + 2 * k2 ) ; x0 = x0 + h ; } return y ; } public static void main ( String [ ] args ) { double x0 = 0 , y = 1 , x = 2 , h = 0.2 ; System . out . println ( rungeKutta ( x0 , y , x , h ) ) ; } }