x1 - code for difference schemes comparison
/* shows the difference between forward, backward, and central finite difference schemes
approximating f'(x) for f(x) = sin(x)
i.e. f'(x) = cos(x)
*/
#include <stdio.h>
#include <math.h>
/* Function */
double forward_diff(double x, double h) {
return (f(x + h) - f(x)) / h;
}
double backward_diff(double x, double h) {
return (f(x) - f(x - h)) / h;
}
double central_diff(double x, double h) {
return (f(x + h) - f(x - h)) / (2.0 * h);
}
int main(void) {
double h = 0.1; // Δx
double x_start = 0.0;
double x_end = 4.0;
FILE *fp = fopen("derivatives.dat", "w");
if (!fp) {
perror("File opening failed");
return 1;
}
int n_steps = (int)((x_end - x_start) / h);
double x_n = x_start;
for (int n = 0; n <= n_steps; n++) {
// compute x at the nth step
x_n = x_start + n * h;
// compute derivatives at x_n
double exact = cos(x_n);
double fwd = forward_diff(x_n, h);
double bwd = backward_diff(x_n, h);
double cent = central_diff(x_n, h);
// add to file
fprintf(fp, "%f %f %f %f %f\n", x_n, exact, fwd, bwd, cent);
}
fclose(fp);
return 0;
}