def run_all_methods(file, f, Df, D2f, a, b, x): csv_file = open('%s.csv' % file, mode='w') writer = csv.writer(csv_file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL) writer.writerow(['Method', 'Iteration', 'Convergence']) i = methods.newton(f, Df, a, 10**(-16)) p = methods.convergenceOrder(get_abs(i, x)) write_result(writer, 'Newton', i, p) print("Newton found solution:", i[-1], "in", len(i), "iterations") i = methods.halley(f, Df, D2f, a, 10**(-16)) p = methods.convergenceOrder(get_abs(i, x)) write_result(writer, 'Halley', i, p) print("Halley found solution:", i[-1], "in", len(i), "iterations") i = methods.bisection(f, b, a, 10**(-16)) p = methods.convergenceOrder(get_abs(i, x)) write_result(writer, 'Bisection', i, p) print("Bisection found solution:", i[-1], "in", len(i), "iterations") i = methods.secant(f, b, a, 10**(-16)) p = methods.convergenceOrder(get_abs(i, x)) write_result(writer, 'Secant', i, p) print("Secant found solution:", i[-1], "in", len(i), "iterations")
def rooterror(N,T,filename=None): #plots the convergence of root-finding methods terms = len(N) a = np.zeros([terms,3]) exact = newraph(1000,5,1.523679,0.0934) #again, thanks NR! tol = 1e-14 for i in range(terms): a[i,0] = np.abs(secant(N[i],T)-exact) a[i,1] = np.abs(relax(N[i],T)-exact) a[i,2] = np.abs(bisect(N[i],T)-exact) for j in range(3): if a[i,j]<tol: a[i,j] = tol*0.1 lN = N la = np.log10(a) least = np.zeros([3,2]) for j in range(3): least[j,:] = ls.leastsquares(lN,la[:,j],np.log10(tol)) fig1, ax1 = plt.subplots(1,1) ax1.plot(lN, la[:,0],'ko') p0, = ax1.plot(lN,least[0,0]*lN+least[0,1],'k-',label = '%.4f Secant' % least[0,0]) ax1.set_title("t = "+str(T)) ax1.plot(lN, la[:,1],'ro') p1, = ax1.plot(lN,least[1,0]*lN+least[1,1],'r-',label = '%.4f Relaxation' % least[1,0]) ax1.plot(lN, la[:,2],'bo') p2, = ax1.plot(lN,least[2,0]*lN+least[2,1],'b-',label = '%.4f Bisection' % least[2,0]) ax1.set_xlabel("N") ax1.set_ylabel("Root Log Error") ax1.set_ylim([np.log10(0.1*tol),1]) l0 = ax1.legend(handles=[p0,p1,p2],loc=1)
def get_secant_iterations(thing, tolerance): try: return methods.secant(thing['fn'], thing['bounds'][0], thing['bounds'][1], tolerance)['iterations'] except: return "Fail"
xn = 1.0 xnm1 = 1.0005 xnm2 = 1.005 eps = 0.1 x0 = -1.00 x1 = 1.00 print("Метод Ньютона", methods.newton(f, df, xn, eps)) print("Метод Чебышева", methods.chebishev(f, df, ddf, xn, eps)) print("Метод Хэлли", methods.helley(f, df, ddf, xn, eps)) print("Метод обратной параболической интерполяции", methods.inverseInterpolation(f, xn, xnm1, xnm2, eps)) print("Для другой функции: ") print("Метод секущих", methods.secant(f1, x0, x1, eps)) print("Метод Ньютона", methods.newton(f1, df1, xn, eps)) print("Метод Чебышева", methods.chebishev(f1, df1, ddf1, xn, eps)) print("Метод Хэлли", methods.helley(f1, df1, ddf1, xn, eps)) print("Метод обратной параболической интерполяции", methods.inverseInterpolation(f1, xn, xnm1, xnm2, eps)) input()
def gerar_resultados(minGrau, maxGrau, quantidade, MU, SIGMA, ERROR): random_polinomials = generate_random_polynomials(quantidade, MU, SIGMA, minGrau, maxGrau) results = { "minGrau": minGrau, "maxGrau": maxGrau, "quantidade": quantidade, "mu": MU, "sigma": SIGMA, "error": ERROR, "calculadoPorTodos": 0, "graus": {}, "bissection": { "iterations": 0, "time": 0, "avgF(x)": 0, "ignored": 0, "graus": {} }, "newton": { "iterations": 0, "time": 0, "avgF(x)": 0, "ignored": 0, "graus": {} }, "secant": { "iterations": 0, "time": 0, "avgF(x)": 0, "ignored": 0, "graus": {} } } for i in range(minGrau, maxGrau + 1): results["graus"]["grau%i" % i] = 0 for name in ["bissection", "newton", "secant"]: for i in range(minGrau, maxGrau + 1): results[name]["graus"]["grau%i" % i] = { "iterations": 0, "time": 0, "avgF(x)": 0, "ignored": 0 } for p in random_polinomials: print(p) grauName = "grau%i" % p.o timeBstart = time.time() xB, itrB = methods.bisection(p, ERROR) timeBend = time.time() timeB = (timeBend - timeBstart) timeSstart = time.time() xS, itrS = methods.secant(p, ERROR) timeSend = time.time() timeS = (timeSend - timeSstart) timeNstart = time.time() xN, itrN = methods.newton(p, ERROR) timeNend = time.time() timeN = (timeNend - timeNstart) if xB == None: results["bissection"]["ignored"] += 1 results["bissection"]["graus"][grauName]["ignored"] += 1 if xN == None: results["newton"]["ignored"] += 1 results["newton"]["graus"][grauName]["ignored"] += 1 if xS == None: results["secant"]["ignored"] += 1 results["secant"]["graus"][grauName]["ignored"] += 1 if xB != None and xN != None and xS != None: results["calculadoPorTodos"] += 1 results["graus"][grauName] += 1 results["bissection"]["avgF(x)"] += (p.__call__(xB))/quantidade results["bissection"]["graus"][grauName]["avgF(x)"] += (p.__call__(xB))/quantidade results["bissection"]["iterations"] += itrB results["bissection"]["graus"][grauName]["iterations"] += itrB results["bissection"]["time"] += timeB results["bissection"]["graus"][grauName]["time"] += timeB results["newton"]["avgF(x)"] += (p.__call__(xN))/quantidade results["newton"]["graus"][grauName]["avgF(x)"] += (p.__call__(xN))/quantidade results["newton"]["iterations"] += itrN results["newton"]["graus"][grauName]["iterations"] += itrN results["newton"]["time"] += timeN results["newton"]["graus"][grauName]["time"] += timeN results["secant"]["avgF(x)"] += (p.__call__(xS))/quantidade results["secant"]["graus"][grauName]["avgF(x)"] += (p.__call__(xS))/quantidade results["secant"]["iterations"] += itrS results["secant"]["graus"][grauName]["iterations"] += itrS results["secant"]["time"] += timeS results["secant"]["graus"][grauName]["time"] += timeS for name in ["bissection", "newton", "secant"]: results[name]["iterations"] = results[name]["iterations"]/results["calculadoPorTodos"] results[name]["time"] = results[name]["time"]/results["calculadoPorTodos"] for i in range(minGrau, maxGrau + 1): results[name]["graus"]["grau%i" % i]["iterations"] = results[name]["graus"]["grau%i" % i]["iterations"]/results["graus"]["grau%i" % i] results[name]["graus"]["grau%i" % i]["time"] = results[name]["graus"]["grau%i" % i]["time"]/results["graus"]["grau%i" % i] return results