## 1 Replies - 22443 Views - Last Post: 11 December 2016 - 05:12 AM

### #1 Huzi94 Reputation: 14
• Posts: 119
• Joined: 14-November 09

# Newton-Raphson method

Posted 21 October 2012 - 11:22 AM

Description: This snippet uses the Newton-Raphson method to find the root of a polynomial
```#A python program to approximate a root of a polynomial
#using the newton-raphson method
import math
#f(x) - the function of the polynomial
def f(x):
function = (x*x*x) - (2*x) - 1
return function

def derivative(x): #function to find the derivative of the polynomial
h = 0.000001
derivative = (f(x + h) - f(x)) / h
return derivative

def newton_raphson(x):
return (x - (f(x) / derivative(x)))

# p - the initial point i.e. a value closer to the root
# n - number of iterations
def iterate(p, n): #
x = 0
for i in range(n):
if i == 0: #calculate first approximation
x = newton_raphson(p)
else:
x = newton_raphson(iterate(x, n)) #iterate the first and subsequent approximations
n=n-1
return x

print iterate(1, 3) #print the root of the polynomial x^3 - 2x - 1 using 3 iterations and taking initial point as 1

```

Is This A Good Question/Topic? 0

## Replies To: Newton-Raphson method

### #2 DK3250 Reputation: 552
• Posts: 1,730
• Joined: 27-December 13

## Re: Newton-Raphson method

Posted 11 December 2016 - 05:12 AM

I just found this snippet while browsing around on DIC.
I see that the post is now four years old, but I feel like commenting it anyway.

The iterate() function is used recursively, and honestly, this is not how it should be.
It leads to a lot of redundant calculations.

The function is better (and simpler) like this:
```def iterate(p, n):
x = p
for _ in range(n):
x = newton_raphson(x)
return x
```

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }