def unit_lengendre_roots(order, tol=1e-15, output=True): roots = [] print("Finding roots of Legendre polynomial of order ", order) # The polynomials are alternately even and odd functions # so evaluate only half the number of roots for i in range(1, int(order / 2) + 1): # initial guess, x0, for ith root # the approximate values of the abscissas. # these are good initial guesses x0 = np.cos(np.pi * (i - 0.25) / (order + 0.5)) # call newton to find the roots of the legendre polynomial Ffun, Jfun = L(order), dL(order) ri, _ = newton(Ffun, Jfun, x0) roots.append(ri) # use symetric properties to find remmaining roots # the nodal abscissas are computed by finding the # nonnegative zeros of the Legendre polynomial pm(x) # with Newton’s method (the negative zeros are obtained from symmetry). roots = np.array(roots) # even. no center if order % 2 == 0: roots = np.concatenate((-1.0 * roots, roots[::-1])) # odd. center root is 0.0 else: roots = np.concatenate((-1.0 * roots, [0.0], roots[::-1])) return roots
def unit_lengendre_roots(order, tol=1e-15, output=True): roots = [] print("Finding roots of Legendre polynomial of order ", order) # The polynomials are alternately even and odd functions # so evaluate only half the number of roots for i in range(1, int(order / 2) + 1): # initial guess, x0, for ith root x0 = np.cos(np.pi * (i - 0.25) / (order + 0.5)) # call newton to find the roots of the legendre polynomial Ffun, Jfun = L(order), dL(order) ri, _ = newton(Ffun, Jfun, x0) roots.append(ri) # use symetric properties to find remmaining roots roots = np.array(roots) # even. no center if order % 2 == 0: roots = np.concatenate((-1.0 * roots, roots[::-1])) # odd. center root is 0.0 else: roots = np.concatenate((-1.0 * roots, [0.0], roots[::-1])) return roots
def pilihan(a, b, c, pil): if (pil == "1"): print("Metode Tabel") tabel(a, b, c) elif (pil == "2"): print("Metode biseksi") biseksi(a, b, c) elif (pil == "3"): print("Metode regula falsi") regula(a, b, c) elif (pil == "4"): print("Metode Newton Raphson") newton(a, b, c) elif (pil == "5"): print("Metode Secant") secant(a, b, c)
def timestep(s0, OW, OW0, ref, param): def F(s): return momentum(s, s0, OW, OW0, ref, param) def gradF(ds, s): return jacobian_momentum(ds, s, OW, ref, param) return newton(F, gradF, s0)
def unit_lobatto_nodes(order, tol=1e-15, output=True): roots = [] print( "Finding roots of the derivative of the Legendre polynomial of order ", order) # The polynomials are alternately even and odd functions # so evaluate only half the number of roots # order - 1, lobatto polynomial is derivative of legendre polynomial of order n-1 order = order - 1 for i in range(1, int(order / 2) + 1): # initial guess, x0, for ith root # the approximate values of the abscissas. # these are good initial guesses #x0=np.cos(np.pi*(i-0.25)/(order+0.5)) x0 = np.cos(np.pi * (i + 0.1) / (order + 0.5)) # not sure why this inital guess is better # call newton to find the roots of the lobatto polynomial #Ffun, Jfun = dL(order-1), ddL(order-1) Ffun, Jfun = dL(order), ddL(order) ri, _ = newton(Ffun, Jfun, x0) roots.append(ri) # remove roots close to zero cleaned_roots = [] tol = 1e-08 for r in roots: if abs(r) >= tol: cleaned_roots += [r] roots = cleaned_roots # use symetric properties to find remmaining roots # the nodal abscissas are computed by finding the # nonnegative zeros of the Legendre polynomial pm(x) # with Newton’s method (the negative zeros are obtained from symmetry). roots = np.array(roots) # add -1 and 1 to tail ends # check parity of order + 1 # even. no center #if order % 2==0: if (order + 1) % 2 == 0: roots = np.concatenate(([-1.0], -1.0 * roots, roots[::-1], [1.0])) # odd. center root is 0.0 else: roots = np.concatenate( ([-1.0], -1.0 * roots, [0.0], roots[::-1], [1.0])) return roots
[df_dx1_dx2(x), 200]]) def print_error(i, direction, alpha, x): opt = f(array([1,1])) print("%d, %.20f" % (i, f(x)-opt)) def print_gradient(i, direction, alpha, x): print("%d, %.20f" % (i, linalg.norm(fd(x)))) def print_all(i, direction, alpha, x): print("iteration %d: \t direction: %s \t alpha: %.7f \t x: %s" % (i, ["%.7f" % _ for _ in direction], alpha, ["%.7f" % _ for _ in x])) x = array([0, 0]) precision = 10e-6 max_iterations = 100 callback = print_all print("steepest descent:") steepest_descent(f, fd, x, max_iterations, precision, callback) print("\nnewton:") newton(f, fd, fdd, x, max_iterations, precision, callback) print("\nquasi newton:") quasi_newton(f, fd, x, max_iterations, precision, callback) print("\nconjugate gradient:") conjugate_gradient(f, fd, x, max_iterations, precision, callback)
from bisection import * from newton import * from secant import * print("-------- START ---------") print("Bisection") f = "x*sin(x)-1" a = 0 b = 2 tol = 0.001 print(bisection(f, a, b, tol)) print("\nNewton-Raphson") f = "exp(-x)-x" x0 = 0 tol = 0.0001 maxIter = 20 print(newton(f, x0, tol, maxIter)) print("\nSecant") f = "x^3-3*x+2" x0 = -2.6 x1 = -2.4 tol = 0.0001 maxIter = 20 print(secant(f, x0, x1, tol, maxIter)) print("-------- END ----------")
# ------------------------------------------------------------ # buscar raices a, b = rootSearch(f, -10, 10, 0.5, printText=1) # bisection print "\nMetodo Bisection" print bisection(f, a, b, switch=1) # brent print "\nMetodo Brent" print brent(f, a, b, printText=0) # secant print "\nMetodo Secant" print secant(f, a, b, printText=0) # newton print "\nMetodo de Newton" print newton(f, d1f, a, printText=0) # newton raphson print "\nMetodo de Newton-Raphson" print newtonRaphson(f, d1f, a, b, printText=0) # posicion falsa print "\nMetodo Posicion Falsa o Falsa Regla" print falseRule(f, a, b, printText=0) # punto fijo print "\nMetodo Punto Fijo" print fixedPoint(g, a, printText=0) # steffensen print "\nMetodo Steffensen" print steffensen(g, a, printText=0) # ridder print "\nMetodo de Ridder" print ridder(f, a, b, printText=0)
output = True maxit = 50 Satol = 1e-6 Srtol = 1e-6 Ratol = 1e-13 Rrtol = 1e-13 x0 = [-5, 2, 5] for num in x0: divider() #-------------------------------------------------------------------------- print(" Newton:") # Start computation time tstart = time.time() x1, its1 = newton(f, J, num, maxit, Srtol, Satol, Rrtol, Ratol, output) # Stop time ttot = time.time() - tstart # Record solution print(" final solution = ", x1, ", residual = ", np.abs(f(x1)), ", time = ", ttot, ", its = ", its1) #-------------------------------------------------------------------------- print(" Steffensen:") # Start computation time tstart = time.time() x2, its2 = steffensen(f, num, maxit, Srtol, Satol, Rrtol, Ratol, output) # Stop time ttot = time.time() - tstart
Compute the function evaluted at the vector x. use: F = f(x) :param x: vector x of length 3. :returns: vector of length 3, or function from question 4 evaluted at x. """ f0 = lambda x: x[0]*(1 + 0.004) + x[1]*x[2]*(-1000) -1 f1 = lambda x: x[0]*(-0.004) + x[1] + x[1]**2*(30) + x[1]*x[2]*1000 f2 = lambda x: x[1]**2*(-30) + x[2] return np.array([f0(x), f1(x), f2(x)]) input("Press Enter to continue...") # call solvers on this problem for i in range(ntols): print("\n Srtol = ", Srtols[i], ", Satol = ", Satols[i],", Rrtol = ", Rrtols[i], ", Ratol = ", Ratols[i], ":") print(" Newton:") tstart = time.time() x, its = newton(f, J, x0, maxit, Srtols[i], Satols[i], Rrtols[i], Ratols[i], True) ttot = time.time() - tstart print(" final solution = ", x, ", residual = ", np.abs(f(x)), ", time = ", ttot, ", its = ", its) print(" Picard:") tstart = time.time() x, its = picard(f, J(x0), x0, maxit, Srtols[i], Satols[i], Rrtols[i], Ratols[i], True) ttot = time.time() - tstart print(" final solution = ", x, ", residual = ", np.abs(f(x)), ", time = ", ttot, ", its = ", its)
elif f1 == "2" and f2 == "2": Y = absolute(absolute(X, a2, b2), a1, b1) elif f1 == "2" and f2 == "3": Y = absolute(trigonometric(X, a2, b2), a1, b1) elif f1 == "3" and f2 == "1": Y = trigonometric(polynomial(X, factors2), a1, b1) elif f1 == "3" and f2 == "2": Y = trigonometric(absolute(X, a2, b2), a1, b1) elif f1 == "3" and f2 == "3": Y = trigonometric(trigonometric(X, a2, b2), a1, b1) # Nasza interpolacja xs = np.linspace(left, right, 1000, endpoint=True) ys = [] for x in xs: ys.append(newton(X, Y, x)) # Rzeczywisty wykres funkcji xs2 = np.linspace(left, right, 1000, endpoint=True) ys2 = [] for x in xs2: if (func == "1"): ys2.append(horner(x, factors)) if (func == "2"): ys2.append(absolute(x, a, b)) if (func == "3"): ys2.append(trigonometric(x, a, b)) if (func == "4"): if f1 == "1" and f2 == "1": ys2.append(polynomial(polynomial(x, factors2), factors1)) elif f1 == "1" and f2 == "2":
:param x: vector x of length 3. :returns: vector of length 3, or function from question 4 evaluted at x. """ f0 = lambda x: x[0]*(1 + 0.004) + x[1]*x[2]*(-1000) -1 f1 = lambda x: x[0]*(-0.004) + x[1] + x[1]**2*(30) + x[1]*x[2]*1000 f2 = lambda x: x[1]**2*(-30) + x[2] return np.array([f0(x), f1(x), f2(x)]) for x_initial in initial_guesses: input("Press Enter to continue...") print("Initial guess x: %s\n\n" % x_initial) # call solvers on this problem for i in range(ntols): print("\n Srtol = ", Srtols[i], ", Satol = ", Satols[i],", Rrtol = ", Rrtols[i], ", Ratol = ", Ratols[i], ":") print(" Newton:") tstart = time.time() x, its = newton(f, J, x_initial, maxit, Srtols[i], Satols[i], Rrtols[i], Ratols[i], True) ttot = time.time() - tstart print(" final solution = ", x, ", residual = ", np.abs(f(x)), ", time = ", ttot, ", its = ", its) print(" Picard:") tstart = time.time() x, its = picard(f, J(x_initial), x_initial, maxit, Srtols[i], Satols[i], Rrtols[i], Ratols[i], True) ttot = time.time() - tstart print(" final solution = ", x, ", residual = ", np.abs(f(x)), ", time = ", ttot, ", its = ", its)
XsCheb = chebyshev(50, -180, 180) senoIE = list(map(seno, XsIE)) senoCheb = list(map(seno, XsCheb)) # Definição dos pontos a serem usados para os testes testes = igualmenteEspacados(500, -180, 180) senoTeste = list(map(seno, testes)) ###################################################################################### ''' Valores igualmente Espaçados ''' # Cálculos de interpolação com função Seno lagrangeIE = lagrange(testes, XsIE, senoIE) baricentricoIE = baricentrico(testes, XsIE, senoIE) newtonIE = newton(testes, XsIE, senoIE) nevilleIE = neville(testes, XsIE, senoIE) # Gráfico 1 : Resultados da interpolação em todos os algoritmos com função seno plt.figure(1) plt.subplot(211) plt.plot(testes, lagrangeIE, color='green') plt.plot(testes, baricentricoIE, color='blue') plt.plot(testes, newtonIE, color='red') plt.plot(testes, nevilleIE, color='aqua') plt.plot(testes, senoTeste, color='yellow') plt.title('Valores igualmente espaçados') plt.ylabel('Valores Calculados') # Gráfico 2: Erros entre os algoritmos e os valores esperados
Satol = 10**(-5) Srtol = 10**(-10) # unspecified Rrtol = 10**(-5) Ratol = 10**(-10) # interp_representation_error interp_representation_error = lambda Gfun, x_final: abs(Gfun(x_final) - x_final) # run trials for Gfun_name, Gfun in fixed_point_functions.items(): Gfun = fixed_point_functions[Gfun_name] x = initial_guesses[Gfun_name] # convert Gfun to parameters useful in newtons method newton, # newton(Ffun, Jfun, x, maxit, Srtol, Satol, Rrtol, Ratol, output) Ffun, Jfun = root_finding_form(Gfun) # find x* x_target = newton(Ffun, Jfun, x, maxit, Srtol, Satol, Rrtol, Ratol, output=SHOW_OUTPUT) # display interp_representation_error error = interp_representation_error(Gfun, x) logger.info("\n\nFinal fixed point target error using newton interpolating polynomial in place of Ffun.\n \ \n\tFunction name: %s, \n\n\t\t |Gfun(x) - x| = %s.\n" % (Gfun_name, error))
from numpy import * from newton import * def g(x): return float(x)**2-1 def dg(x): return 2*float(x) x0 = 3 eps = 1e-3 y = newton (g, dg, x0, eps) print y
# Primero se generan datos para la funcion # esta informacion es la que pueden cambiar a su antojo dimension_matriz_Q = 10 iteracion_maxima_newton = 100 iteracion_maxima_gradiente = 100 epsilon = 0.1 # ******* NO TOCAR NADA DE AQUI PARA ABAJO ******** # (si deseas probar un metodo y no ambos comenta la linea 31 o 34, respectivamente) # Para que siempre genere los mismos numeros al azar np.random.seed(1) # En base a su informacion entregada como input de aqui en adelante el programa # se corre solo Q, c = generar_datos(dimension_matriz_Q) # Se ocupa el vector de "unos" como punto de inicio # (notar el salto que pega) de la iteracion 1 a la 2 el valor objetivo # -- Queda a tu eleccion que vector ingresar como solucion para la iteracion 1 -- x0 = np.random.rand(dimension_matriz_Q, 1) # Maximo de iteraciones para newton (y asi no quede un loop infinito) newton(Q, c, x0, epsilon, iteracion_maxima_newton) # Maximo de iteraciones para gradiente (y asi no quede un loop infinito) #gradiente(Q, c, x0, epsilon, iteracion_maxima_gradiente)
#allLinearAlgoritms from limites import * from utils import * f = f3 g = g2c from pontoFixo import * from bissecao import * from newton import * from cordaSimples import * show = False intervalo1 = trocaDeSinal(f, True) intervalo2 = limites(f) print('Troca de sinal encontrou {}'.format(intervalo1) ) print('Limites encontrou {}'.format(intervalo2) ) print('') bissect(f, intervalo1[0], intervalo1[1], 0.00001, show) cordaSimples(f, intervalo1[0], intervalo1[1], 0.00001, show) pontoFixo(f, g, intervalo1[0], 0.00001, show) newton(f, intervalo1[0], 0.00001, show)
def answer(self): I1 = newton(self.Fx.get(), self.derivative.get(), int(self.nIter.get()), float(self.tolerance.get()), float(self.x0.get())) self.label["text"] = I1.newton1()
# -*- decoding: utf-8 -*- from MinimosCuadrados import * from Lector import * from GaussJordan import * from newton import * import math lec = Lector("archivo.txt") m = lec.lee() print "Hola, este programa obtiene una función polinomial a partir de una función tabular" newt = newton(m) a = newt.intervalo if a != -1: print "Los incrementos no son constantes, favor de ingresar el orden deseado" orden = int(raw_input("Favor de introducir el orden")) if orden > len(m) - 1: orden = len(m) - 1 minimos = MinimosCuadrados(orden) print "Las ecuaciones: " var = minimos.formatearEcuaciones() matriz = minimos.transfomaEcuaciones(var) for x in xrange(0,len(var)): print var[x].printPolinomio() gauss = GaussJordan(matriz) m = gauss.GaussJordan(matriz, orden)
print '...' print 'Iteration 8:' X8 = newton2d(eqn1,eqn2, X7) print X8 print 'Error: ', infinTol(X7,X8) print '...' print 'Iteration 9:' X9 = newton2d(eqn1,eqn2, X8) print X9 print 'Error: ', infinTol(X8,X9) print print '***Solving by using the one dimensional method***' y = oneMtwo(1) print 'For this case f(x) is first equation minus the second equation' print 'for the first iterations we will guess the x value is 1, which makes the f(1)= ', y x1 = newton(oneMtwo,dOneMdTwo,1) print 'which gives us the x1: ', x1 print print 'using the infinity norm our error is:' print singleTol(1,x1) print '...' print 'Iteration 2:' print 'f(x1) = ', oneMtwo(x1) x2 = newton(oneMtwo,dOneMdTwo,x1) print 'x2 = ', x2 print 'Error: ', singleTol(x1,x2) print '...' print 'Iteration 3:' print 'f(x2) = ', oneMtwo(x2) x3 = newton(oneMtwo,dOneMdTwo,x2) print 'x3 = ', x3
def jacobi(x): J = np.array([[2 * x[0][0], 2 * x[1][0]], [x[1][0] - 3, x[0][0] + 1]]) return J def newton(e, N, x): k = 0 err = 1 while k < N and err > e: d = np.linalg.solve(jacobi(x), -f(x)) err = np.linalg.norm(d) x = x + d print( k, 'x:', x, ) k = k + 1 return x if __name__ == "__main__": x0 = np.array([[6], [5]]) N = 10 e = 0.001 B = np.eye(2) ans = newton(e, N, x0) print(ans)
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
# -*- decoding: utf-8 -*- from MinimosCuadrados import * from Lector import * from GaussJordan import * from newton import * import math men = True; while(men): lec = Lector("archivo.txt") m = lec.lee() print "Hola, este programa obtiene una función polinomial a partir de una función tabular" newt = newton(m) a = newt.intervalo if a != -1: print "Los incrementos no son constantes, favor de ingresar el orden deseado" orden = int(raw_input("Favor de introducir el orden: ")) if orden > len(m) - 1: orden = len(m) - 1 minimos = MinimosCuadrados(orden) print "Las ecuaciones: " var = minimos.formatearEcuaciones() matriz = minimos.transfomaEcuaciones(var) for x in xrange(0,len(var)): print var[x].printPolinomio()
float(s) return True except ValueError: return False menu = True; print ' Hola, favor de introducir los comandos que desee:' print ' Para interpopacion/extrapolacion exacta, escribe --> "1"' print ' Para interpopacion/extrapolacion aproximada, escribe --> "2"' print ' Escribe "salir" para salir del programa' print "" #Creación de clase lector con la direscción del archivo a leer lector = Lector("datos.txt") #Creación de objeto newton FuncionNewton = newton(lector.lee()) FuncionLagrange = Lagrange(lector.lee()) #validar entrada para ver si se puede ejecutar newton #print str(validarNewton) while menu: opcion = raw_input(">>>") if opcion == '1': inpu = (raw_input("introduce el valor a calcular: ")) if is_number(inpu): FuncionLagrange.formula(float(inpu)) else:
@author: sbroad """ from logistic import * from newton import * # investigate the basin of attraction for each of several logistic parameters init = np.random.random(200) plt.close(1) plt.figure(1) for a in [(0.5,'b.'), (1.5,'g.'), (2.5,'r.'), (3.2,'k.')]: attr = [ logistic(x, a[0], n=100) for x in init] plt.plot(init, attr,a[1],label=r'$\lambda=%.2f$' % (a[0])) plt.ylim(ymin=0,ymax=1) plt.legend(loc='best') # investigate the basin of attraction for roots of sin(x) init = np.random.random(200)*10 plt.close(2) plt.figure(2) quad = (lambda x: x**2-6*x+8, 'b.', r'$x^2-5x+4$') trig = (lambda x: sin(x/2.), 'g.', r'$\sin(\pi x)$') tran = (lambda x: log(x),'r.', r'$\log x$') for b in [quad, trig, tran]: attr = [newton(b[0], x, n=100) for x in init] plt.plot(init, attr, b[1], label=b[2]) plt.legend(loc='best')