Check out the Pastebin Gadgets Shop. We have thousands of fun, geeky & affordable gadgets on sale :-)Want more features on Pastebin? Sign Up, it's FREE!

1

By: a guest on Mar 16th, 2012  |  syntax: None  |  size: 1.89 KB  |  views: 49  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1. public class Runge2{
2.
3.     public static double f(double x, double y){
4.         double f = Math.pow(x,5) * Math.pow(Math.E,Math.pow(x,3));
5.         return f;
6.     }
7.
8.     /* This is the Runge Function given in class */
9.
10.     public static double rk(double x, double y, double step){
11.         double h = step;
12.         double k1 = h * f(x, y);
13.         double k2 = h * f(x + h/2, y + k1/2);
14.         double k3 = h * f(x + h/2, y + k2/2);
15.         double k4 = h * f(x + h, y + k3);
16.
17.         return y += k1/6 + k2/3+ k3/3 + k4/6;
18.     }
19.
20.     public static void main(String[] args){
21.
22.
23.
24.         try{
25.
26.         double stepSize = Double.parseDouble(args[0]);
27.
28.
29.         /* this sets the range of the integral */
30.
31.         double initial = 0;
32.         double end = 1;
33.
34.         /* steps is total steps and finalY is the value of the integral */
35.
36.         double steps = (end - initial) / stepSize;
37.         double i = 0;
38.         double finalY = 0;
39.
40.         if (stepSize <= 0)
41.             throw new Exception("Error: Stepsize is negative or 0. \n");
42.
43.         for (i = 0; i < steps ; i++){
44.             finalY += rk(initial + i * stepSize,
45.                          0, stepSize);
46.         }
47.
48.         System.out.printf("The Runge Kutta method gives the value \n" );
49.         System.out.printf("%1.4f as the integral of x^5 * e^x^3  \n",
50.                           finalY);
51.         System.out.printf("on the interval of %1.4f to %1.4f  \n",
52.                           initial, end );
53.         System.out.printf("using %1.0f steps and a step size of %1.6f \n",
54.                           steps,stepSize);
55.
56.         if (stepSize > 1.0)
57.             throw new Exception("Warning: Stepsize is large. Values may be off.\n");
58.         }
59.
60.         catch(Exception e){
61.             System.out.printf(e.getMessage());
62.             System.out.printf("\nYou need to input a float point value \n");
63.             System.out.printf("For the value of the step size. To get a \n");
64.             System.out.printf("reasonable answer, this step size should \n");
65.             System.out.printf("be fairly small, non-negative and entered \n");
66.             System.out.printf("as a command line argument, thank you. \n");
67.
68.         }
69.
70.
71.     }
72. }
clone this paste RAW Paste Data
Top