Print the Approximations
In this step, you will enhance the program to print detailed approximation results and compare them with the actual derivative.
Open the previous file and modify the code to include comprehensive output:
cd ~/project
nano finite_difference.c
Update the code with detailed approximation printing:
#include <stdio.h>
#include <math.h>
// Define the function f(x)
double f(double x) {
return x * x; // Example function: f(x) = x^2
}
// Actual derivative function
double actual_derivative(double x) {
return 2 * x; // Derivative of x^2 is 2x
}
int main() {
// Define multiple step sizes for comparison
double step_sizes[] = {0.1, 0.01, 0.001, 0.0001};
int num_steps = sizeof(step_sizes) / sizeof(step_sizes[0]);
// Point at which to evaluate the derivative
double x = 2.0;
// Actual derivative value
double true_derivative = actual_derivative(x);
printf("Derivative Approximation Analysis\n");
printf("--------------------------------\n");
printf("Function: f(x) = x^2\n");
printf("Evaluation Point: x = %f\n", x);
printf("True Derivative: %f\n\n", true_derivative);
printf("Step Size | Forward Diff | Backward Diff | Forward Error | Backward Error\n");
printf("-----------------------------------------------------------------------\n");
// Compute and print approximations for different step sizes
for (int i = 0; i < num_steps; i++) {
double h = step_sizes[i];
// Forward Difference Approximation
double forward_diff = (f(x + h) - f(x)) / h;
// Backward Difference Approximation
double backward_diff = (f(x) - f(x - h)) / h;
// Calculate absolute errors
double forward_error = fabs(forward_diff - true_derivative);
double backward_error = fabs(backward_diff - true_derivative);
printf("%9f | %11f | %12f | %11f | %12f\n",
h, forward_diff, backward_diff, forward_error, backward_error);
}
return 0;
}
Compile and run the program:
gcc -o finite_difference finite_difference.c -lm
./finite_difference
Example output:
Derivative Approximation Analysis
--------------------------------
Function: f(x) = x^2
Evaluation Point: x = 2.000000
True Derivative: 4.000000
Step Size | Forward Diff | Backward Diff | Forward Error | Backward Error
-----------------------------------------------------------------------
0.100000 | 4.100000 | 3.900000 | 0.100000 | 0.100000
0.010000 | 4.010000 | 3.990000 | 0.010000 | 0.010000
0.001000 | 4.001000 | 3.999000 | 0.001000 | 0.001000
0.000100 | 4.000100 | 3.999900 | 0.000100 | 0.000100
Key observations:
- As step size
h
decreases, the approximation becomes more accurate
- Forward and backward differences converge to the true derivative
- Error reduces with smaller step sizes