1

I am studying numerical analysis and also solving algorithms which is described in book. My problem is about Newton's method. In general, if some function is given and we have to find root, how can we determine derivative of function in code? or even limit? because as you know Newton's method involves derivative and makes iteration like this. Suppose some function f(x) and initial guess,p0, then p(n)=p(n-1)+f(p(n-1))/f'(p(n-1)) here f' denotes derivative of f.

How can I approximate it in code? Thanks a lot.

Vivek Ji
  • 117
  • 1
  • 7
  • possible duplicate of [implementing the derivative in C/C++](http://stackoverflow.com/questions/1559695/implementing-the-derivative-in-c-c) – AndersK Oct 07 '11 at 04:40

2 Answers2

3

If you want to use Newton's Method, you will need to know the derivative of the function and code it in.

Otherwise, you can go with the Secant Method which doesn't require knowing the derivative. But it converges at a slower rate.

Mysticial
  • 464,885
  • 45
  • 335
  • 332
  • i know derivative,i want to implement it in c++,i have wrote secant method already –  Oct 07 '11 at 04:43
  • So if you already know what `f'(x)` you can't just implement it? – Mysticial Oct 07 '11 at 04:45
  • yes @Mysticial,just i wanted approximate expression such that,not loss any data while calculation derivative at given point –  Oct 07 '11 at 04:57
  • 1
    The algorithm that approximates `f'(x)` in Newton's Method (I think) ends up reducing to the Secant Method after some algebra. – Mysticial Oct 07 '11 at 05:00
2

Depending on how the function is given, you can do a couple of things

  1. symbolic differentiation, if you have a symbolic representation of your function
  2. Numerical differentiation, if you only have point-value pairs
  3. Interpolate with a polynomial and differentiate that (symobolically of course)

All Options are viable. Which of these is most suited to your problem depends on the function and also the time you want to invest in coding and/or reading up on how to do it.

Edit: If you already know the function before execution time, then compute the differential by hand and implement it as a function. You should also already have implemented your f(x) as a function like this

float f (float x) {
    // ...
}

And thus:

float df_dx (float x) {
    // ...
}
arne
  • 4,514
  • 1
  • 28
  • 47
  • can i use this? (f(x + h) - f(x - h))/2h –  Oct 07 '11 at 04:58
  • You could try. Whether this gives you a good approximation of your derivative depends on the smoothness of your function, how large you choose `h` and also whether you can evaluate your function at arbitrary points. – arne Oct 07 '11 at 05:01
  • 1
    Also: have a look at the article linked as possible duplicate. It explains derivatives and their pitfalls pretty well. – arne Oct 07 '11 at 05:05