def test_newton(capsys): equa = [-1, 0, 6, -5, 1] prec = 12 newton.newton(equa, prec) captured_stdout, captured_stderr = capsys.readouterr() assert captured_stderr == "" assert captured_stdout == "('x =', 0.5)\n('x =', '0.522727272727')\n"\ "('x =', '0.522740003514')\n('x =', '0.522740003526')\n"
def ga(limit, alpha1, beta1, alpha2, beta2, alpha3, beta3, crop, epoch, a_p, b_p, c_p, fit = F, selection=selection, n=6): global a_par, b_par, c_par a_par, b_par, c_par = a_p, b_p, c_p mutation_f = mutate_function(alpha1, beta1, alpha2, beta2, alpha3, beta3) initial_individuals1 = [] # формируем популяцию for i in range (0, crop - 1): individual = [np.random.uniform(low=alpha1, high=beta1) for i in range(2)] individual = individual + [np.random.uniform(low=alpha2, high=beta2) for i in range(2)] individual = individual + [np.random.uniform(low=alpha3, high=beta3) for i in range(2)] sys_solution = newton.newton(individual, a_par, b_par, c_par) while not sys_solution.constraints_satisfy(limit): # новый набор Q и проверка на ограничения individual = [np.random.uniform(low=alpha1, high=beta1) for i in range(n)] sys_solution = newton.newton(individual, a_par, b_par, c_par) initial_individuals1.append(Individual(individual, sys_solution)) center = center_of_mass(initial_individuals1) population = [(x, fit(center, Individual.getSol(x))) for x in initial_individuals1] population.sort(key=operator.itemgetter(1)) pcross = 0.3 #вероятность кроссинговера pmut = 0.5 #вероятность мутации iter = 0 while iter < epoch: iter += 1 print('%s epoch' % iter) # selection if len(population) >= crop: population = selection(population, crop) center = center_of_mass_pop(population) # print(center) pop_len = len(population) # cross childs = crossover(population, pop_len, pcross, fit, center, limit) # mutation # выбираются родителькие хромосомы для мутации mutation_list = mutation(population, pmut, fit, center, limit, mutation_f) population += mutation_list while len(population) < crop: childs = crossover(population, pop_len, pcross, fit, center, limit) mutation_list = mutation(population, pmut, fit, center, limit, mutation_f) population += mutation_list population.sort(key=operator.itemgetter(1)) population.sort(key=operator.itemgetter(1)) return population[:(crop)]
def cross(ind1, ind2, limit): ind1 = np.asarray(Individual.getQ(ind1)) ind2 = np.asarray(Individual.getQ(ind2)) c = np.random.rand() ch1 = c * ind1 + (1 - c) * ind2 ch2 = c * ind2 + (1 - c) * ind1 sol1, sol2 = newton.newton(ch1, a_par, b_par, c_par), newton.newton(ch2, a_par, b_par, c_par) while not sol1.constraints_satisfy(limit) & sol2.constraints_satisfy(limit): c = np.random.rand() ch1 = c * ind1 + (1 - c) * ind2 ch2 = c * ind2 + (1 - c) * ind1 sol1, sol2 = newton.newton(ch1, a_par, b_par, c_par), newton.newton(ch2, a_par, b_par, c_par) return ch1, ch2, sol1, sol2
def cons_to_prim( U, gamma ): """ perform a recovery of the primitive variables """ W = zeros(U.shape) D = U[0,:] S = U[1,:] tau = U[2,:] ps = zeros(U.shape[1]) p0 = 5 for i in range(U.shape[1]): proot = newton( fp, dfp , p0 , D[i] , S[i],tau[i], gamma) ps[i] = proot vs = S / ( tau + ps + D ) lors = lorentz_factor( vs ) rs = D / lors if (ps<0).any(): print("Negative pressure") print(ps) ps = where(ps<0,fabs(S-tau-D),ps) if ( vs >= 1).any(): print( "v greater than c") print(vs[vs>1]) vs = where( vs>1 , 1e-6 , vs ) W[2,:] = ps[:] W[1,:] = vs[:] W[0,:] = rs[:] return W
def mutation(childs, pmut, fit, center, limit, mutation_f): mutation_list = list(filter(lambda individual: np.random.rand() < pmut, childs[:int(len(childs) * pmut)])) for i, individual in enumerate(mutation_list): mutated = mutation_f(Individual.getQ(individual[0]), limit) sol = newton.newton(mutated, a_par, b_par, c_par) mutation_list[i] = (Individual(mutated, sol), fit(center, sol)) return mutation_list
def polozaj_planeta(index, t, r_speed=False, matrica=False): # kao sadasnjost se racuna godina 2000. if index == 0: return np.array([0.0, 0.0, 0.0]) if matrica and not r_speed: if not podaci.polozaji_ucitani: podaci.polozaji_ucitani = True podaci.beg_date = np.load('datum.npy')[0] podaci.years_saved = np.load('years.npy') podaci.step_matrica = np.load('step.npy')[0] podaci.polozaji_matrica = np.load('polozaji_planeta.npy') offset = dt.timedelta(seconds=t) offset = podaci.beg_of_time + offset - podaci.beg_date index_vreme = int(offset / podaci.step_matrica) (x1, y1) = podaci.polozaji_matrica[index_vreme][index] (x2, y2) = podaci.polozaji_matrica[index_vreme + 1][index] # ugao1 = math.atan2(y1, x1) # ugao2 = math.atan2(y2, x2) # ugao = ugao1 + (offset-index_vreme*podaci.step_matrica)/podaci.step_matrica * (ugao2-ugao1) # r = (modulo(np.array(x1, y1)) + modulo(np.array(x2, y2))) / 2 # return np.array((r*math.cos(ugao), r*math.sin(ugao))) return np.array((x1 + (offset - index_vreme * podaci.step_matrica) / podaci.step_matrica * (x2 - x1), y1 + (offset - index_vreme * podaci.step_matrica) / podaci.step_matrica * (y2 - y1))) else: a0, a1, e0, e1, l0, l1, omegabar0, omegabar1 = podaci.info[index] # omegabar1 = 0.44441088 t = t / (24 * 3600) t_ = t / 36525 a0 = a0 + a1 * t_ e0 = e0 + e1 * t_ l0 = l0 + l1 * t_ omegabar0 = omegabar0 + omegabar1 * t_ m = np.deg2rad(((l0 - omegabar0) % 360) - 180) e_ = newton(e0, m, m, tol=1e-10, maxiter=10) if not r_speed: e_ = e_ * 1 x = a0 * (math.cos(e_) - e0) * au y = a0 * math.sqrt(1 - e0**2) * math.sin(e_) * au if r_speed: m_prime = np.deg2rad(l1 - omegabar1) # /cty e_prime = (m_prime + e1 * math.sin(e_)) / (1 - e0 * math.cos(e_) ) # /cty x_prime = a1 * (math.cos(e_) - e0 ) - a0 * math.sin(e_) * e_prime - a0 * e1 # au/cty x_prime = x_prime * au / (36525 * 24 * 3600) # iz au/cty u m/s y_prime = (a1 * math.sqrt(1 - e0**2) * math.sin(e_) - a0 * e0 * e1 * math.sin(e_) / math.sqrt(1 - e0**2) + a0 * math.sqrt(1 - e0**2) * math.cos(e_) * e_prime) y_prime *= au / (36525 * 24 * 3600) return np.array([x, x_prime, y, y_prime], dtype=np.float64) return np.array([x, y, e_], dtype=np.float64)
def test_parabola_with_constant_term(s, r): ''' tests if the Newton algorithm correctly finds that the function f(x) = x^2-r has two zeros x=sqrt(r) and x=-sqrt(r), with r>0. The strategy is to test the algorithm starting from different initial points: if the initial guess is positive, the positive zero (x=2) is found; if the initial guess is negative, the negative zero (x=-2) is found. ''' def f(x): return x**2 - r def Df(x): return 2 * x x0 = s if x0 > 0: assert round(newton(f, Df, x0).x, 5) == round(np.sqrt(r), 5) elif x0 < 0: assert round(newton(f, Df, x0).x, 5) == round(-np.sqrt(r), 5)
def resultados_newton(): f = open("resultados", "a") f.write("\n******** Newton ********\n\n") f.close() resultados = [] # Resultados do metodo de newton resultados = newton.newton(f1, math.pi / 2, precisao_absoluta) converg = oc.ordem_convergencia(resultados, f1_rcorreto) print_resultados(1, resultados, converg) resultados = newton.newton(f2, 7.5, precisao_absoluta) converg = oc.ordem_convergencia(resultados, f2_rcorreto) print_resultados(2, resultados, converg) resultados = newton.newton(f3, 1.0, precisao_absoluta) converg = oc.ordem_convergencia(resultados, f3_rcorreto) print_resultados(3, resultados, converg)
def test_polynomial(self): #return False print("polynomial") def f(x): return 3*x**3-7*x**2+x-1 x=newton.newton(f, lambda x: 9*x**2-14*x+1, 2, 1e-8) print(x) print(f(x)) assert(norm(f(x)) < 1e-8)
def problem_1b_newton_ill(): n_observations, n_variables = problem1_variables() X = generate_ill_conditioned(n_observations, n_variables) beta = generate_sample_beta(X.shape[1]) func, grad, hessian = generate_classical(X, beta) x0 = np.zeros([beta.shape[0], 1]) estimated_beta, history = newton(func, grad, hessian, x0, beta, method = 'diminishing') np.savetxt('problem_1b_newton_ill', history)
def test_polynomial(self): #return False print("polynomial") def f(x): return 3 * x**3 - 7 * x**2 + x - 1 x = newton.newton(f, lambda x: 9 * x**2 - 14 * x + 1, 2, 1e-8) print(x) print(f(x)) assert (norm(f(x)) < 1e-8)
def task1(): rho = 1 a = -1.8 b = 0.6 # for i in np.linspace(-1.7, 0.6, 24): # print(rho, i, newton(rho, i, fa, dfa, first_stop_criteria)[1]) # print(secant(rho, a, i, fa, first_stop_criteria)[1]) for i in range(16): print(i, newton(rho, -1, fa, dfa, first_stop_criteria)[1]) rho /= 10
def f(individual, limit): pow_factor = 12 new_ind = np.copy(individual) for i in range(len(individual)): if (i == 1 | i == 2): alpha = alpha1 beta = beta1 elif (i == 3 | i == 4): alpha = alpha2 beta = beta2 else: alpha = alpha3 beta = beta3 factor = np.random.rand() if np.random.randint(0, 2) == 0: new_ind[i] -= (new_ind[i] - alpha) * factor ** pow_factor else: new_ind[i] += (beta - new_ind[i]) * factor ** pow_factor sol = newton.newton(new_ind, a_par, b_par, c_par) while not sol.constraints_satisfy(limit): for i in range(len(individual)): if (i == 1 | i == 2): alpha = alpha1 beta = beta1 elif (i == 3 | i == 4): alpha = alpha2 beta = beta2 else: alpha = alpha3 beta = beta3 factor = np.random.rand() if np.random.randint(0, 2) == 0: new_ind[i] -= (new_ind[i] - alpha) * factor ** pow_factor else: new_ind[i] += (beta - new_ind[i]) * factor ** pow_factor sol = newton.newton(new_ind, a_par, b_par, c_par) return new_ind
def main(argv): if (len(sys.argv) != 8): helper.helper() sys.exit(84) checker() flag = int(sys.argv[1]) a0 = int(sys.argv[2]) a1 = int(sys.argv[3]) a2 = int(sys.argv[4]) a3 = int(sys.argv[5]) a4 = int(sys.argv[6]) prec = int(sys.argv[7]) equa = [a0, a1, a2, a3, a4] if (flag == 1): bisection.bisection(equa, prec) elif (flag == 2): newton.newton(equa, prec) elif (flag == 3): secant.secant(equa, prec) exit(0)
def main(): a, Delta, N = rps.readParameters() x0 = 0.5 y0 = -3 v = newton.newton(x0, y0) x, y = createCurve.createCurve(v) plt.plot(x, y, "b-o") plt.grid() plt.xlim(min(x) - 0.05, max(x) + 0.05) plt.ylim(min(y) - 0.05, max(y) + 0.05) plt.show() return 0
def problem_1c_newton(): n_observations, n_variables = problem1_variables() X = generate_ill_conditioned(n_observations, n_variables) beta = generate_sample_beta(X.shape[1]) for penalty in [0.1, 1.0, 10.0, 100.0]: func, grad, hessian = generate_ridge(X, beta, penalty) x0 = np.zeros([beta.shape[0], 1]) estimated_beta, history = newton(func, grad, hessian, x0, beta, method = 'diminishing') np.savetxt('problem_1c_newton' + '_%.1f' % penalty, history)
def solve_poly(p): roots = list() cur_p = p diff_p = diff_poly(p) for i in range(p.degree): if len(roots) > 0: cur_p = deflate(cur_p, roots[-1]) x0, x1, x2 = muller_init_poly(cur_p) r = muller(cur_p, 2, x0, x1, x2) r = newton(r, p, diff_p, 10) roots.append(r) return roots
def test_parabola_without_constant_term(s): ''' tests if the Newton algorithm correctly finds that the function f(x)=x^2 has a unique zero at x=0 starting from different initial conditions in between the interval [-10,10]. ''' def f(x): return x**2 def Df(x): return 2 * x assert round(newton(f, Df, x0=s).x, 5) == 0
def test_exception(s, r): ''' tests if the newton algorithm raises a false boolean variable success if a function with no zeros is given as input, for example the parabola f(x) = x^2 + r, with r positive number. The initial guess is a float number s within the interval [-10,10]. ''' def f(x): return x**2 + r def Df(x): return 2 * x x0 = s assert newton(f, Df, x0).success == False
def exercicio1_2(): print("Exercicios 1") inicializar() M = gauss.gauss(n,Matriz,d) print("Parametro M") print(str(np.array(M))) A = parametros.parametroA(x,M,h,n) print("Parametro A") print(str(np.array(A))) B = parametros.parametroB(x,M,h,n) print("Parametro B") print(str(np.array(B))) valoresDeTeste = np.zeros(n); valoresDeTeste[0] = (t[1] + t[0]) / 2 print("Valores de t") for i in range(1, n, 1): valoresDeTeste[i] = valoresDeTeste[i - 1] + (1.0/60) print(str(np.array(valoresDeTeste))) print("Teste do polinomio") spline = np.zeros(n) for i in range(0, n, 1): spline[i] = util.splineCubico(valoresDeTeste[i],M,h,A,B,t,n) print(str(np.array(spline))) print("Teste da primeira derivada") derivada1 = np.zeros(n) for i in range(0, n, 1): derivada1[i] = util.derivadaSC(valoresDeTeste[i],M,h,A,B,t,n) print(str(np.array(derivada1))) print("Teste da segunda derivada") derivada2 = np.zeros(n) for i in range(0, n, 1): derivada2[i] = util.segundaDerivadaSC(valoresDeTeste[i],M,h,A,B,t,n) print(str(np.array(derivada2))) print("O intervalo escolhido é [t19, t20]") print("Exercicio 2") print("O chute será 0.333") raiz = newton.newton(0.333,M,h,A,B,t,n,10**-10,n) print("O t é: " + str(raiz))
def main(): tab = [[i, i**2] for i in range(11)] x = 0.5 print('\n\nТаблица функции (y = x^2):') print("+{:11s}|{:11s}+".format('-', '-').replace(' ', '-')) print('| X | Y |') print("|{:11s}|{:11s}|".format('-', '-').replace(' ', '-')) for i in tab: print('|{:11d}|{:11d}|'.format(i[0], i[1])) print("|{:11s}|{:11s}|".format('-', '-').replace(' ', '-')) print('\nX =', x) print('Результат интерполяции кубическим сплайном: {:.6f}'.format(spline(tab, x))) print('Значение y(x): {:.3f}'.format(x ** 2)) print('Результат интерполяции полиномом Ньютона 3-ей степени: {:.6f}'.format(newton(tab, 3, x)))
def bsimpvol(callput, S0, K, r, T, price, q=0, priceTolerance=0.01, init=0, max_iter=100, method='bisect'): ''' :param callput:judgement for option :param S0:intial value of the underlying :param K:the strike price :param r:interest rate :param T:time to maturity :param price:theoretical price under BS formula :param q:continuous return rate on the underlying :param priceTolerance:criterion to stop the process :param method:judgement to use bisect method or newton method :return:implied volatility and iteration ''' sigma = init #np.random.random() results = [] def f(x): return bsformula(callput, S0, K, r, T, x, q)[0] - price if method == 'bisect': results = bisect(0, f, None, [0.001, 1.0], [priceTolerance, priceTolerance], max_iter) else: def f_prime(x): return bsformula(callput, S0, K, r, T, x, q)[2] results = newton(f, f_prime, sigma, priceTolerance, max_iter) return results
def determina_n(): # Calcula o erro_gauss do método de Gauss erro_gauss = gauss.erro_n(y, q, r, a, b, a_, b_, 41, 5) n_erro_gauss = range(5, 41, 5) # Calcula e imprime o polinomio interpolador pelo método de mínimos quadrados mmq = minimos.polin(n_erro_gauss, erro_gauss) print('CONSTANTES POLINÔMIO OBTIDO POR MÍNIMOS QUADRADOS') print(mmq[1]) # Le o erro desejado erro_desejado = float(input('Insira o erro desejado ')) def mmq_erro(x): return mmq[0](x) - erro_desejado def mmq_erro_deriv(x): return -(mmq[1][0] * (x**2) + 2 * mmq[1][1] * x + 3 * mmq[1][2]) / x**4 # Resolução por Bissecção start_time = time.time() n_erro = bisseccao.bissec(mmq_erro, 1, 500, 0.1, 0) total_time = abs(start_time - time.time()) print('--------------- Utlizando Bissecção ---------------') print( 'Para garantir um erro inferior a {:.0e} é necessário n={:.0f}'.format( erro_desejado, n_erro[0])) print('Número de iterações: {}'.format(n_erro[1])) print('Tempo consumido: {:.6f} segundos'.format(total_time)) # Resolução por Newton start_time = time.time() n_erro = newton.newton(mmq_erro, mmq_erro_deriv, 10, 1000, 0.1) total_time = abs(start_time - time.time()) print('--------------- Utlizando Newton ---------------') print( 'Para garantir um erro inferior a {:.0e} é necessário n={:.0f}'.format( erro_desejado, n_erro[0])) print('Número de iterações: {}'.format(n_erro[1])) print('Tempo consumido: {:.6f} segundos'.format(total_time))
def main(): f = lambda x: 3*x**2 - 2 trials = 10 print newton(f, trials, 7)
def trsc(sigma, delta, xc, f, g, H, D): # import necessary functions from numpy import diag, min, argmin, identity, dot, inf, sqrt from numpy.linalg import eig, solve, norm # our own functions from newton import newton from newtonw import newtonw # Define function to minimise fun = lambda x: f + dot(x,g) + 0.5 * dot(x,dot(H,x)) + (sigma / 3) * norm(x) ** 3 # n.b. x -> x - xc for convenience # Return roots of quadratic equation def quadeq(a, b, c): x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a) x2 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a) return x1, x2 # Case a) Trust-region inactive # Given w, get eig. dec. LV, UV = eig(H) # Get minimum eigenvalue l1 = min(LV) il = argmin(LV) LV = diag(LV) # diagonalise LV # Define nf1(w) to find roots def nf1(w): # Find x(w) xw = solve((LV + w * identity(D)),dot(-UV.T,g)) # Calculate |xw|-w/sigma (for newton stopping rule) xwmws = norm(xw) - w / sigma # Calculate f(w)for p=-1 fw = 1 / norm(xw) - sigma / w # Find x'(w) xwp = solve((LV + w * identity(D)),(-xw)) # Calculate f'(w) for p=-1 fwp = -dot(xw,xwp) * (dot(xw,xw) ** (-1.5)) + sigma / (w * w) # Calculate increment dw = fw / fwp # Set w/sigma Wsigma = w / sigma return xwmws, dw, Wsigma # No interior solution for sigma < 0 and H < 0 if (not ((sigma < 0) and (l1 < 0))): # If sigma is negative if (sigma < 0): # Initial perturbation w = -1e-5 # Lower bound on w wl = -l1 else: # Find singularity sp = max(0, -l1) # Initial perturbation w = sp + 1e-5 # Lower bound on w wl = 0 # Find x(w) xw = solve((LV + w * identity(D)),dot(-UV.T,g)) # Check for Hard Case if (norm(xw) <= w / sigma): #disp('Hard Case! TR Inactive') u = UV[:,il] # Find quadratic roots [alpha1, alpha2] = quadeq(dot(u,u), 2 * dot(xw,u), dot(xw,xw) - (w / sigma) ** 2) xbh1 = xw + alpha1 * u bndh1 = fun(xbh1) xbh2 = xw + alpha2 * u bndh2 = fun(xbh2) # Return minimum of bndh1 and bndh2 if (bndh1 < bndh2): bnd1 = bndh1 xb1 = xbh1 else: bnd1 = bndh2 xb1 = xbh2 else: # Run newton w = newtonw(nf1, w, wl) # Given w, find x x = solve((H + w * identity(D)),(-g)) # Check if root is within trust region if (norm(x) < delta): bnd1 = fun(x) xb1 = x else: # No solution bnd1 = inf xb1 = inf else:# No solution bnd1 = inf xb1 = inf # Case b) Trust-region active # Initial perturbation l = -l1 - sigma * delta + 1e-5 # Define nf2(l) to find roots def nf2(l): # Find x(l) xl = solve((LV + (l + sigma * delta) * identity(D)),dot(-UV.T,g)) # Calculate |xl|-delta (for newton stopping rule) xlmd = norm(xl) - delta # Calculate f(l) for p=-1 fl = 1 / norm(xl) - 1 / delta # Find x'(l) xlp = solve((LV + (l + sigma * delta) * identity(D)),(-xl)) # Calculate f'(l) for p=-1 flp = -dot(xl,xlp) * (dot(xl,xl) ** (-1.5)) # Calculate increment dl = fl / flp # Set Delta Delta = delta return xlmd, dl, Delta # Find x(l) xl = solve((LV + (l + sigma * delta) * identity(D)),dot(-UV.T,g)) # Check for hard case if (norm(xl) <= delta): #disp('Hard Case! TR Active') u = UV[:,il] # Find quadratic roots [alpha1, alpha2] = quadeq(dot(u, u), 2 * dot(xl,u), dot(xl,xl) - (delta * delta)) xbh1 = xl + alpha1 * u bndh1 = fun(xbh1) xbh2 = xl + alpha2 * u bndh2 = fun(xbh2) # Return minimum of bndh1 and bndh2 if (bndh1 < bndh2): bnd2 = bndh1 xb2 = xbh1 else: bnd2 = bndh2 xb2 = xbh2 else: # Run newton l = newton(nf2, l) # Given l, find x x = solve((H + (l + sigma * delta) * identity(D)),(-g)) bnd2 = fun(x) xb2 = x # Return minimum of bnd1 and bnd2 if (bnd1 < bnd2): bnd = bnd1 xb = xb1 + xc# since x -> x - xc else: bnd = bnd2 xb = xb2 + xc# since x -> x - xc return bnd, xb
y = math.cos(x) - x return y def f4(x): y = -math.sin(x) - 1 return y print("metodo bisseccao \n") print("iteracoes | ponto | erro") bisseccao.bisseccao(f3, 0, 1, 1e-4) print("\n----------------------------------\n") print("metodo de newton \n") print("iteracoes | ponto | erro") newton.newton(f3, f4, 3.1415 / 2, 1e-2) print("\n----------------------------------\n") print("metodo da eliminacao gauseana \n") matriz1 = [[1, 2, -3, 4, 7], [1, 2, 4, 7, -1], [2, 7, 1, 3, 5], [8, 3, 2, 1, 2]] print("matriz: ", matriz1) eliminacao_gauseana.eliminacao_gauseana(matriz1) print("\n----------------------------------\n") matriz2 = [[1, 1, 0, 3, 4], [2, 1, -1, 1, 1], [3, -1, -1, 2, -3], [-1, 2, 3, -1, 4]] print("metodo da decomposicao LU \n") LU, B = decomposicao_LU.decomposicao_LU(matriz2) print("matriz: ", matriz2) x = decomposicao_LU.resolver_LU(LU, B) print("vetor final: ", x)
def main(): import os import sys import numpy as np import numpy.linalg if (len(sys.argv) == 1): print "a0 = sys.argv[1], b0 = sys.argv[2]. alpha = a0*exp(-i*b0). " return -1 if (len(sys.argv) == 2): a0 = float(sys.argv[1]) b0 = 0.05 if (len(sys.argv) == 3): a0 = float(sys.argv[1]) b0 = float(sys.argv[2]) Greal = "G_cc_real.txt" Gimag = "G_cc_imag.txt" omega_n, G_real, G_imag = readFiles(Greal, Gimag) Niom = len(omega_n) N = 101 omega_lower = -8 omega_upper = -omega_lower domega = (omega_upper - omega_lower) / float(N) omega = np.zeros(N + 1) for i in range(N + 1): omega[i] = omega_lower + i * domega Nomega = len(omega) A_initial = np.zeros(Nomega) model = np.zeros(Nomega) for i in range(Nomega): model[i] = default.D(omega[i]) printFile.printFile(omega, model, "model.txt") if (not os.path.exists("A_initial.txt")): for i in range(len(A_initial)): A_initial[i] = default.D(omega[i]) printFile.printFile(omega, A_initial, "A_initial.txt") else: omega, A_initial = read_spectral("A_initial.txt") Nomega = len(omega) C_real = np.zeros((Niom, Niom)) C_imag = np.zeros((Niom, Niom)) ifile = open("CM_cc_real.txt", "r") for (index, string) in enumerate(ifile): a = string.split() rowIndex = int(a[0]) - 1 colIndex = int(a[1]) - 1 if (True): C_real[rowIndex, colIndex] = float(a[2]) ifile.close() ifile = open("CM_cc_imag.txt", "r") for (index, string) in enumerate(ifile): a = string.split() rowIndex = int(a[0]) - 1 colIndex = int(a[1]) - 1 if (True): C_imag[rowIndex, colIndex] = float(a[2]) ifile.close() eig = 0.01 ofile = open("eig.txt", "w") ofile.write(str(eig) + "\n") ofile.close() for i in range(Niom): C_real[i, i] = eig**2 C_imag[i, i] = eig**2 C_real_inv = numpy.linalg.inv(C_real) C_imag_inv = numpy.linalg.inv(C_imag) printFile.printMatrix(C_real_inv, "C_real_inv.txt") if (False): alpha = 1.0 function = f.f(alpha, G_real, G_imag, A_initial, omega_n, omega, C_real_inv, C_imag_inv) Jacobian = J.J(alpha, A_initial, omega_n, omega, C_real_inv, C_imag_inv) print function printFile.printMatrix(Jacobian, "J.txt") return 0 if (True): alpha = [] for i in range(30): alpha.append(a0 * np.exp(-i * b0)) ofile = open("alpha.txt", "a") for i in range(len(alpha)): A_updated = newton.newton(alpha[i], G_real, G_imag, omega_n, omega, A_initial, C_real_inv, C_imag_inv) if (nan.array_isnan(A_updated)): omega, A_initial = read_spectral("A_initial.txt") continue output = "A_updated_alpha_" + str(alpha[i]) + ".txt" printFile.printFile(omega, A_updated, output) os.system("cp " + output + " A_initial.txt") ofile.write(str(alpha[i]) + "\n") print "alpha = ", alpha[i] A_initial = A_updated ofile.close() else: alpha = 0.01 print "alpha = ", alpha A_updated = newton(alpha, G, omega_n, omega, A_initial, C_real_inv, C_imag_inv) if (nan.array_isnan(A_updated)): printFile.printFile(omega, A_updated, "A_updated_alpha_" + str(alpha) + ".txt") os.system("cp A_updated_alpha_" + str(alpha) + ".txt" + "A_initial.txt") return 0
print 'Solving the rootfinding with the Newton method' f0 = lambda x: (x[0]-2)**2+ (x[1]+1)**2+(x[2]+3)**2 #def f0(x): # return (x[0]-2)**2 def f1(x): return (x[1]+1)**2 def f2(x): return (x[2]+3)**2 fs=[f0,f1,f2] u=newton.newton(fs,[1.5,-0.5,-5.2]) print 'Solving f=0 with f(x,y,z)=(x-2)^2+(y+1)^2+(z+3)^2, initial point (x,y,z)=[1.5,-0.5,-5.2] and acceptance 1e-6' print u print 'the function value at this point is' print f0(u) #banana example f0 = lambda x: (1-x[0])**2+100*(x[1]-x[0]**2)**2 f1 = lambda x: (1-x[0])**2 fs=[f0,f1] u=newton.newton(fs,[-1.3,2.7]) print 'Solving Rosenbruck' print 'with f(x,y)=(1-x)^2+100*(y-x^2)^2, initial point (x,y)=[-1.3,2.7] and acceptance 1e-6' print u
print("Trying initial point %f..." % (x0)) x,err,res = iteration(f, g, x0, tol_err, tol_res, itmax) # in the final run, the approximate solutions approaches minus infinity... # now call the recursively programmed function x0 = 1.0 print("Trying initial point %f with recursion..." % (x0)) x,err,res = recursion(f, g, x0, tol_err, tol_res, itmax) # question 2 - Naming conflict with question 1. Comment Q1 and Uncomment code below to get answer. #def f(x): # return math.exp(x-x**2)-x/2.0-1.0836 def fp(x): return (1.0-2.0*x)*math.exp(x-x**2)-0.5 # residual and error tolerance, number of iterations tol_err = 1e-10 tol_res = 1e-10 itmax = 10 # initial point x0 = 1.0 # first try Newton iteration print("Calling Newton function...") x,err,res = newton(f,fp,x0,tol_res,tol_err,itmax) # that converges slowly, now try steffenson print("Calling Steffensen function...") x,err,res = steff(f,fp,x0,tol_err,tol_res,itmax)
def trsq(Lg, delta, xc, f, g): # import necessary functions from numpy import dot, inf from numpy.linalg import norm # our own functions from newton import newton # Define function to minimise fun = lambda x: f + dot(x,g) + (Lg / 2) * norm(x) ** 2 # n.b. x -> x - xc for convenience # Case a) Trust-region inactive # Quadratic order approx. solution xq1 = -g / Lg # Check if q. ord. root is within trust region if (norm(xq1) < delta): bndq1 = fun(xq1) xbq1 = xq1 else: # No solution bndq1 = inf xbq1 = inf # Case b) Trust-region active # Initial perturbation l = -Lg + 1e-5 # Define nfq(l) to find quadratic approx. roots def nfq(l): # Find x(l) xl = -g / (l + Lg) # Calculate |xl|-delta (for newton stopping rule) xlmd = norm(xl) - delta # Calculate f(l) for p=-1 fl = 1/norm(xl) - 1/delta # Find x'(l) xlp = g / ((l + Lg) ** 2) # Calculate f'(l) for p=-1 flp = -dot(xl,xlp) * (dot(xl,xl) ** (-1.5)) # Calculate increment dl = fl / flp # Set Delta Delta = delta return xlmd, dl, Delta # Run newton l = newton(nfq, l) # Given l, find xq2 xq2 = -g / (l + Lg) bndq2 = fun(xq2) xbq2 = xq2 # Return minimum of bndq1 and bndq2 if (bndq1 < bndq2): bnd = bndq1 xb = xbq1 + xc# since x -> x - xc else: bnd = bndq2 xb = xbq2 + xc# since x -> x - xc return bnd, xb
if False: """Figure 7, Example 3.20. """ random = False if random: na = 14 nb = 10 w = [1]*na + [0]*nb np.random.shuffle(w) else: #actual word used in the paper: w = [0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1] (w1,w2) = newton.getMinMax(w) wtext = ''.join(map(str,w1)) w2text = ''.join(map(str,w2)) #do plots of the gray region (P,S) = newton.newton(w,1) A = newton.getVertices(P,S) (Q,T) = newton.newton(w,0) B = newton.getVertices(Q,T) na = sum(w) nb = len(w)-na #Compute the control points points = np.sort(np.array(A+B), axis = 0) points= np.append(points, [[na,nb]],axis=0) newton._plotHull(P,S,na,nb,linecol='b--') newton._plotHull(Q,T,na,nb,linecol='r--') for i in xrange(len(points)-1): p = points[i] q = points[i+1] plt.plot((p[0],q[0]),(p[1],p[1]),'xkcd:dark lavender') plt.plot((p[0],p[0]),(p[1],q[1]),'xkcd:dark lavender')
from newton import newton, newton_aitken, newton_chord, newton_secant import numpy as np # Get machine precision eps = np.finfo(float).eps ################################################################################ print( '-----------------------------------------------------------------------') print(' f(x) = 2^x-cos(x+3)^2+exp(x+2)') f = lambda x: 2**x - (cos(x + 3))**2 + exp(x + 2) f1 = lambda x: 2**x * log(2) + 2 * cos(x + 3) * sin(x + 3) + exp(x + 2) print('> Newton plain') x, steps = newton(0, f, f1, eps, 1000, 1) print(" x = {}\n steps = {}\n error = {}".format(x, steps, abs(f(x)))) print('> Newton chords') x, steps = newton_chord(0, f, f1, eps, 1000) print(" x = {}\n steps = {}\n error = {}".format(x, steps, abs(f(x)))) print('> Newton secant') x, steps = newton_secant(0, f, f1, eps, 1000) print(" x = {}\n steps = {}\n error = {}".format(x, steps, abs(f(x)))) ################################################################################ print( '-----------------------------------------------------------------------') print(' f(x) = log(sin(x+4)-cos(x-1))-exp(3*x-x^2)') f = lambda x: log(sin(x + 4) - cos(x - 1)) - exp(3 * x - x**2) f1 = lambda x: (cos(x + 4) + sin(x - 1)) / (sin(x + 4) - cos(x - 1)) - exp(
return J def dhimmelblau(x): fx = 2*(2*x[0]*(x[0]**2 + x[1]-11) + x[0] + x[1]**2 - 7) fy = 2*(x[0]**2 + 2*x[1]*(x[0] + x[1]**2 - 7) + x[1] - 11) return np.array([fx, fy]) def himmelblau_jacobian(x): J = np.empty((2, 2)) J[0, 0] = 8*x[0]**2 + 4*(x[0]**2 + x[1] - 11) + 2 J[1, 0] = 4*(x[0] + x[1]) J[0, 1] = 4*(x[0] + x[1]) J[1, 1] = 8*x[1]**2 + 4*(x[1]**2 + x[0] - 7) + 2 return J rosenbrock = newton(np.array([8.1, 3.1])) sol_analytic, f_calls_analytic = rosenbrock.roots_analytic(drosenbrock, rosenbrock_jacobian, ['backtrack']) sol_numeric, f_calls_num = rosenbrock.roots_numeric(drosenbrock) print('Function test\t: Rosenbrock') print('##### NUMERIC JACOBIAN #####') print('Global min.\t= [ 1, 1]') print('Initial guess\t= [ 8, 3]') print('Min. found\t=', sol_numeric) print('Func. calls\t=', f_calls_num, '\n') print('##### ANALYTIC JACOBIAN #####') print('Global min.\t= [ 1, 1]') print('Initial guess\t= [ 8, 3]') print('Min. found\t=', sol_analytic) print('Func. calls\t=', f_calls_analytic)
def test(algorithm, method="gd"): plot_title = "" print("*********************") if method == "gd": print("Gradient descent") plot_title += "Gradient descent" else: print("Newton's method") plot_title += "Newton's method" print("*********************") plot_title += " / " if algorithm == "Newton": print("Newton-Rhapson") plot_title += "Newton-Rhapson" elif algorithm == "Quadint": print("Quadratic interpolation") plot_title += "Quadratic interpolation" elif algorithm == "Bisection": print("Bisection method") plot_title += "Bisection method" elif algorithm == "BasicArm": print("Basic Armijo") plot_title += "Basic Armijo" else: print("Cubic Armijo") plot_title += "Cubic Armijo" print("*********************\n") print( "1. Minimum of f(x, y) = x^2 + y^2 - 2xy, starting at (x, y) = (1, 0):\n" ) if method == "gd": (x, f, msg, x_v, f_v) = gradient_descent.gradient_descent( gun, [decimal.Decimal(1), decimal.Decimal(0)], algorithm, decimal.Decimal(0.005)) else: (x, f, msg, x_v, f_v) = newton.newton( gun, [decimal.Decimal(1), decimal.Decimal(0)], algorithm, decimal.Decimal(0.005)) print("The minimum is at (x, y) = (" + str(x[0]) + ", " + str(x[1]) + ")") print("f(x, y) =", f) print(msg) print("\n") # contour_plot(x_v, gun) print( "2. Minimum of f(x, y) = 10x^4 - 20x^2 y + 10y^2 + x^2 - 2x + 5, starting at (x, y) = (-1, 3):\n" ) if method == "gd": (x, f, msg, x_v, f_v) = gradient_descent.gradient_descent( hun, [decimal.Decimal(-1), decimal.Decimal(3)], algorithm, decimal.Decimal(0.005)) else: (x, f, msg, x_v, f_v) = newton.newton( hun, [decimal.Decimal(-1), decimal.Decimal(3)], algorithm, decimal.Decimal(0.005)) print("The minimum is at (x, y) = (" + str(x[0]) + ", " + str(x[1]) + ")") print("f(x, y) =", f) print(msg) print("\n") contour_plot(x_v, hun, plot_title) plot_energy(x_v, f_v, plot_title) print( "3. Minimum of f(x, y, z) = x^2 + 2y^2 + 2z^2 + 2xy + 2yz, starting at (x, y, z) = (2, 4, 10):\n" ) if method == "gd": (x, f, msg, x_v, f_v) = gradient_descent.gradient_descent( pun, [decimal.Decimal(2), decimal.Decimal(4), decimal.Decimal(10)], algorithm, decimal.Decimal(0.005)) else: (x, f, msg, x_v, f_v) = newton.newton( pun, [decimal.Decimal(2), decimal.Decimal(4), decimal.Decimal(10)], algorithm, decimal.Decimal(0.005)) print("The minimum is at (x, y, z) = (" + str(x[0]) + ", " + str(x[1]) + "," + str(x[2]) + ")") print("f(x, y, z) =", f) print(msg) print("\n")
def trsq(Lg, delta, xc, f, g): # import necessary functions from numpy import dot, inf from numpy.linalg import norm # our own functions from newton import newton # Define function to minimise fun = lambda x: f + dot(x, g) + (Lg / 2) * norm(x)**2 # n.b. x -> x - xc for convenience # Case a) Trust-region inactive # Quadratic order approx. solution xq1 = -g / Lg # Check if q. ord. root is within trust region if (norm(xq1) < delta): bndq1 = fun(xq1) xbq1 = xq1 else: # No solution bndq1 = inf xbq1 = inf # Case b) Trust-region active # Initial perturbation l = -Lg + 1e-5 # Define nfq(l) to find quadratic approx. roots def nfq(l): # Find x(l) xl = -g / (l + Lg) # Calculate |xl|-delta (for newton stopping rule) xlmd = norm(xl) - delta # Calculate f(l) for p=-1 fl = 1 / norm(xl) - 1 / delta # Find x'(l) xlp = g / ((l + Lg)**2) # Calculate f'(l) for p=-1 flp = -dot(xl, xlp) * (dot(xl, xl)**(-1.5)) # Calculate increment dl = fl / flp # Set Delta Delta = delta return xlmd, dl, Delta # Run newton l = newton(nfq, l) # Given l, find xq2 xq2 = -g / (l + Lg) bndq2 = fun(xq2) xbq2 = xq2 # Return minimum of bndq1 and bndq2 if (bndq1 < bndq2): bnd = bndq1 xb = xbq1 + xc # since x -> x - xc else: bnd = bndq2 xb = xbq2 + xc # since x -> x - xc return bnd, xb
from bisect import bisect from newton import newton import numpy as np # Get machine precision as tolx tolx = np.finfo(float).eps print('f(x) = x^3 - 5x') f = lambda x: x**3 - 5 * x f1 = lambda x: 3 * x**2 - 5 print('> Try with Newton') x, steps = newton(1, f, f1, tolx, 1000, 1) print(" x = {}\n steps = {}\n error = {}".format(x, steps, abs(f(x)))) if abs(f(x)) > tolx * abs(f1(x)): print('> Non-convergence detected, fallback to Bisection') x, steps = bisect(-10, 1, f, tolx) print(" x = {}\n steps = {}\n error = {}".format(x, steps, abs(f(x))))
def test_sin(self): print("sin") x=newton.newton(sin,cos,0.5,1e-8) print(sin(x)) assert(norm(sin(x)) < 1e-8)
import time pl.rc('text', usetex=True) pl.rc('font', family='Bookman') g = (3.45,-5.8,-7.2,2.17) tol = (10e-4,10e-5, 10e-7,10e-12) nmax = (10,50,100,10) X = [] Y = [] for i in range (0, 4): t0 = time.clock() for j in range (0, 10000): sol = newton.newton (g[i], tol[i], nmax[i], 0) tf = time.clock() - t0 X = X + [i+1] Y = Y + [tf] print Y pl.plot(X,Y,'mp--') pl.title(r'Costo computacional del m\'etodo de Newton') pl.xlabel(r'Cantidad de iteraciones (en decenas de miles)') pl.ylabel(r'Tiempo de CPU (segundos)') pl.xlim(0.5, 4.5) pl.ylim(0, 0.2) pl.savefig("CPUtime.eps", dpi=72)
def test_polynomial(self): def fun(x): return x**2-1 result = newton(fun, lambda x: 2*x, 2.) assert(abs(fun(result)) < 1e-8)
def test_sin(self): assert(abs(sin(newton(sin, cos, 0.5))) < 1e-8)
def dhimmelblau(x): fx = 2 * (2 * x[0] * (x[0]**2 + x[1] - 11) + x[0] + x[1]**2 - 7) fy = 2 * (x[0]**2 + 2 * x[1] * (x[0] + x[1]**2 - 7) + x[1] - 11) return np.array([fx, fy]) def himmelblau_jacobian(x): J = np.empty((2, 2)) J[0, 0] = 8 * x[0]**2 + 4 * (x[0]**2 + x[1] - 11) + 2 J[1, 0] = 4 * (x[0] + x[1]) J[0, 1] = 4 * (x[0] + x[1]) J[1, 1] = 8 * x[1]**2 + 4 * (x[1]**2 + x[0] - 7) + 2 return J rosenbrock = newton(np.array([8.1, 3.1])) sol_bt, f_calls_bt = rosenbrock.roots_analytic(drosenbrock, rosenbrock_jacobian, ['backtrack']) sol_quad, f_calls_quad = rosenbrock.roots_analytic(drosenbrock, rosenbrock_jacobian, ['quadratic', frosenbrock]) print('Function test\t: Rosenbrock') print('##### BACKTRACK LINESEARCH #####') print('Global min.\t= [ 1, 1]') print('Initial guess\t= [ 8, 3]') print('Min. found\t=', sol_bt) print('Func. calls\t=', f_calls_bt, '\n') print('##### GOLDEN SECTION QUADRATIC INTERPOLATION #####')
import half_div import newton from test_env import get_keys, build_plot from termcolor import cprint keys = get_keys() if keys.get("--a"): a = float(keys.get("--a")) else: print('Введите a:') a = float(input()) if keys.get("--b"): b = float(keys.get("--b")) else: print('Введите b:') b = float(input()) if keys.get("--eps"): eps = float(keys.get("--eps")) else: print('Введите eps:') eps = float(input()) half_div_res = half_div.half(a, b, eps) newton_res = newton.newton(a, b, eps) print('-------------------------------------Results-------------------------------------') cprint(f"1. Half dividing: x = {half_div_res[0]}, f(x) = {half_div_res[1]:.10f}, {half_div_res[2]} iterations", 'yellow') cprint(f"2. Newton: x = {newton_res[0]}, f(x) = {newton_res[1]:.10f}, {newton_res[2]} iterations", 'yellow') print('---------------------------------------------------------------------------------')