Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Matlab Derivative Approximation

  1. Apr 3, 2008 #1
    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
    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

    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
  2. jcsd
  3. Apr 12, 2008 #2
    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.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook