Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

DZone's Guide to

# Bisection, Rope And Newton Methods

· ·
Free Resource

Comment (0)

Save
{{ articles[0].views | formatCount}} Views
``````
from math import log

def bisect(f, a, b, e):
""" Determines zero between a and b using Bisection. """
n = 0
fa = f(a)
if fa == 0.0: return (a, n)
fb = f(b)
if fb == 0.0: return (b, n)

while (abs(a-b) > e):
c = 0.5*(a+b)
fc = f(c)

if fc == 0.0: return (c, n)
n = n + 1
if fb*fc < 0.0:
a = c
fa = fc

else:
b = c
fb = fc

if fa < fb:
return (a, n)
else:
return (b, n)

def rope(f, a, b, e):
""" Determines zero between a and b using the Rope methode. """
n = 0
fa = f(a)
if fa == 0.0: return (a, n)
fb = f(b)
if fb == 0.0: return (b, n)

while (abs(a-b) > e):
c = (a*fb - b*fa) / (fb - fa)
fc = f(c)
if fc == 0.0: return (c, n)
n = n + 1
if fb*fc < 0:
a = c
fa = fc

else:
b = c
fb = fc

if fa < fb:
return (a, n)
else:
return (b, n)

# Note: must verify that for the function f and guess c
#		the method will _converge_.
def newton(f, df, c, t):
""" Determines zero between a and b using Newton """
n = 0
fc = f(c)
if fc == 0.0: return (c, n)

while (True):
fc = f(c)
dfc = df(c)
if dfc == 0:
print "dfc is 0"
return (0, -1)

dc = -fc/dfc

c = c + dc
n = n + 1
print c
if abs(dc) < t: return (c, n)

##Tests
#def f(x): return -log(x)+4.0
#def df(x): return -1.0/x
#x= bisect(f, 1, 70, 0.00000001)
#print x
#x = rope(f, 1, 70, 0.00000001)
#print x
#x = newton(f, df, 0.1, 0.0001)
#print x

def f(x): return (x+2)*log(2*x**3)+3.0
def df(x): return log(2*x**3)+(3*(x+2))/x

x,y = newton(f, df, 1.0, 0.0001)
print x,y
``````
Topics:

Comment (0)

Save
{{ articles[0].views | formatCount}} Views

Opinions expressed by DZone contributors are their own.