def zero(a, b, err=0.01, max_inter=100): n = 0 if func(a) * func(b) > 0: print('Intervalo inválido') return None while n < max_inter: if func(a) == 0: return a elif func(b) == 0: return b if n == 0: new_ant = b new = (((func(a) * (a - b)) / (func(b) - func(a))) + a) if func(new) == 0 or abs((new - new_ant) / new) < err: return new elif func(a) * func(new) < 0: b = new else: a = new n += 1
def parabola(x1, x2, x3, epsilon): f1 = function.func(x1) f2 = function.func(x2) f3 = function.func(x3) countFunc = 3 iter = 1 while 1: ucurrent = x2 - ((x2 - x1)**2 * (f2 - f3) - (x2 - x3)**2 * (f2 - f1)) / (2 * ((x2 - x1) * (f2 - f3) - (x2 - x3) * (f2 - f1))) fu = function.func(ucurrent) countFunc += 1 if iter > 1 and math.fabs(uprev - ucurrent) < epsilon: print(ucurrent, fu) # itercount.append(iter) return ("Локальный минимум: ", ucurrent, "Количество итераций: ", iter, "Количество вычислений: ", countFunc) uprev = ucurrent if f2 > fu: if ucurrent > x2: x1 = x2 f1 = f2 else: x3 = x2 f3 = f2 x2 = ucurrent f2 = fu else: if ucurrent > x2: x3 = x2 f3 = f2 else: x1 = x2 f1 = f2 iter = iter + 1
def goldenRatio(epsilon, a, b): prev = b - a countIter = 1 countFunc = 0 phi = (math.sqrt(5) + 1) / 2 resphi = 2 - phi x1 = a + resphi * (b - a) x2 = b - resphi * (b - a) f1 = function.func(x1) f2 = function.func(x2) countFunc += 2 while (b - a) > epsilon: countIter += 1 if f1 < f2: b = x2 x2 = x1 f2 = f1 x1 = a + resphi * (b - a) f1 = function.func(x1) countFunc += 1 else: a = x1 x1 = x2 f1 = f2 x2 = b - resphi * (b - a) f2 = function.func(x2) countFunc += 1 curent = b - a print(curent / prev) prev = curent print("минимум: ", (x1 + x2) / 2, "количество итераций: ", countIter, "количество вызовов функций: ", countFunc)
def Fibonacci(epsilon, a, b): countIter = 0 countFunc = 0 fib1 = 2 fib2 = 1 fib3 = 1 prev = b - a while ((b - a) / epsilon) >= fib1: fib3 = fib2 temp_fib = fib1 fib1 = fib2 + fib1 fib2 = temp_fib tmp1 = a + fib3 / fib1 * (b - a) tmp2 = a + fib2 / fib1 * (b - a) count_operation = 0 ytmp1 = function.func(tmp1) ytmp2 = function.func(tmp2) countFunc += 2 while (b - a > epsilon): countIter += 1 count_operation = count_operation + 1 if (ytmp1 > ytmp2): a = tmp1 tmp1 = tmp2 ytmp1 = ytmp2 tmp2 = a + fib2 / fib1 * (b - a) ytmp2 = function.func(tmp2) countFunc += 1 else: b = tmp2 tmp2 = tmp1 ytmp2 = ytmp1 tmp1 = a + fib3 / fib1 * (b - a) ytmp1 = function.func(tmp1) countFunc += 1 print((b - a) / prev) prev = b - a temp_fib = fib3 fib3 = fib2 - fib3 fib1 = fib2 fib2 = temp_fib # print(fib3, fib2, fib1) tmp2 = tmp1 + epsilon ytmp2 = function.func(tmp2) countFunc += 1 if (ytmp1 >= ytmp2): a = tmp1 else: b = tmp2 print("минимум: ", (a + b) / 2, "количество итераций: ", countIter, "количество вызовов функций: ", countFunc)
def __init__(self): print("[----------------------------------------]") print("[-------------Welcome Vaccums------------]") print("[----------------------------------------]") self.function_fu = func() self.function_fu.start() self.started_time = time.time()
def __init__(self, parent): tk.Tk.__init__(self, parent) self.parent = parent self.bm = battman() self.func = func(self.parent, self.bm) self.initialize()
def dichotomy(epsilon, a, b): countIter = 0 countFunc = 0 local_a = a local_b = b prev = b - a while (local_b - local_a) > epsilon: countIter += 1 x1 = (local_a + local_b) / 2 - epsilon / 10 x2 = (local_a + local_b) / 2 + epsilon / 10 x1tmp = function.func(x1) x2tmp = function.func(x2) countFunc += 2 if x1tmp > x2tmp: local_a = x1 else: local_b = x2 curent = local_b - local_a print(curent / prev) prev = curent print("минимум: ", (local_a + local_b) / 2, "количество итераций: ", countIter, "количество вызовов функций: ", countFunc)
def zero(a, b, err=0.01, max_inter=100): n = 0 if func(a) * func(b) > 0: print('Intervalo inválido') return None while n < max_inter: if n == 0: new_ant = b new = (a+b)/2 if func(new) == 0 or abs((new - new_ant)/new) < err: return new elif func(a) * func(new) < 0: b = new else: a = new n += 1 print(f'Excedeu o número de interações máximo. ({max_inter} {n})') return None
def continuous_finding(): start_number = read_start() n = start_number while True: if not func(n): store_found(n) print(f'Found {n}') if n % 1000 == 0: write_start(n) print(f'Currently, until {n} is good') if n % 100000 == 0: if not os.path.exists('log'): os.makedirs('log') write_start(n, f'log/Now-{n}.txt') n += 1
def solve(nodes, tol): # initialize madDel as greater than the tolerance madDel = tol + 1 iterator = 0 while (madDel > tol) and iterator < 10000: newValues = [] iterator = iterator + 1 # Iterate through the nodes and solve as needed for k in range(len(nodes)): node = nodes[k] val = func(node, node.neighbours["left"], node.neighbours["right"], node.neighbours["top"], node.neighbours["bottom"]) newValues.append(val) #some equation # Calculate the max change, 'madDel', of the new positions madDel = calcDel(newValues, nodes) for k in range(len(newValues)): nodes[k].T = newValues[k] print(iterator) return nodes
# LINE TEXT INIT pygame.draw.line(screen, (144,144,144), (windowSize[0]/2,0), (windowSize[0]/2,windowSize[1]),1) pygame.draw.line(screen, (144,144,144), (0,windowSize[1]/2), (windowSize[0],windowSize[1]/2),1) pygame.display.update() #var set notstop = 1 c = loops = counter = 0 x = [0,0] data = [] #refactoring and function counting loop for counter in xrange(windowSize[0]): j = counter*(finish-start)/windowSize[0]+start y = func(j) data.append(y) counter+=1 if y>funcMaxY: #maxy and mid detecting for future function rescaling funcMaxY = y if y<funcMinY: funcMinY = y # VAR RESET counter = 0 if (funcMinY-funcMaxY)==0: funcMaxY+=0.01 koeff = -windowSize[1]/(funcMinY-funcMaxY) #scaling koefficent count # PYGAME LINE DRAWING
import function print function.func(1.0)
from function import func if __name__ == '__main__': for i in range(100): func(i, True)
setattr(self, name, value) self.result = np.empty(2) self.num = np.asarray(self.num) self.num_int = np.asarray(self.num_int) def create_params(self, params): params.numbers = self.num.ctypes.data_as(POINTER(c_double)) params.numbers_int = self.num_int.ctypes.data_as(POINTER(c_long)) params.N = len(self.num) params.scale = self.scale params.result = self.result.ctypes.data_as(POINTER(c_double)) def get_sum(self): params = Parameters() self.create_params(params) CalculateSum(params) if __name__ == "__main__": Data = dict( num=[2., 3.], num_int=[5, 6], scale=2 ) ans = Calculate(**Data) ans.get_sum() print(func(ans.result))
def test_output(self): array = [2, 1, 5, 7] self.assertEqual(function.func(array), [35, 70, 14, 10])
from function import list_arg as func func(['a'])
from function import func import numpy as np import logging def setLogger(): logger = logging.getLogger("main") logger.setLevel(logging.INFO) file_handler = logging.FileHandler('log_file.log', mode='w') file_handler.setLevel(logging.INFO) errors = logging.FileHandler('log_file.log') errors.setLevel(logging.ERROR) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s') file_handler.setFormatter(formatter) errors.setFormatter(formatter) logger.addHandler(file_handler) logger.addHandler(errors) return logger if __name__ == "__main__": logger = setLogger() n = 10000 ar = [float(i) for i in np.random.randint(1, n, n)] logger.info(f"Program started with ar: {ar}") func(ar) logger.info("Done!")
def test_func(): from function import func result = func(1, 2) assert result is False