MATLAB Program to Approximate Derivatives Using the Finite Difference Formula

 

Question Restated and Explained

You are asked to create a MATLAB program that computes an approximate value for the derivative of any function at a given point, using the finite difference formula:

f(x)f(x+h)f(x)hf'(x) \approx \frac{f(x + h) - f(x)}{h}

You should then test your program with the function f(x)=tan(x) at x=1x = 1.

MATLAB Program to Approximate Derivatives Using the Finite Difference Formula


Step-by-Step Solution

Explanation:

  • The finite difference formula gives a numerical estimate for the derivative at a point.

  • The choice of hh (a small value, e.g., 0.0001) affects the accuracy.

  • You can write a MATLAB function that takes as input any function handle, the value of xx, and a step size hh, and returns the approximate derivative.

  • To test: use f(x)=tan(x)f(x) = \tan(x), x=1x = 1.


MATLAB Code

matlab

% Function to compute approximate derivative using finite difference function approx_deriv = finite_difference(f, x, h) approx_deriv = (f(x + h) - f(x)) / h; end % Testing the program with tan(x) at x = 1 f = @tan; % Function handle for tan(x) x = 1; % Point at which to compute the derivative h = 1e-5; % Small step size approximate_derivative = finite_difference(f, x, h); % Exact derivative for comparison: derivative of tan(x) is sec^2(x) exact_derivative = sec(x)^2; fprintf('Approximate derivative of tan(x) at x = 1: %f\n', approximate_derivative); fprintf('Exact derivative (sec^2(1)) at x = 1: %f\n', exact_derivative); fprintf('Error: %e\n', abs(approximate_derivative - exact_derivative));

  • This code defines a function finite_difference to calculate the approximate derivative.

  • It then uses this function to compute the derivative of tan(x) at x = 1.

  • It also compares the approximate result to the exact value, displaying both and the error.



📩 Need a similar solution? Email me: adel455@hotmail.com








Previous Post Next Post

Comments

Nepali Graphics - Learn design, Animation, and Progrmming