Skip to content

Instantly share code, notes, and snippets.

@metula
Created January 3, 2014 12:29
Show Gist options
  • Select an option

  • Save metula/8237180 to your computer and use it in GitHub Desktop.

Select an option

Save metula/8237180 to your computer and use it in GitHub Desktop.
from random import *
def NR(func, deriv, epsilon=10**(-8),n=100,x0=None):
""" Given a real valued func and its real value derivative,
deriv, NR attempts to find a zero of func, using the
Newton-Raphson method.
NR starts with a an initial x0 (default value is None
which is replaced upon execusion by a random number distributed
uniformly in (-100.,100.)), and performs n=100 iterations.
If the absolute value derivative on some x_i is smaller
than epsilon, None is the returned value. """
if x0 is None:
x0 = uniform(-100.,100.)
x = x0
y = func(x)
for i in range(n):
if abs(y) < epsilon:
return x
elif abs(deriv(x)) < epsilon:
print ("zero derivative, x0=", x0, " i=", i, " xi=", x)
return None
else:
x = x - func(x) / deriv(x)
y = func(x)
print("no convergence, x0=", x0," i=", i, " xi=", x)
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment