Dec-01-2017, 09:40 PM
import random def diff_param(f,h=0.001): return (lambda x: (f(x+h)-f(x))/h) def NR(func, deriv, epsilon=10**(-8), n=100, x0=None): if x0 is None: x0 = random.uniform(-100.,100.) x=x0; y=func(x) for i in range(n): if abs(y)<epsilon: print (x,y,"convergence in",i, "iterations") return x elif abs(deriv(x))<epsilon: print ("zero derivative, x0=",x0," i=",i, " xi=", x) return None else: print(x,y) x = x- func(x)/deriv(x) y = func(x) print("no convergence, x0=",x0," i=",i, " xi=", x) return None # a def equal(f1, f2): root = NR(f1()-f2(),diff_param(f1()-f2(),h=0.001)) return root def test(): f1, f2 = lambda x:4*x+1, lambda x: -x+6 if equal(f1,f2) == None or abs(equal(f1, f2) - 1) > 10**-7: print("error in equal") test()NR() and diff_param() are given functions by the teacher. equal() is what I need to write, adding only two lines! (which I already added here)
In test() you can see f1,f2 , also given by the teacher, that the program needs to run with.
Hope this helps to understand