MATLAB Matlab Derivative Approximation

AI Thread Summary
The discussion focuses on a program designed to estimate the derivative of a polynomial and calculate the associated error. The code provided uses a centered difference approximation method within a for-loop to iteratively refine the step size (dh) for derivative calculation. The user encounters an issue where the output values for the derivative (df) and the error are switched. A suggestion is made to modify the loop condition to terminate based on a threshold (e) rather than relying on dh reaching zero, as dh is a real number and will not become zero. This adjustment aims to prevent an infinite loop and improve the accuracy of the derivative estimation.
JefeNorte
Messages
9
Reaction score
0
I am trying to write a program that estimates the derivative of a polynominal and determines the error. So far my code is

% The code for Problem 3.

a=5-4*x^2+3*x^3-2*x^4+x^5; % ask for a function to be differentiated

x=input('Enter the value x at which to find the derivative '); % ask for input
dh=.5;
for i=1:dh:100% do the loop
dh=.5*(1/2)^i; % step size
df=((5-4.*(x+dh).^2+3.*(x+dh).^3-2.*(x+dh).^4+(x+dh).^5)-(5-4*x^2+3*x^3-2*x^4+x^5))/dh; % centered difference approximation
if 1+dh==1
break
else
dh=dh/2;
end
end
error=(-8*x+9*x^2-8*x^3+5*x^4)-df;
disp(df)
disp(error)


The result is two numbers that are correct but the df is switched with error and vise versa. Does anyone know what I am doing wrong
 
Physics news on Phys.org
I don't know if this has to with your problem. But in my opinion has your for-loop an infinite number of turns because dh will never be 0 (dh is a real number). So instead you should stop your loop then dh<e, where e is some limit.
 

Similar threads

Replies
4
Views
1K
Replies
1
Views
2K
Replies
2
Views
3K
Replies
1
Views
2K
Replies
8
Views
2K
Back
Top