import math
from random import *
def diff_param(f,h=0.001):
return (lambda x: (f(x+h)-f(x))/h)
def sin_by_million(x):
return math.sin(10**6*x)
def sin_by_million_deriv(x):
return 10**6*math.cos(10**6*x)
def NR(func, deriv=None, 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 function, using the
Newton-Raphson method.
deriv is supposed to be the derivative of func. Default parameter
None is replaced upon execution by diff_param(func).
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 function on some x_i is smaller
than epsilon, None is the returned value """
if deriv is None:
deriv = diff_param(func)
if x0 is None:
x0 = uniform(-100.,100.)
x=x0; y=func(x)
for i in range(n):
if abs(y)