Python Root finding code

36

import mathdef derivative(f, x): h=1e-8 return (f(x+h)-f(x))/hdef solver(f, x0, epsilon, max_iter): xn=x0 for n in range(0,max_iter): y=f(xn) if abs(y)<epsilon: return xn slope=derivative(f,xn) if(slope==0): return None xn=xn-y/slope return Nonedef loop(f, L_bound, R_bound, increment): solutions=[] while L_bound<=R_bound: solution=solver(f, L_bound, 1e-10, 1000) if solution is not None: solution=round(solution,4) if solution not in solutions: solutions.append(solution) L_bound+=increment print(sorted(solutions)) print(“we found “+str(len(solutions))+” solutions!”)equation=””def f(x): try: y=eval(equation) except ZeroDivisionError: y= 1e-10 return yequation=”x**2–9"loop(f,-100,100,0.5)

Comments

Submit
0 Comments