0

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?

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
noob
  • 107
  • 6

2 Answers2

1

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!

mcfisty
  • 187
  • 10
  • Selection of a good `h` is skipped here - it is not so trivial. So the problem, in the general case, remains unanswered - yet this appears to meet OP's basic need. – chux - Reinstate Monica Dec 03 '18 at 23:16
0

Adding on to @mcfisty, you can have the derivative function taking a pointer to the function that will be manipulated, making the derivative function more general.

double deriv(double x, double (*func)(double))
{
    const double h = 0.0001;
    return (func(x+h) - func(x)) / h;
}

Note this is an approximation. Ideally we'd find the limit as h approaches 0, but that is impossible to do programmatically without having to know what the definition of func is—and we want to keep the definition of the derivative as general as possible.

lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75
  • Floating point math has a logarithmic distribution of values. `x + h` is meaningless for large and small values of `x` - not a good step toward "keep the definition of the derivative as general as possible" . `const double h = x*0.0001;` makes more sense, yet edge cases need consideration. – chux - Reinstate Monica Dec 03 '18 at 23:13
  • @chux what if I change it to 0.001? Is that better – lost_in_the_source Dec 03 '18 at 23:28
  • As 0.001 or 0.01, consider `double f(double x) { return x; }` then `deriv(1e+20, f)` incorrectly returns 0.0 instead of 1.0. A good `h` depends on `x`. See [Implementing the derivative in C](https://stackoverflow.com/q/1559695/2410359) – chux - Reinstate Monica Dec 03 '18 at 23:36