//This function implements a simple exponential function: f(t) = e^(-t/tau) //It compares the analytically known derivative (true_deriv[]) to //a numerical approximation. It outputs the followings values to //columns in a file: // t f(t) true_deriv finite_deriv (true - finite) (% error) //This should be easy to plot in gnuplot as before with a line like: // plot "output.txt" using <column_to_use_as_x>:<column_to_use_as_y> //Try the following and see how the errors change: // 1) Increase the step size by making NPOINTS larger // 2) Try bringing the step size back down and switching to the // centered finite difference method. // 3) Try increasing the step size using the finite difference method // // What works best to keep the % error down? #include <iostream> #include <math.h> #include <fstream> #define NPOINTS 100 using namespace std; main() { double tau = 100.; double step_size = 4.*tau / NPOINTS; double t_points[NPOINTS], y_points[NPOINTS]; double true_deriv[NPOINTS - 2], finite_deriv[NPOINTS-2]; double deriv_error[NPOINTS - 2]; for (int i = 0; i < NPOINTS; ++i) { t_points[i] = step_size * double(i); y_points[i] = exp(-t_points[i] / tau); } ofstream fout("output.txt"); fout.width(10); fout.setf(ios::scientific); for (int i = 1; i < NPOINTS - 1; ++i) { true_deriv[i] = -1./tau * exp(-t_points[i] / tau); //Forward finite difference finite_deriv[i] = (y_points[i+1] - y_points[i]) / step_size; //Centered finite difference // finite_deriv[i] = (y_points[i+1] - y_points[i-1]) / (2.0 * step_size); deriv_error[i] = finite_deriv[i] - true_deriv[i]; fout << t_points[i] << "\t" << y_points[i] << "\t" << true_deriv[i] << "\t" << finite_deriv[i] << "\t" << deriv_error[i] << "\t" << deriv_error[i] / true_deriv[i] << endl; } fout.close(); }