(* RUNGE-KUTTA (ORDER 4) ALGORITHM 5.2 * * To approximate the solution of the initial value problem: * Y' = F(T,Y), A <= T <= B, Y(A) = ALPHA, * at n+1 equally spaced points in the interval [A,B]. * * INPUT: endpoints a, b; initial condition ALPHA; integer n. * * OUTPUT: Approximation W to Y at the (n+1) values of T. *) TEMP=Input["This is the Runge-Kutta Order Four Method\n Input the function F(T,Y) in terms of t and y\n \n For example: y-t^2+1\n"]; F[t_,y_] :=Evaluate[TEMP]; OK = 0; While[OK == 0, A=Input["Input the left endpoint\n"]; B=Input["Input the right endpoint\n"]; If[A >= B, Input["Left endpoint must be less than right endpoint\n \n Press 1 [enter] to continue\n"], OK = 1; ]; ]; ALPHA=Input["Input thr initial condition\n"]; OK=0; While[OK == 0, n=Input["Input a positive integer for the number of\n subintervals\n"]; If[n<=0, Input["Number must be a positive integer\n \n Press 1 [enter] to continue\n"], OK=1; ]; ]; If[OK == 1, FLAG = Input["Select output destination\n 1. Screen\n 2. Text file\n Enter 1 or 2\n"]; If[FLAG == 2, NAME = InputString["Input the file name\n For example: output.dta\n"]; OUP = OpenWrite[NAME,FormatType->OutputForm], OUP = "stdout"; ]; Write[OUP,"Runge-Kutta Fourth Order Method\n"]; Write[OUP,"t w \n"]; Write[OUP,"\n"]; (* Step 1 *) H=N[(B-A)/n]; T=A; W=ALPHA; Write[OUP,SetPrecision[T,9]," \n",SetPrecision[W,9]]; (* Step 2 *) For[i=1, i<=n, i++, (* Step 3 - Use K1,K2,K3,K4, for K(1),K(2),K(3),K(4) resp. *) K1=H*F[T,W]; K2=H*F[T+H/2.0,W+K1/2.0]; K3=H*F[T+H/2.0,W+K2/2.0]; K4=H*F[T+H,W+K3]; (* Step 4 - Compute W(I) *) W=W+(K1+2.0*(K2+K3)+K4)/6.0; (* Comput T(I) *) T=A+i*H; (* Step 5 *) Write[OUP,SetPrecision[T,9]," \n",SetPrecision[W,9]]; ]; (* Step 6 *) If[OUP == "OutputStream[",NAME," 3]", Print["Output file: ",NAME," created successfully\n"]; Close[OUP] ]; ]; Quit[];