Print the Approximate Derivative
In this step, we will expand our derivative approximation program to compare the numerical approximation with the analytical derivative and print the results in a more informative way.
Update the derivative_approximation.c
file:
nano ~/project/derivative_approximation.c
Replace the previous code with the following:
#include <stdio.h>
#include <math.h>
// Quadratic function f(x) = x^2 + 2x + 1
double f(double x) {
return x * x + 2 * x + 1;
}
// Analytical derivative of f(x)
double analytical_derivative(double x) {
return 2 * x + 2;
}
// Approximate derivative using difference method
double approximate_derivative(double x, double h) {
return (f(x + h) - f(x)) / h;
}
int main() {
double x = 2.0; // Point of derivative approximation
double h_values[] = {1e-1, 1e-2, 1e-3, 1e-4, 1e-5};
int num_h = sizeof(h_values) / sizeof(h_values[0]);
double true_derivative = analytical_derivative(x);
printf("Function: f(x) = x^2 + 2x + 1\n");
printf("Derivative Point: x = %.2f\n", x);
printf("Analytical Derivative: %.4f\n\n", true_derivative);
printf("Derivative Approximation Results:\n");
printf("-----------------------------------\n");
printf("Step Size (h) Approximate Derivative Error\n");
printf("-----------------------------------\n");
for (int i = 0; i < num_h; i++) {
double h = h_values[i];
double approx_derivative = approximate_derivative(x, h);
double error = fabs(true_derivative - approx_derivative);
printf("%.1e %.4f %.6f\n",
h, approx_derivative, error);
}
return 0;
}
Compile and run the updated code:
gcc derivative_approximation.c -o derivative_approximation -lm
./derivative_approximation
Example output:
Function: f(x) = x^2 + 2x + 1
Derivative Point: x = 2.00
Analytical Derivative: 6.0000
Derivative Approximation Results:
-----------------------------------
Step Size (h) Approximate Derivative Error
-----------------------------------
1.0e-01 6.200000 0.200000
1.0e-02 6.020000 0.020000
1.0e-03 6.002000 0.002000
1.0e-04 6.000200 0.000200
1.0e-05 6.000020 0.000020
Code Explanation
- Added
analytical_derivative()
function to calculate the true derivative
- Created an array of different step sizes
h
to demonstrate convergence
- Used a loop to print approximations with different step sizes
- Calculated and displayed the error between analytical and numerical derivatives
- Demonstrates how smaller
h
values lead to more accurate approximations