Search code examples
cderivative

Calculate derivative using limit definition in C


I should write a function that calculates the derivative of sin^2(x)/x+3 by using the formula (f(x+h)-f(x))/h.

I have read many examples in Internet but they were complicated. I don`t know much about coding, I should calculate this derivative only by making a function.

For ex.

float deriv(float x,float h)

How can we write this function?


Solution

  • I think a good way to do this is with one function that calculates the derivative based on that definition, as well as with one function that implements that specific formula.

    float deriv (float x, float h) {
    
         float dydx = (function(x+h) - function(x))/h;
         return dydx;
    }
    
    float function(float x) {
        // Implement your sin function here evaluated for the argument
    }
    

    Keep in mind that the definition of a derivative works for as h->0 and to get f'(x) requires stuff to cancel. What we have here is a numerical estimate that is a glorified gradient equation. Good luck!