(1) |
1 #include <stdio.h> 2 #include <math.h> 3 #define IMAX 100001 4 double func(double x, double y); 5 int mk_plot_data(char *a, double x[], double y[], int n); 6 int mk_graph(char *f); 7 8 /*================================================================*/ 9 /* main function */ 10 /*================================================================*/ 11 int main(){ 12 double x[IMAX], y[IMAX]; 13 double final_x, h; 14 double k1, k2, k3, k4; 15 char temp; 16 int ncal, i; 17 18 19 /*--- set initial condition and cal range ---*/ 20 21 printf("\ninitial value x0 = "); 22 scanf("%lf%c", &x[0], &temp); 23 24 printf("\ninitial value y0 = "); 25 scanf("%lf%c", &y[0], &temp); 26 27 printf("\nfinal x = "); 28 scanf("%lf%c", &final_x, &temp); 29 30 do{ 31 printf("\nNumber of calculation steps( <= %d ) = ",IMAX-1); 32 scanf("%d%c", &ncal, &temp); 33 }while(ncal > IMAX-1); 34 35 36 /* --- size of calculation step --- */ 37 38 h=(final_x-x[0])/ncal; 39 40 41 /* --- 4th Runge Kutta Calculation --- */ 42 43 for(i=0; i < ncal; i++){ 44 k1=h*func(x[i],y[i]); 45 k2=h*func(x[i]+h/2.0, y[i]+k1/2.0); 46 k3=h*func(x[i]+h/2.0, y[i]+k2/2.0); 47 k4=h*func(x[i]+h, y[i]+k3); 48 49 x[i+1]=x[i]+h; 50 y[i+1]=y[i]+1.0/6.0*(k1+2.0*k2+2.0*k3+k4); 51 } 52 53 54 /* --- make a graph --- */ 55 56 mk_plot_data("out.txt", x, y, ncal); 57 mk_graph("out.txt"); 58 59 return 0; 60 } 61 62 63 /*================================================================*/ 64 /* define function */ 65 /*================================================================*/ 66 double func(double x, double y){ 67 double dydx; 68 69 dydx=sin(x)*cos(x)-y*cos(x); 70 71 return(dydx); 72 } 73 74 75 /*==========================================================*/ 76 /* make a data file */ 77 /*==========================================================*/ 78 int mk_plot_data(char *a, double x[], double y[], int n){ 79 int i; 80 FILE *out; 81 82 out = fopen(a, "w"); 83 84 for(i=0; i<=n; i++){ 85 fprintf(out, "%e\t%e\n", x[i], y[i]); 86 } 87 88 fclose(out); 89 90 return 0; 91 } 92 93 /*==========================================================*/ 94 /* make a graph */ 95 /*==========================================================*/ 96 int mk_graph(char *f){ 97 FILE *gp; 98 99 gp = popen("gnuplot -persist","w"); 100 101 fprintf(gp, "reset\n"); 102 fprintf(gp, "set terminal postscript eps color\n"); 103 fprintf(gp, "set output \"graph.eps\"\n"); 104 fprintf(gp, "set grid\n"); 105 106 107 /* ------- plat graph ---------*/ 108 109 fprintf(gp, "plot \"%s\" using 1:2 with line\n",f); 110 fprintf(gp, "set terminal x11\n"); 111 fprintf(gp, "replot\n"); 112 113 pclose(gp); 114 115 return 0; 116 }
各行の役割は,以下の通りである.