/*********************** Numerically integrate a differential equation using Euler's method ************************/ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Symbols~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // h :: Step size of integration // x_n :: position at nth time // x_n1 :: position at (n+1)th time // c :: integration constant //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //Include libraries #include #include main() { int i, n; double x_n, x_n1, h, c; FILE*fw = fopen( "euler.dat", "w" ); FILE*fa = fopen( "analytical.dat", "w" ); printf( "Enter the step size, h: \t" ); scanf( "%lf", &h ); printf( "Enter the number of steps: \t" ); scanf( "%d", &n ); printf( "Enter the initial value of x0 between 0 to 2 pi: \t" ); scanf( "%lf", &x_n ); fprintf( fw, "%d\t%lf\n", 0, x_n ); c = log( tan( x_n / 2.0 ) ); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Euler's Method~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ for( i = 1; i <= n; i++ ) { x_n1 = x_n + h * sin( x_n ); x_n = x_n1; fprintf( fw, "%0.6lf\t%0.6lf\n", i * h, x_n ); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Analytical Results~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ for( i = 1; i <= n; i++ ) { x_n = 2 * atan( exp( i * h + c ) ); fprintf( fa, "%0.6lf\t%0.6lf\n", i * h, x_n ); } fclose(fw); fclose(fa); }