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 calculate(self): """Does all the work""" item_number = self.fields.curselection() polynomial = self.json_data["functions"][int(item_number[0])] result_floating = None result_interval = None if self.json_data["method"] == "regula_falsi": try: result_floating = regula_falsi(polynomial["a"], polynomial["b"], function_from_list, polynomial["coeff"] ) except MyError as error: result_floating = error.value except ZeroDivisionError: result_floating = "Unfortunately, division by 0 happened" try: result_interval = regula_falsi_interval(polynomial["a"], polynomial["b"], function_from_list, polynomial["coeff"] ) result_interval = result_interval.format('%.20E')[9:] result_interval = result_interval[:-1] except MyError as error: result_interval = error.value elif self.json_data["method"] == "newton": try: result_floating = newton(polynomial["x"], polynomial["epsilon"], polynomial["max_iterations"], function_from_list, polynomial["coeff"], polynomial["derivative_coeff"] ) except ZeroDivisionError: result_floating = "Unfortunately, division by zero happened" except MyError as error: result_floating = error.value try: result_interval = newton_interval(polynomial["x"], polynomial["epsilon"], polynomial["max_iterations"], function_from_list, polynomial["coeff"], polynomial["derivative_coeff"] ) result_interval = result_interval.format('%.20E')[9:] result_interval = result_interval[:-1] except MyError as error: result_interval = error.value else: result_interval = "You propably" result_floating = "gave me wrong JSON" self.show_result_floating.config(text=result_interval) self.show_result_interval.config(text=result_floating)
def ddf1(x): return -math.sin(x) def f2(x): return x**3 - 18 * x - 83 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))
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
if 0 < stop_condition < 3: correct = True else: print("Brak takiego kryterium") except ValueError: print("Brak takiego kryterium") accuracy = 0 iteration = 0 if stop_condition == 1: accuracy = abs(float(input("Podaj dokładność epsilon: "))) iteration = -1 else: iteration = int(input("Podaj liczbe iteracji: ")) accuracy = -1 result_bisection = bisection(left, right, accuracy, iteration, function_number) # miejsce zerowe (bisekcja) result_newton = newton(left, right, accuracy, iteration, function_number) # miejsce zerowe (netwon) if result_bisection is False: print("Bisekcja: Funkcja nie spełnia założeń na danym przedziale") else: print("Bisekcja - " + str(result_bisection)) if result_newton is False: print("Newton: Funkcja nie spełnia założeń na danym przedziale") else: print("Newton - " + str(result_newton)) show_plot(left, right, function_number, result_bisection, result_newton) # rysowanie wykresu