Exemplo n.º 1
0
def complex_to_lattice(z, d, a, N=None):
    """
    Given an algebraic number z of degree d, set of up the
    lattice which tries to express a in terms of powers of z,
    where the last two colmns are weighted by N.
    """
    if N is None:
        N = ZZ(2)**(z.prec() - 10)
    nums = [z**k for k in range(d)] + [a]
    last_columns = [[round(N * real_part(x)) for x in nums],
                    [round(N * imag_part(x)) for x in nums]]
    A = matrix(identity_matrix(len(nums)).columns() + last_columns)
    return A.transpose()
Exemplo n.º 2
0
def linear_dependencies(m, err_dec=20, round_dec=10):

    import numpy as np
    from sage.all import matrix, round

    W = m.numpy()
    (nr, nc) = W.shape

    d = np.identity(nc)

    if not W[:, 0].any():
        d[0, 0] = 0.0

    for i in range(1, nc):
        if not W[:, i].any():
            d[i, i] = 0.0
        else:
            A = W[:, :i]
            b = W[:, i:i + 1]
            Api = np.linalg.pinv(A)
            x = np.dot(Api, b)
            err = np.linalg.norm(b - np.dot(A, x))
            if err < 10.0**(-err_dec):
                d[:, i:i + 1] = np.vstack(
                    (x.reshape(i, 1), np.zeros((nc - i, 1))))
                W[:, i:i + 1] = np.zeros((nr, 1))

    return matrix(d).apply_map(lambda i: round(i, round_dec))
Exemplo n.º 3
0
def crack_when_pq_close(n):
    t = Integer(ceil(sqrt(n)))
    while True:
        k = t**2 - n
        if k > 0:
            s = Integer(int(round(sqrt(t**2 - n))))
            if s**2 + n == t**2:
                return t + s, t - s
        t += 1
Exemplo n.º 4
0
def vect_to_sym(v):
    n = ZZ(round((-1+sqrt(1+8*len(v)))/2))
    M = matrix(n)
    k = 0
    for i in range(n):
        for j in range(i, n):
            M[i,j] = v[k]
            M[j,i] = v[k]
            k=k+1
    return [[int(M[i,j]) for i in range(n)] for j in range(n)]
Exemplo n.º 5
0
def test_real_quadratic(minp=1,maxp=100,minwt=2,maxwt=1000):
    for p in prime_range(minp,maxp):
        if p%4==1:
            print "p = ", p
            gram=Matrix(ZZ,2,2,[2,1,1,(1-p)/2])
            M=VectorValuedModularForms(gram)
            if is_odd(minwt):
                minwt=minwt+1
            for kk in range(minwt,round(maxwt/2-minwt)):
                k = minwt+2*kk
                if M.dimension_cusp_forms(k)-dimension_cusp_forms(kronecker_character(p),k)/2 != 0:
                    print "ERROR: ", k, M.dimension_cusp_forms(k), dimension_cusp_forms(kronecker_character(p),k)/2
                    return False
    return true
Exemplo n.º 6
0
def EvalRom_Funcion(funcion, h, n, inferior):
    """Funcion que evaluara funcion para aplicar la regla del trapecio"""
    # Crea la matriz que contendra los valores de 'x' y 'y'
    matDatos = np.empty(((n + 1), 2), dtype = 'f')

    # Primero llena la primera columna con los valores de 'x'
    for priCol in range(n + 1):
        matDatos[priCol, 0] = round(inferior + (h * priCol), 6)

    # Evalua la funcion en cada punto de 'x' y lo almacena en la segunda columna
    for segCol in range(n + 1):
        matDatos[segCol, 1] = funcion.subs(x = matDatos[segCol, 0])

    # Regresa la matriz con los datos que se usaran aplicando la regla del trapecio
    return matDatos
Exemplo n.º 7
0
def test_real_quadratic(minp=1, maxp=100, minwt=2, maxwt=1000):
    for p in prime_range(minp, maxp):
        if p % 4 == 1:
            print "p = ", p
            gram = Matrix(ZZ, 2, 2, [2, 1, 1, (1 - p) / 2])
            M = VectorValuedModularForms(gram)
            if is_odd(minwt):
                minwt = minwt + 1
            for kk in range(minwt, round(maxwt / 2 - minwt)):
                k = minwt + 2 * kk
                if M.dimension_cusp_forms(k) - dimension_cusp_forms(
                        kronecker_character(p), k) / 2 != 0:
                    print "ERROR: ", k, M.dimension_cusp_forms(
                        k), dimension_cusp_forms(kronecker_character(p), k) / 2
                    return False
    return true
Exemplo n.º 8
0
def symround(expr, ndigits=0):
    if hasattr(expr, 'operator') and expr.operator():
        opds = map(lambda y: symround(y, ndigits=ndigits), expr.operands())
        if len(opds) == 1:
            return expr.operator()(opds[0])
        else:
            r = opds[0]
            for i in xrange(1, len(opds)):
                r = expr.operator()(r, opds[i])
            return r
    try:
        from sage.all import round
        r = round(expr, ndigits=ndigits)
        if r == expr: return expr
        else: return r
    except TypeError:
        return expr
Exemplo n.º 9
0
def test_jacobi(index=1,minwt=4,maxwt=100,eps=-1):
    m=index
    gram=Matrix(ZZ,1,1,[-eps*2*m])
    M=VectorValuedModularForms(gram)
    if is_odd(minwt):
        minwt=minwt+1
    for kk in range(0,round(maxwt/2-minwt)+2):
        k = minwt+2*kk+(1+eps)/2
        print "Testing k = ", k
        if eps==-1:
            dimJ=dimension_jac_forms(k,m,-1)
            dimV=M.dimension(k-1/2)
        else:
            dimJ=dimension_jac_cusp_forms(k,m,1)
            dimV=M.dimension_cusp_forms(k-1/2)
        if dimJ-dimV != 0:
            print "ERROR: ", k, dimJ, dimV
            return False
    return true
Exemplo n.º 10
0
def test_jacobi(index=1, minwt=4, maxwt=100, eps=-1):
    m = index
    gram = Matrix(ZZ, 1, 1, [-eps * 2 * m])
    M = VectorValuedModularForms(gram)
    if is_odd(minwt):
        minwt = minwt + 1
    for kk in range(0, round(maxwt / 2 - minwt) + 2):
        k = minwt + 2 * kk + (1 + eps) / 2
        print "Testing k = ", k
        if eps == -1:
            dimJ = dimension_jac_forms(k, m, -1)
            dimV = M.dimension(k - 1 / 2)
        else:
            dimJ = dimension_jac_cusp_forms(k, m, 1)
            dimV = M.dimension_cusp_forms(k - 1 / 2)
        if dimJ - dimV != 0:
            print "ERROR: ", k, dimJ, dimV
            return False
    return true
Exemplo n.º 11
0
def test_jacobi(index=1, minwt=4, maxwt=100, eps=-1):
    m = index
    gram = Matrix(ZZ, 1, 1, [-eps * 2 * m])
    M = VectorValuedModularForms(gram)
    if is_odd(minwt):
        minwt = minwt + 1
    for kk in range(0, round(maxwt / QQ(2) - minwt) + 2):
        k = minwt + 2 * kk + (1 + eps) / 2
        print("Testing k = {0}".format(k))
        if eps == -1:
            dimJ = dimension_jac_forms(k, m, -1)
            dimV = M.dimension(k - QQ(1) / QQ(2))
        else:
            dimJ = dimension_jac_cusp_forms(k, m, 1)
            dimV = M.dimension_cusp_forms(k - QQ(1) / QQ(2))
        if dimJ - dimV != 0:
            print("ERROR: {0},{1},{2}".format(k, dimJ, dimV))
            return False
    return True
Exemplo n.º 12
0
def Interpolacion_Diferencias_Divididas(nombre):
    """Funcion que construira el Polinomio Interpolante de Newton"""
    # Primero llena una matriz con los datos contenidos en el documento de texto
    matDatos = LLenar_Matriz_Datos(nombre)
    # Une la matriz 'matDatos' con otra matriz de ceros de orden n x n - 1, donde n es el numero de datos
    matDatos = np.copy(
        np.append(matDatos,
                  np.zeros((matDatos.shape[0], (matDatos.shape[0] - 1)),
                           dtype='f'),
                  axis=1))

    # Bucle que se repetira hasta calcular la ultima diferencia dividida posible
    # Este contador se utilizara para indexar los valores de las columnas de 'matDatos' [Burden p. 124]
    for cont1 in range(1, matDatos.shape[0]):
        #  Este contador se utilizara para indexar los valores de las filas de 'matDatos'
        cont2 = 0
        # Bucle que calcula los elementos de la tabla de diferencias divididas
        for elemRengl in range(cont1, matDatos.shape[0]):
            # La variable 'elemRengl' va a indexar la fila del valor de x que se va a usar en el minuendo (primer elemento de la resta)
            matDatos[cont2, (
                cont1 +
                1)] = (matDatos[(cont2 + 1), cont1] - matDatos[cont2, cont1]
                       ) / (matDatos[elemRengl, 0] - matDatos[cont2, 0])
            cont2 += 1

    np.set_printoptions(precision=6, suppress=True)

    # Imprime la matriz 'matDatos'
    print("\n" + "\n".join([
        ''.join(['{:12}'.format(round(val, 6)) for val in fila])
        for fila in matDatos
    ]) + "\n")

    # Pide al usuario el grado del polinomio
    while True:
        try:
            num = int(
                input(
                    "Ingrese el grado del polinomio que quiera usar para el calculo: "
                ))
            if num > 0 and num < (matDatos.shape[1] - 1):
                break
            print("Entrada invalida")
        except:
            print("Entrada invalida")

    # Crea la variable que contendra el polinomio en formato'str'
    polinomio = f"({round(matDatos[0, 1], 8)})+"  # Primero agrega el primer termino del polinomio (constante)
    # Lista que contendra los terminos lineales
    terLin = [f"(x - {round(matDatos[0, 0], 6)})"
              ]  # Almacena el primer termino lineal en la lista
    # Bucle que construye el polinomio usando como coeficientes los elementos de la primera fila de la matriz
    for coeficientes in range(1, num + 1):
        polinomio += f"({round(matDatos[0, (coeficientes + 1)], 8)}"
        # Bucle que agregara los terminos lineales al polinomio
        for terminosLineales in terLin:
            polinomio += f" * {terminosLineales}"
        polinomio += ")+"

        # Agrega un nuevo termino a la lista de terminos lineales
        terLin.append(f"(x - {round(matDatos[coeficientes, 0], 6)})")

    # Elimina el ultimo signo '+' que esta en la cadena que contiene el polinomio
    polinomio = polinomio[:(len(polinomio) - 1)]

    # Pide al usuario que elija una opcion
    opcion = OpcionesDifDiv()

    if opcion == 1:
        # Imprime el polinomio interpolante
        print(f"\n\nEl Polinomio Interpolante es: {polinomio}\n")

        while True:
            print("Desea simplificar? Si - 1, No - 2: ", end='')
            try:
                opcion = int(input())
                if opcion > 0 and opcion < 3:
                    print()
                    break
                print("Opcion invalida!!!")
            except:
                print("Opcion invalida!!!")

        # Si el usuario desea simplificar el polinomio lo convierte a formato sagemath y lo simplifica
        if opcion == 1:
            polinomio = SR(polinomio)

            # Simplifica el polinomio resultante y lo imprime
            print(
                f"\n\nEl Polinomio Interpolante es: {polinomio.simplify_full()}\n"
            )

    else:  # Sustituye el punto que se quiere calcular por las 'x' que aparecen en la cadena de caracteres que contiene el polinomio
        x = float(
            input("\nIngresa una abscisa: "))  # Pide al usuario una abscisa
        polinomio = polinomio.replace('x', str(x))
        polinomio = SR(polinomio)

        # Simplifica el resultado y lo imprime redondeandolo a 8 decimales
        print(
            f"\n\nEl valor de la funcion en el punto {x} es aproximadamente: {round(polinomio.simplify_full(), 8)}\n"
        )
Exemplo n.º 13
0
def FormulasInt_Datos(matriz):
    """Funcion que pedira al usuario elegir que formula de integracion numerica aplicar si ingreso los valores de 'x' y 'y'"""
    # Pide al usuario que elija una de las siguientes opciones
    print("\n1.- Regla del trapecio")
    print("2.- Regla de simpson 1/3")
    print("3.- Regla de simpson 3/8")
    print("4.- Regla del punto medio")
    # Crea la lista que contendra los valores que ingrese el usuario para aplicar las formulas de integracion numerica
    lista = []

    while True:
        try:
            op = int(input("\nElija una opcion: "))
            if op > 0 and op < 5:
                break
            print("Opcion invalida!!!")
        except:
            print("Opcion invalida!!!")

    # Agrega la opcion elegida por el usuario a la lista 'lista'
    lista.append(op)

    np.set_printoptions(precision = 6, suppress = True)

    # Imprime los datos
    print("\nLos datos ingresados son los siguientes:\n")
    # Bucle que recorre la matriz que contiene los datos y los imprime de manera enumerada para que el usuario elija los datos que desee utilizar
    for elem in range(matriz.shape[0]):
        print((elem + 1), end = "   -   ")
        print(matriz[elem, :])

    # Pide al usuario elegir que datos elegir cuantos datos elegir
    while True:
        try:
            op = int(input("\nCuantos valores desea usar? "))
            if op > 1 and op <= matriz.shape[0]:
                lista.append(op)
                break
            print("Opcion invalida!!!")
        except:
            print("Opcion invalida!!!")

    # Crea el vector auxiliar que contendra los valores que se usaran en las formulas
    vectAux = np.empty((op, 2), dtype = 'f')

    # Si el usuario decide usar todos los datos
    if op == matriz.shape[0]:
        vectAux = matriz
    
    # Si el usuario decide no usar todos los datos
    else:
        # Pide al usuario elegir que datos usar
        for indice in range(op):
            while True:
                try:
                    dato = int(input(f"Elije el dato {indice + 1} que desee usar: "))
                    if dato > 0 and dato <= matriz.shape[0]:
                        vectAux[indice] = matriz[dato - 1]
                        break
                    print("Entrada invalida")
                except:
                    print("Entrada invalida")

    # Pide al usuario que ingrese un valor para 'h' positivo
    while True:
        try:
            h = float(input("\nIngrese un valor para 'h': "))
            if h > 0:
                break
            print("Entrada invalida")
        except:
            print("Entrada invalida")

    # Agrega el valor de 'h' ingresado por el usuario a la lista 'lista'
    lista.append(round(h, 6))

    # Regresa el vector con los datos que se usaran en la formula y 
    # la lista con los valores [formula, cantidad de valores, el valor de h]
    return(vectAux, lista)
Exemplo n.º 14
0
    def dimension(self,k,ignore=False, debug = 0):
        if k < 2 and not ignore:
            raise NotImplementedError("k has to >= 2")
        s = self._signature
        if not (2*k in ZZ):
            raise ValueError("k has to be integral or half-integral")
        if (2*k+s)%4 != 0 and not ignore:
            raise NotImplementedError("2k has to be congruent to -signature mod 4")
        if self._v2.has_key(0):
            v2 = self._v2[0]
        else:
            v2 = 1

        if self._g != None:
            if not self._aniso_formula:
                vals = self._g.values()
            #else:
                #print "using aniso_formula"
            M = self._g
        else:
            vals = self._M.values()
            M = self._M
            
        prec = ceil(max(log(M.order(),2),52)+1)+17
        #print prec
        RR = RealField(prec)
        CC = ComplexField(prec)
        d = self._d
        m = self._m
        if debug > 0: print d,m
            
        if self._alpha3 == None:
            if self._aniso_formula:
                self._alpha4 = 1
                self._alpha3 = -sum([BB(a)*mm for a,mm in self._v2.iteritems() if a != 0])
                #print self._alpha3
                self._alpha3 += Integer(d) - Integer(1) - self._g.beta_formula()
                #print self._alpha3, self._g.a5prime_formula()
                self._alpha3 = self._alpha3/RR(2)
            else:
                self._alpha3 = sum([(1-a)*mm for a,mm in self._v2.iteritems() if a != 0])
                #print self._alpha3
                self._alpha3 += sum([(1-a)*mm for a,mm in vals.iteritems() if a != 0])
                #print self._alpha3
                self._alpha3 = self._alpha3 / Integer(2)
                self._alpha4 = 1/Integer(2)*(vals[0]+v2) # the codimension of SkL in MkL
        alpha3 = self._alpha3
        alpha4 = self._alpha4
        if debug > 0: print alpha3, alpha4
        g1=M.char_invariant(1)
        g1=CC(g1[0]*g1[1])
        #print g1
        g2=M.char_invariant(2)
        g2=RR(real(g2[0]*g2[1]))
        if debug > 0: print g2, g2.parent()
        g3=M.char_invariant(-3)
        g3=CC(g3[0]*g3[1])
        if debug > 0: print RR(d) / RR(4), sqrt(RR(m)) / RR(4), CC(exp(2 * CC.pi() * CC(0,1) * (2 * k + s) / Integer(8)))
        alpha1 = RR(d) / RR(4) - (sqrt(RR(m)) / RR(4)  * CC(exp(2 * CC.pi() * CC(0,1) * (2 * k + s) / Integer(8))) * g2)
        if debug > 0: print alpha1
        alpha2 = RR(d) / RR(3) + sqrt(RR(m)) / (3 * sqrt(RR(3))) * real(exp(CC(2 * CC.pi() * CC(0,1) * (4 * k + 3 * s - 10) / 24)) * (g1+g3))
        if debug > 0: print alpha1, alpha2, g1, g2, g3, d, k, s
        dim = real(d + (d * k / Integer(12)) - alpha1 - alpha2 - alpha3)
        if debug > 0:
            print "dimension:", dim
        if abs(dim-round(dim)) > 1e-6:
            raise RuntimeError("Error ({0}) too large in dimension formula for {1} and k={2}".format(abs(dim-round(dim)), self._M if self._M is not None else self._g, k))
        dimr = dim
        dim = Integer(round(dim))
        if k >=2 and dim < 0:
            raise RuntimeError("Negative dimension (= {0}, {1})!".format(dim, dimr))
        return dim
Exemplo n.º 15
0
def Interpolacion_Splines_Cubicos(nombre):
    """Funcion que construira la tabla de los coeficientes para construir los Splines Cubicos"""
    # Primero llena una matriz con los datos contenidos en el documento de texto
    matDatos = LLenar_Matriz_Datos(nombre)

    vectH = np.empty(((matDatos.shape[0] - 1), 1), dtype='f')
    # Bucle que calcula la diferencia entre cada par de x en el intervalo y los almacena en 'vectH'
    for i in range(vectH.shape[0]):
        vectH[i] = matDatos[(i + 1), 0] - matDatos[i, 0]

    # Manda a llamar a la funcion para pedir al usuario que elija una opcion para aplicar el algoritmo
    listaDts = AlgoritmoTraz()

    # Si el usuario elije usar el algoritmo de trazador cubico natural
    if listaDts[0] == 1:
        vectAlpha = np.zeros(vectH.shape, dtype='f')
    # Si el usuario elije usar el algoritmo de trazador cubico sujeto
    else:
        vectAlpha = np.zeros((matDatos.shape[0], 1), dtype='f')
        # Calcula el primer y el ultimo valor de alpha [Burden p. 148]
        vectAlpha[0] = ((3 * (matDatos[1, 1] - matDatos[0, 1])) /
                        vectH[0]) - (3 * listaDts[1][0])
        vectAlpha[vectAlpha.shape[0] - 1] = ((3 * listaDts[1][1]) - \
        ((3 * (matDatos[(vectAlpha.shape[0] - 1), 1] - matDatos[(vectAlpha.shape[0] - 2), 1])) / vectH[vectAlpha.shape[0] - 2]))

    # Bucle que calcula los alphas
    for j in range(1, vectH.shape[0]):
        vectAlpha[j] = ((3 / vectH[j]) *
                        (matDatos[(j + 1), 1] - matDatos[(j), 1])) - (
                            (3 / vectH[j - 1]) *
                            (matDatos[(j), 1] - matDatos[(j - 1), 1]))

    # Despues resuelve un sistema lineal tridiagonal [Burden p. 146]
    vectL = np.ones((matDatos.shape[0], 1), dtype='f')
    vectZ = np.zeros(vectL.shape, dtype='f')
    vectMu = np.zeros(((matDatos.shape[0] - 1), 1), dtype='f')

    # Si el usuario elije usar el algoritmo de trazador cubico sujeto [Burden p.146]
    if listaDts[0] == 2:
        vectL[0] = 2 * vectH[0]
        vectMu[0] = 0.5
        vectZ[0] = vectAlpha[0] / vectL[0]

    for k in range(1, vectMu.shape[0]):
        vectL[k] = (2 * (matDatos[
            (k + 1), 0] - matDatos[k - 1, 0])) - (vectH[k - 1] * vectMu[k - 1])
        vectMu[k] = vectH[k] / vectL[k]
        vectZ[k] = (vectAlpha[k] - (vectH[k - 1] * vectZ[k - 1])) / vectL[k]

    vectC = np.zeros(vectL.shape, dtype='f')
    vectB = np.copy(vectC)
    vectD = np.copy(vectB)

    # Si el usuario elije usar el algoritmo de trazador cubico sujeto [Burden p.146]
    if listaDts[0] == 2:
        vectL[vectL.shape[0] - 1] = (vectH[vectL.shape[0] - 2] *
                                     (2 - vectMu[vectL.shape[0] - 2]))
        vectZ[vectL.shape[0] -
              1] = (vectAlpha[vectL.shape[0] - 1] -
                    (vectH[vectL.shape[0] - 2] *
                     vectZ[vectL.shape[0] - 2])) / vectL[vectL.shape[0] - 1]
        vectC[vectL.shape[0] - 1] = vectZ[vectL.shape[0] - 1]

    for l in range((vectC.shape[0] - 2), -1, -1):
        vectC[l] = vectZ[l] - (vectMu[l] * vectC[l + 1])
        vectB[l] = ((matDatos[(l + 1), 1] - matDatos[(l), 1]) /
                    vectH[l]) - (vectH[l] * ((vectC[l + 1] +
                                              (2 * vectC[l])) / 3))
        vectD[l] = (vectC[l + 1] - vectC[l]) / (3 * vectH[l])

    # Almacena los valores obtenidos de las iteraciones anteriores en la matriz 'matDatos'
    matDatos = np.append(matDatos, vectB, axis=1)
    matDatos = np.append(matDatos, vectC, axis=1)
    matDatos = np.append(matDatos, vectD, axis=1)

    # Imprime la matriz 'matDatos'
    print("\n" + "\n".join([
        ''.join(['{:12}'.format(round(val, 6)) for val in fila])
        for fila in matDatos
    ]) + "\n")

    x = float(input("\nIngresa una abscisa: "))  # Pide al usuario una abscisa

    # Si 'x' no se encuentra en el intervalo
    if np.size(np.where(matDatos[:matDatos.shape[0], 0] >= x)) == 0 or np.size(
            np.where(matDatos[:matDatos.shape[0], 0] <= x)) == 0:
        print(f"\n\nEl valor {x} no se encuentra en el intervalo")
        print("Pruebe con otro valor\n\n")
        sys.exit(1)

    # Bucle que recorrera los elementos de la primera columna de la matriz 'matDatos'
    for fila in range(matDatos.shape[0] - 2, -1,
                      -1):  # No se considera el elemento de la ultima fila
        if matDatos[fila, 0] < x:
            # La variable 'fila' se usara para indexar la fila de la matrz 'matDatos' que se usara para construir el spline
            break

    # Crea la variable que contendra el polinomio en formato'str'
    polinomio = ''
    # Variable auxiliar que se usara para indicar el grado
    expAux = 0
    # Bucle que contruye el polinomio usando como coeficientes los elementos de la fila 'fila' de la matriz 'matDatos'
    for coeficiente in matDatos[fila, 1:]:
        polinomio += f"({coeficiente} * (x - {matDatos[fila, 0]}) ** {expAux})+"
        expAux += 1

    # Elimina el ultimo signo '+' que esta en la cadena que contiene el polinomio
    polinomio = polinomio[:(len(polinomio) - 1)]

    print(f"\nEl Polinomio Interpolante es: {polinomio}")

    # Sustituye el punto que se quiere calcular por las 'x' que aparecen en la cadena de caracteres que contiene el polinomio
    polinomio = polinomio.replace('x', str(x))
    polinomio = SR(polinomio)

    # Simplifica el resultado y lo imprime redondeandolo a 8 decimales
    print(
        f"\n\nEl valor de la funcion en el punto {x} es aproximadamente: {round(polinomio.simplify_full(), 8)}\n"
    )
Exemplo n.º 16
0
def FormulasInt_Funcion(funcion):
    """Funcion que pedira al usuario elegir que formula de integracion numerica aplicar si ingreso una funcion"""
    # Pide al usuario que elija una de las siguientes opciones
    print("\n1.- Regla del trapecio")
    print("2.- Regla de simpson 1/3")
    print("3.- Regla de simpson 3/8")
    print("4.- Regla del punto medio")

    # Crea la lista que contendra los valores que ingrese el usuario para aplicar las formulas de integracion numerica
    lista = []

    while True:
        try:
            op = int(input("\nElija una opcion: "))
            if op > 0 and op < 5:
                break
            print("Opcion invalida!!!")
        except:
            print("Opcion invalida!!!")

    # Agrega la opcion elegida por el usuario a la lista 'lista'
    lista.append(op)

    np.set_printoptions(precision = 6, suppress = True)

    while True:
        try:
            x1 = float(input("Ingrese el valor del limite inferior de la integral: "))
            break
        except:
            print("Entrada invalida")

    while True:
        try:
            x2 = float(input("Ingrese el valor del limite superior de la integral: "))
            if x2 > x1:
                break
            print("Entrada invalida")
        except:
            print("Entrada invalida")

    while True:
        try:
            op = int(input("\nCuantos subintervalos desea usar? "))
            if op > 0:
                lista.append(op + 1)
                break
            print("Opcion invalida!!!")
        except:
            print("Opcion invalida!!!")

    # Calcula el valor de 'h' [Burden p. 197]
    h = (x2 - x1) / op
    # Agrega el valor de 'h' a la lista 'lista'
    lista.append(round(h, 6))

    # Crea la matriz que contendra los valores de 'x' y 'y'
    matDatos = np.empty(((op + 1), 2), dtype = 'f')

    # Primero llena la primera columna con los valores de 'x'
    for priCol in range(op + 1):
        matDatos[priCol, 0] = round(x1 + (h * priCol), 6)

    # Evalua la funcion en cada punto de 'x' y lo almacena en la segunda columna
    for segCol in range(op + 1):
        matDatos[segCol, 1] = funcion.subs(x = matDatos[segCol, 0])

    # Regresa el vector columna con los datos que se usaran en la formula y 
    # la lista con los valores [formula, cantidad de valores, el valor de h]
    return(matDatos, lista)
Exemplo n.º 17
0
def FormulasDer(matriz):
    """Funcion que pedira al usuario elegir que formula de derivacion numerica aplicar"""
    # Pide al usuario que elija una de las siguientes opciones
    print("\n1.- Derivacion numerica hacia adelante")
    print("2.- Derivacion numerica hacia atras")
    print("3.- Derivacion numerica centrada")
    # Crea la lista que contendra los valores que ingrese el usuario para aplicar las formulas de derivacion numerica
    lista = []

    while True:
        try:
            op = int(input("\nElija una opcion: "))
            if op > 0 and op < 4:
                break
            print("Opcion invalida!!!")
        except:
            print("Opcion invalida!!!")

    # Agrega la opcion elegida por el usuario a la lista 'lista'
    lista.append(op)

    np.set_printoptions(precision = 6, suppress = True)

    # Imprime los datos
    print("\nLos datos ingresados son los siguientes:\n")
    # Bucle que recorre la matriz que contiene los datos y los imprime de manera enumerada para que el usuario elija los datos que desee utilizar
    for elem in range(matriz.shape[0]):
        print((elem + 1), end = "   -   ")
        print(matriz[elem, :])

    # Pide al usuario elegir que datos elegir cuantos datos elegir
    while True:
        try:
            op = int(input("\nCuantos valores desea usar (3 o 5)? "))
            if op == 3 or op == 5:
                break
            elif op > matriz.shape[0]:
                print(f"\nNo es posible usar {op} valores porque solo se han ingresado {matriz.shape[0]} valores de entrada")
                print("Agregue mas datos al archivo de texto y vuelve a correr el programa\n")
                sys.exit(1)
            print("Opcion invalida!!!")
        except:
            print("Opcion invalida!!!")

    # Agrega la opcion elegida por el usuario a la lista 'lista'
    lista.append(op)

    # Crea el vector auxiliar que contendra los valores que se usaran en las formulas
    vectAux = np.empty((op, 2), dtype = 'f')

    # Pide al usuario elegir que datos usar
    for indice in range(op):
        while True:
            try:
                dato = int(input(f"Elije el dato {indice + 1} que desee usar: "))
                if dato > 0 and dato <= matriz.shape[0]:
                    vectAux[indice] = matriz[dato - 1]
                    break
                print("Entrada invalida")
            except:
                print("Entrada invalida")

    # Pide al usuario que ingrese un valor para 'h' positivo
    while True:
        try:
            h = float(input("\nIngrese un valor para 'h': "))
            if h > 0:
                break
            print("Entrada invalida")
        except:
            print("Entrada invalida")

    # Agrega el valor de 'h' ingresado por el usuario a la lista 'lista'
    lista.append(round(h, 6))

    # Extrae un valor dependiendo el tipo de formula que elijio el usuario
    if lista[0] == 1:  # Caso en el que se decide usar la formula hacia adelante
        lista.append(vectAux[0, 0])

    if lista[0] == 2:  # Caso en el que se decide usar la formula hacia atras
        lista.append(vectAux[(vectAux.shape[0] - 1), 0])

    else:  # Caso en el que se decide usar la formula centrada
        if lista[1] == 3:  # Caso en el que se decide usar 3 puntos
            lista.append(vectAux[1, 0])
        
        else:  # Caso en el que se decide usar 5 puntos
            lista.append(vectAux[2, 0])

    # Regresa el vector con los datos que se usaran en la formula y 
    # la lista con los valores [formula, cantidad de valores, el valor de h, punto al que se le va a calcular la derivada]
    return(vectAux, lista)
Exemplo n.º 18
0
    def dimension(self, k, ignore=False, debug=0):
        if k < 2 and not ignore:
            raise NotImplementedError("k has to >= 2")
        s = self._signature
        if not (2 * k in ZZ):
            raise ValueError("k has to be integral or half-integral")
        if (2 * k + s) % 4 != 0 and not ignore:
            raise NotImplementedError(
                "2k has to be congruent to -signature mod 4")
        if self._v2.has_key(0):
            v2 = self._v2[0]
        else:
            v2 = 1

        if self._g != None:
            if not self._aniso_formula:
                vals = self._g.values()
            #else:
            #print "using aniso_formula"
            M = self._g
        else:
            vals = self._M.values()
            M = self._M

        prec = ceil(max(log(M.order(), 2), 52) + 1) + 17
        #print prec
        RR = RealField(prec)
        CC = ComplexField(prec)
        d = self._d
        m = self._m
        if debug > 0: print d, m

        if self._alpha3 == None:
            if self._aniso_formula:
                self._alpha4 = 1
                self._alpha3 = -sum(
                    [BB(a) * mm for a, mm in self._v2.iteritems() if a != 0])
                #print self._alpha3
                self._alpha3 += Integer(d) - Integer(
                    1) - self._g.beta_formula()
                #print self._alpha3, self._g.a5prime_formula()
                self._alpha3 = self._alpha3 / RR(2)
            else:
                self._alpha3 = sum([(1 - a) * mm
                                    for a, mm in self._v2.iteritems()
                                    if a != 0])
                #print self._alpha3
                self._alpha3 += sum([(1 - a) * mm
                                     for a, mm in vals.iteritems() if a != 0])
                #print self._alpha3
                self._alpha3 = self._alpha3 / Integer(2)
                self._alpha4 = 1 / Integer(2) * (
                    vals[0] + v2)  # the codimension of SkL in MkL
        alpha3 = self._alpha3
        alpha4 = self._alpha4
        if debug > 0: print alpha3, alpha4
        g1 = M.char_invariant(1)
        g1 = CC(g1[0] * g1[1])
        #print g1
        g2 = M.char_invariant(2)
        g2 = RR(real(g2[0] * g2[1]))
        if debug > 0: print g2, g2.parent()
        g3 = M.char_invariant(-3)
        g3 = CC(g3[0] * g3[1])
        if debug > 0:
            print RR(d) / RR(4), sqrt(RR(m)) / RR(4), CC(
                exp(2 * CC.pi() * CC(0, 1) * (2 * k + s) / Integer(8)))
        alpha1 = RR(d) / RR(4) - (sqrt(RR(m)) / RR(4) * CC(
            exp(2 * CC.pi() * CC(0, 1) * (2 * k + s) / Integer(8))) * g2)
        if debug > 0: print alpha1
        alpha2 = RR(d) / RR(3) + sqrt(RR(m)) / (3 * sqrt(RR(3))) * real(
            exp(CC(2 * CC.pi() * CC(0, 1) * (4 * k + 3 * s - 10) / 24)) *
            (g1 + g3))
        if debug > 0: print alpha1, alpha2, g1, g2, g3, d, k, s
        dim = real(d + (d * k / Integer(12)) - alpha1 - alpha2 - alpha3)
        if debug > 0:
            print "dimension:", dim
        if abs(dim - round(dim)) > 1e-6:
            raise RuntimeError(
                "Error ({0}) too large in dimension formula for {1} and k={2}".
                format(abs(dim - round(dim)),
                       self._M if self._M is not None else self._g, k))
        dimr = dim
        dim = Integer(round(dim))
        if k >= 2 and dim < 0:
            raise RuntimeError("Negative dimension (= {0}, {1})!".format(
                dim, dimr))
        return dim
Exemplo n.º 19
0
def Integracion_Romberg(nombre):
    """Funcion que llevara a cabo la Integral de Romberg"""
    # Primero llena una matriz con los datos contenidos en el documento de texto
    funcion = LLenar_Matriz_Datos(nombre)

    # Si el usuario ingreso datos
    if type(funcion) != type(SR()):
        print("\n\nDebe ingresar una funcion\n\n")
        sys.exit(1)

    # Primero pide los datos al usuario
    datosUsr = IntegralRom()

    # Crea la matriz que contendra los valores de las iteraciones de la integral de Romberg
    matRom = np.zeros((datosUsr[2], datosUsr[2]), dtype='f')

    # Bucle que calculara las primeras aproximaciones
    for cont in range(datosUsr[2]):
        # Llama a la funcion para realizar las evaluaciones necesarias y los almacena en la matriz 'matDatos'
        matDatos = EvalRom_Funcion(funcion,
                                   ((datosUsr[1] - datosUsr[0]) / (2**cont)),
                                   (2**cont), datosUsr[0])

        # Termino que multiplica a las sumas
        integral = ((datosUsr[1] - datosUsr[0]) / (2**cont)) / 2
        # Termino de las sumas
        sumatoria = matDatos[-1, 1] + matDatos[0, 1]
        for suma in range(1, (2**cont)):
            sumatoria += 2 * matDatos[suma, 1]

        integral *= sumatoria

        # Almacena los valores de las primeras aproximaciones en la primera columna de la matriz 'matDatos'
        matRom[cont, 0] = integral

    # Bucle anidado que aplicara la formula para la integral del Romberg [Burden p. 209]
    for col in range(1, matRom.shape[0]):
        for fila in range(col, matRom.shape[0]):
            matRom[fila, col] = (((4**col) * matRom[fila, (col - 1)]) -
                                 matRom[(fila - 1),
                                        (col - 1)]) / ((4**col) - 1)

    # Crea el vector que contendra los errores de las integrales de Romberg
    vectErr = np.zeros((matRom.shape[0], 1), dtype='f')
    # Bucle que recorre todas los elementos de la diagonal
    for error in range(1, matRom.shape[0]):
        vectErr[error] = abs(matRom[error, error] - matRom[(error - 1),
                                                           (error - 1)])

    # Anexa los valores de los errores a la matriz 'matRom'
    matRom = np.append(matRom, vectErr, axis=1)

    # Imprime la matriz 'matRom'
    print("\n" + "\n".join([
        ''.join(['{:13}'.format(round(val, 8)) for val in fila])
        for fila in matRom
    ]) + "\n")

    print(f"\nUsando la integracion de Romberg")
    print(
        f"La aproximacion de la integral de x = {datosUsr[0]} a x = {datosUsr[1]}",
        end=" ")
    print(
        f"con {datosUsr[2]} iteraciones es: {round(matRom[-1, -2], 8)}, con un error de: {round(matRom[-1, -1], 8)}\n\n"
    )
Exemplo n.º 20
0
def render_lattice_webpage(**args):
    f = None
    if 'label' in args:
        lab = clean_input(args.get('label'))
        if lab != args.get('label'):
            return redirect(url_for('.render_lattice_webpage', label=lab), 301)
        f = db.lat_lattices.lucky({'$or':[{'label': lab }, {'name': {'$contains': [lab]}}]})
    if f is None:
        t = "Integral Lattices Search Error"
        bread = [('Lattices', url_for(".lattice_render_webpage"))]
        flash_error("%s is not a valid label or name for an integral lattice in the database.", lab)
        return render_template("lattice-error.html", title=t, properties=[], bread=bread, learnmore=learnmore_list())
    info = {}
    info.update(f)

    info['friends'] = []

    bread = [('Lattice', url_for(".lattice_render_webpage")), ('%s' % f['label'], ' ')]
    credit = lattice_credit
    info['dim']= int(f['dim'])
    info['det']= int(f['det'])
    info['level']=int(f['level'])
    info['gram']=vect_to_matrix(f['gram'])
    info['density']=str(f['density'])
    info['hermite']=str(f['hermite'])
    info['minimum']=int(f['minimum'])
    info['kissing']=int(f['kissing'])
    info['aut']=int(f['aut'])

    if f['shortest']=="":
        info['shortest']==f['shortest']
    else:
        if f['dim']==1:
            info['shortest']=str(f['shortest']).strip('[').strip(']')
        else:
            if info['dim']*info['kissing']<100:
                info['shortest']=[str([tuple(v)]).strip('[').strip(']').replace('),', '), ') for v in f['shortest']]
            else:
                max_vect_num=min(int(round(100/(info['dim']))), int(round(info['kissing']/2))-1);
                info['shortest']=[str([tuple(f['shortest'][i])]).strip('[').strip(']').replace('),', '), ') for i in range(max_vect_num+1)]
                info['all_shortest']="no"
        info['download_shortest'] = [
            (i, url_for(".render_lattice_webpage_download", label=info['label'], lang=i, obj='shortest_vectors')) for i in ['gp', 'magma','sage']]

    if f['name']==['Leech']:
        info['shortest']=[str([1,-2,-2,-2,2,-1,-1,3,3,0,0,2,2,-1,-1,-2,2,-2,-1,-1,0,0,-1,2]), 
str([1,-2,-2,-2,2,-1,0,2,3,0,0,2,2,-1,-1,-2,2,-1,-1,-2,1,-1,-1,3]), str([1,-2,-2,-1,1,-1,-1,2,2,0,0,2,2,0,0,-2,2,-1,-1,-1,0,-1,-1,2])]
        info['all_shortest']="no"
        info['download_shortest'] = [
            (i, url_for(".render_lattice_webpage_download", label=info['label'], lang=i, obj='shortest_vectors')) for i in ['gp', 'magma','sage']]

    ncoeff=20
    if f['theta_series'] != "":
        coeff=[f['theta_series'][i] for i in range(ncoeff+1)]
        info['theta_series']=my_latex(print_q_expansion(coeff))
        info['theta_display'] = url_for(".theta_display", label=f['label'], number="")

    info['class_number']=int(f['class_number'])

    if f['dim']==1:
        info['genus_reps']=str(f['genus_reps']).strip('[').strip(']')
    else:
        if info['dim']*info['class_number']<50:
            info['genus_reps']=[vect_to_matrix(n) for n in f['genus_reps']]
        else:
            max_matrix_num=min(int(round(25/(info['dim']))), info['class_number']);
            info['all_genus_rep']="no"
            info['genus_reps']=[vect_to_matrix(f['genus_reps'][i]) for i in range(max_matrix_num+1)]
    info['download_genus_reps'] = [
        (i, url_for(".render_lattice_webpage_download", label=info['label'], lang=i, obj='genus_reps')) for i in ['gp', 'magma','sage']]

    if f['name'] != "":
        if f['name']==str(f['name']):
            info['name']= str(f['name'])
        else:
            info['name']=str(", ".join(str(i) for i in f['name']))
    else:
        info['name'] == ""
    info['comments']=str(f['comments'])
    if 'Leech' in info['comments']: # no need to duplicate as it is in the name
        info['comments'] = ''
    if info['name'] == "":
        t = "Integral Lattice %s" % info['label']
    else:
        t = "Integral Lattice "+info['label']+" ("+info['name']+")"
#This part code was for the dinamic knowl with comments, since the test is displayed this is redundant
#    if info['name'] != "" or info['comments'] !="":
#        info['knowl_args']= "name=%s&report=%s" %(info['name'], info['comments'].replace(' ', '-space-'))
    info['properties'] = [
        ('Dimension', '%s' %info['dim']),
        ('Determinant', '%s' %info['det']),
        ('Level', '%s' %info['level'])]
    if info['class_number'] == 0:
        info['properties']=[('Class number', 'not available')]+info['properties']
    else:
        info['properties']=[('Class number', '%s' %info['class_number'])]+info['properties']
    info['properties']=[('Label', '%s' % info['label'])]+info['properties']

    if info['name'] != "" :
        info['properties']=[('Name','%s' % info['name'] )]+info['properties']
#    friends = [('L-series (not available)', ' ' ),('Half integral weight modular forms (not available)', ' ')]
    return render_template("lattice-single.html", info=info, credit=credit, title=t, bread=bread, properties=info['properties'], learnmore=learnmore_list(), KNOWL_ID="lattice.%s"%info['label'])
Exemplo n.º 21
0
    def dimension(self,k,ignore=False, debug = 0):
        if k < 2 and not ignore:
            raise NotImplementedError("k has to >= 2")
        s = self._signature
        if not (2*k in ZZ):
            raise ValueError("k has to be integral or half-integral")
        if (2*k+s)%2 != 0:
            return 0
        m = self._m
        n2 = self._n2
        if self._v2.has_key(0):
            v2 = self._v2[0]
        else:
            v2 = 1

        if self._g != None:
            if not self._aniso_formula:
                vals = self._g.values()
            #else:
                #print "using aniso_formula"
            M = self._g
        else:
            vals = self._M.values()
            M = self._M

        if (2*k+s)%4 == 0:
            d = Integer(1)/Integer(2)*(m+n2) # |dimension of the Weil representation on even functions|
            self._d = d
            self._alpha4 = 1/Integer(2)*(vals[0]+v2) # the codimension of SkL in MkL
        else:
            d = Integer(1)/Integer(2)*(m-n2) # |dimension of the Weil representation on odd functions|
            self._d = d
            self._alpha4 = 1/Integer(2)*(vals[0]-v2) # the codimension of SkL in MkL
            
        prec = ceil(max(log(M.order(),2),52)+1)+17
        #print prec
        RR = RealField(prec)
        CC = ComplexField(prec)
        
        if debug > 0: print "d, m = {0}, {1}".format(d,m)
        eps = exp( 2 * CC.pi() * CC(0,1) * (s + 2*k) / Integer(4) )
        eps = round(real(eps))        
        if self._alpha3 is None or self._last_eps != eps:
            self._last_eps = eps
            if self._aniso_formula:
                self._alpha4 = 1
                self._alpha3 = -sum([BB(a)*mm for a,mm in self._v2.iteritems() if a != 0])
                #print self._alpha3
                self._alpha3 += Integer(d) - Integer(1) - self._g.beta_formula()
                #print self._alpha3, self._g.a5prime_formula()
                self._alpha3 = self._alpha3/RR(2)
            else:
                self._alpha3 = eps*sum([(1-a)*mm for a,mm in self._v2.iteritems() if a != 0])
                if debug>0: print "alpha3t = ", self._alpha3
                self._alpha3 += sum([(1-a)*mm for a,mm in vals.iteritems() if a != 0])
                #print self._alpha3
                self._alpha3 = self._alpha3 / Integer(2)
        alpha3 = self._alpha3
        alpha4 = self._alpha4
        if debug > 0: print alpha3, alpha4
        g1=M.char_invariant(1)
        g1=CC(g1[0]*g1[1])
        #print g1
        g2=M.char_invariant(2)
        g2=CC(g2[0]*g2[1])
        if debug > 0: print g2, g2.parent()
        g3=M.char_invariant(-3)
        g3=CC(g3[0]*g3[1])
        if debug > 0: print "eps = {0}".format(eps)
        if debug > 0: print "d/4 = {0}, m/4 = {1}, e^(2pi i (2k+s)/8) = {2}".format(RR(d) / RR(4), sqrt(RR(m)) / RR(4), CC(exp(2 * CC.pi() * CC(0,1) * (2 * k + s) / Integer(8))))
        if eps == 1:
            g2_2 = real(g2)
        else:
            g2_2 = imag(g2)*CC(0,1)
        alpha1 = RR(d) / RR(4) - sqrt(RR(m)) / RR(4)  * CC(exp(2 * CC.pi() * CC(0,1) * (2 * k + s) / Integer(8)) * g2_2)
        if debug > 0: print alpha1
        alpha2 = RR(d) / RR(3) + sqrt(RR(m)) / (3 * sqrt(RR(3))) * real(exp(CC(2 * CC.pi() * CC(0,1) * (4 * k + 3 * s - 10) / 24)) * (g1 + eps*g3))
        if debug > 0: print "alpha1 = {0}, alpha2 = {1}, alpha3 = {2}, g1 = {3}, g2 = {4}, g3 = {5}, d = {6}, k = {7}, s = {8}".format(alpha1, alpha2, alpha3, g1, g2, g3, d, k, s)
        dim = real(d + (d * k / Integer(12)) - alpha1 - alpha2 - alpha3)
        if debug > 0:
            print "dimension:", dim
        if abs(dim-round(dim)) > 1e-6:
            raise RuntimeError("Error ({0}) too large in dimension formula for {1} and k={2}".format(abs(dim-round(dim)), self._M if self._M is not None else self._g, k))
        dimr = dim
        dim = Integer(round(dim))
        if k >=2 and dim < 0:
            raise RuntimeError("Negative dimension (= {0}, {1})!".format(dim, dimr))
        return dim
Exemplo n.º 22
0
def Interpolacion_Minimos_Cuadrados(nombre):
    """Funcion que construira el Polinomio Interpolante usando Minimos Cuadrados"""
    # Primero llena una matriz con los datos contenidos en el documento de texto
    matDatos = LLenar_Matriz_Datos(nombre)

    # Pide al usuario que indique si la relacion de los datos es exponencial
    relacionExp = RelacionMinCuad()

    # Si la relacion de los datos es exponencial
    if relacionExp:
        # Calcula los valores de las columnas (ln y, x^2, x * ln y) que se agregaran a la matriz 'matDatos' [Burden p. 492]
        vetcAux = np.copy(ln(matDatos[:, 1]))
        matDatos = np.append(matDatos, np.reshape(vetcAux, (vetcAux.shape[0], 1)), axis = 1)
        vetcAux = np.copy(matDatos[:, 0] * matDatos[:, 0])
        matDatos = np.append(matDatos, np.reshape(vetcAux, (vetcAux.shape[0], 1)), axis = 1)
        vetcAux = np.copy(matDatos[:, 0] * matDatos[:, 2])
        matDatos = np.append(matDatos, np.reshape(vetcAux, (vetcAux.shape[0], 1)), axis = 1)

        # Crea una matriz con las sumatorias necesarias para calcular el polinomio de la forma bx^a
        matBXA = np.array([[np.sum(ln(matDatos[:, 0]) * ln(matDatos[:, 0])), np.sum(ln(matDatos[:, 0])), np.sum(ln(matDatos[:, 0]) * ln(matDatos[:, 1]))], \
        [np.sum(ln(matDatos[:, 0])), matDatos.shape[0], np.sum(matDatos[:, 2])]])

        # Calculamos las inversas de las matrices para calcular el polinomio de orden 2
        matBXA = np.matmul(np.linalg.inv(matBXA[:, :2]), matBXA[:, 2])

    # Si la relacion de los datos no es exponencial
    else:
        # Bucle que calcula los valores de 'x' elevados a un exponente y los agrega a la matriz 'matDatos'
        for exponente in range(2, 7):
            vetcAux = np.copy(matDatos[:, 0]**exponente)
            matDatos = np.append(matDatos, np.reshape(vetcAux, (matDatos.shape[0], 1)), axis = 1)

        # Bucle que calcula los valores 'y' por 'x' elevados a un exponente y los agrega a la matriz 'matDatos'
        for columna in range(0, 4):  # Recorrera las columnas con los valores calculados en el bucle anterior
            # Se salta la columna con los valores de la 'y'
            if columna == 1:  
                continue
            vetcAux = np.copy(matDatos[:, columna]*matDatos[:, 1])
            matDatos = np.append(matDatos, np.reshape(vetcAux, (matDatos.shape[0], 1)), axis = 1)

        # Crea una matriz con las sumatorias necesarias para calcular el polinomio de orden 2
        matPolOrd2 = np.array([[matDatos.shape[0], np.sum(matDatos[:, 0]), np.sum(matDatos[:, 2]), np.sum(matDatos[:, 1])], \
        [np.sum(matDatos[:, 0]), np.sum(matDatos[:, 2]), np.sum(matDatos[:, 3]), np.sum(matDatos[:, 7])], \
        [np.sum(matDatos[:, 2]), np.sum(matDatos[:, 3]), np.sum(matDatos[:, 4]), np.sum(matDatos[:, 8])]])

        # Crea una matriz con las sumatorias necesarias para calcular el polinomio de orden 3
        matPolOrd3 = np.array([[matDatos.shape[0], np.sum(matDatos[:, 0]), np.sum(matDatos[:, 2]), np.sum(matDatos[:, 3]), np.sum(matDatos[:, 1])], \
        [np.sum(matDatos[:, 0]), np.sum(matDatos[:, 2]), np.sum(matDatos[:, 3]), np.sum(matDatos[:, 4]), np.sum(matDatos[:, 7])], \
        [np.sum(matDatos[:, 2]), np.sum(matDatos[:, 3]), np.sum(matDatos[:, 4]), np.sum(matDatos[:, 5]), np.sum(matDatos[:, 8])], \
        [np.sum(matDatos[:, 3]), np.sum(matDatos[:, 4]), np.sum(matDatos[:, 5]), np.sum(matDatos[:, 6]), np.sum(matDatos[:, 9])]])

        # Calculamos las inversas de las matrices para calcular el polinomio de orden 2
        matPolOrd2 = np.matmul(np.linalg.inv(matPolOrd2[:, :3]), matPolOrd2[:, 3])

        # Calculamos las inversas de las matrices para calcular el polinomio de orden 3
        matPolOrd3 = np.matmul(np.linalg.inv(matPolOrd3[:, :4]), matPolOrd3[:, 4])

    # Imprime la matriz 'matDatos'
    print("\n" + "\n".join([''.join(['{:12}'.format(round(val, 6)) for val in fila]) for fila in matDatos]) + "\n")

    # Crea la variable que contendra el polinomio en formato'str'
    polinomio = ''
    # Constuiye el polinomio usando como coeficientes las sumatorias  tomando en [Burden pp. 487, 492]
    # Si la relacion de los datos es exponencial
    if relacionExp:
        # Crea las variable que contendran los polinomios en formato'str'
        polinomio2 = ''

        valor1 = ((matDatos.shape[0] * np.sum(matDatos[:, 4])) - (np.sum(matDatos[:, 0]) * np.sum(matDatos[:, 2])))
        valor1 /= ((matDatos.shape[0] * np.sum(matDatos[:, 3])) - (np.sum(matDatos[:, 0]) ** 2))
        valor2 = ((np.sum(matDatos[:, 3]) * np.sum(matDatos[:, 2])) - (np.sum(matDatos[:, 4]) * np.sum(matDatos[:, 0])))
        valor2 /=((matDatos.shape[0] * np.sum(matDatos[:, 3])) - (np.sum(matDatos[:, 0]) ** 2))
        polinomio = f"(e ** {valor2}) * (e ** ({valor1} * x))"

        polinomio2 = f"({e ** matBXA[1]}) * x ** {matBXA[0]}"
    # Si la relacion de los datos no es exponencial
    else:
        # Crea las variable que contendran los polinomios en formato'str'
        polinomio2 = ''
        polinomio3 = ''

        valor1 = ((np.sum(matDatos[:, 2]) * np.sum(matDatos[:, 1])) - (np.sum(matDatos[:, 0]) * np.sum(matDatos[:, 7])))
        valor1 /= ((matDatos.shape[0] * np.sum(matDatos[:, 2])) - (np.sum(matDatos[:, 0]) ** 2))
        valor2 = ((matDatos.shape[0] * np.sum(matDatos[:, 7])) - (np.sum(matDatos[:, 0]) * np.sum(matDatos[:, 1])))
        valor2 /= ((matDatos.shape[0] * np.sum(matDatos[:, 2])) - (np.sum(matDatos[:, 0]) ** 2))
        polinomio = f"({valor2} * x) + {valor1}"

        polinomio2 = f"({matPolOrd2[2]} * x**2) + ({matPolOrd2[1]} * x) + {matPolOrd2[0]}"
        polinomio3 = f"({matPolOrd3[3]} * x**3) + ({matPolOrd3[2]} * x**2) + ({matPolOrd3[1]} * x) + {matPolOrd3[0]}"

    polinomio = SR(polinomio)
    polinomio2 = SR(polinomio2)
    # Si la relacion de los datos es exponencial
    if relacionExp:
        print(f"\nEl Polinomio Interpolante de la forma be^(ax) es: {polinomio}")
        print(f"\nEl Polinomio Interpolante de la forma bx^a es: {polinomio2}")

        # Matriz que contendra los valores de error
        matErr = np.empty((matDatos.shape[0], 2), dtype = 'f')
        cont = 0
        # Bucle para almacenar las evaluaciones de los polinomios
        for valorX in matDatos[:, 0]:
            matErr[cont, 0] = polinomio.subs(x = valorX)
            matErr[cont, 1] = polinomio2.subs(x = valorX)
            cont += 1

        # Calcula los errores
        matErr[:, 0] = abs(np.copy(matErr[:, 0] - matDatos[:, 1]))**2
        matErr[:, 1] = abs(np.copy(matErr[:, 1] - matDatos[:, 1]))**2

        print(f"\nLos errores totales de los polinomios respectivamente son:\n {np.sum(matErr[:, 0])} y \n {np.sum(matErr[:, 1])}")

    # Si la relacion de los datos no es exponencial
    else:
        polinomio3 = SR(polinomio3)

        print(f"\nEl Polinomio Interpolante de grado 1 es: {polinomio}")
        print(f"El Polinomio Interpolante de grado 2 es: {polinomio2}")
        print(f"El Polinomio Interpolante de grado 3 es: {polinomio3}")
        # Matriz que contendra los valores de error
        matErr = np.empty((matDatos.shape[0], 3), dtype = 'f')
        cont = 0
        # Bucle para almacenar las evaluaciones de los polinomios
        for valorX in matDatos[:, 0]:
            matErr[cont, 0] = polinomio.subs(x = valorX)
            matErr[cont, 1] = polinomio2.subs(x = valorX)
            matErr[cont, 2] = polinomio3.subs(x = valorX)
            cont += 1

        # Calcula los errores
        matErr[:, 0] = abs(np.copy(matErr[:, 0] - matDatos[:, 1]))**2
        matErr[:, 1] = abs(np.copy(matErr[:, 1] - matDatos[:, 1]))**2
        matErr[:, 2] = abs(np.copy(matErr[:, 2] - matDatos[:, 1]))**2

        print(f"\nLos errores totales de los polinomios respectivamente son:\n {np.sum(matErr[:, 0])}, \n {np.sum(matErr[:, 1])} y \n {np.sum(matErr[:, 2])}")

    a = float(input("\nIngresa una abscisa: "))  # Pide al usuario una abscisa

    # Declara la variable simbolica
    x = var('x')

    # Si la relacion de los datos es exponencial
    if relacionExp:
        print(f"\n\nEl valor de la funcion en el punto {a} (usando be^(ax)) es aproximadamente: {round(polinomio.subs(x = a).simplify_full(), 8)}")
        print(f"\n\nEl valor de la funcion en el punto {a} (usando bx^a) es aproximadamente: {round(polinomio2.subs(x = a).simplify_full(), 8)}")

    # Si la relacion de los datos no es exponencial
    else:
        # Simplifica el resultado y lo imprime redondeandolo a 8 decimales
        print(f"\n\nEl valor de la funcion en el punto {a} (usando el polinomio lineal) es aproximadamente: {round(polinomio.subs(x = a).simplify_full(), 8)}")
        print(f"El valor de la funcion en el punto {a} (usando el polinomio cuadratico) es aproximadamente: {round(polinomio2.subs(x = a).simplify_full(), 8)}")
        print(f"El valor de la funcion en el punto {a} (usando el polinomio cubico) es aproximadamente: {round(polinomio3.subs(x = a).simplify_full(), 8)}\n")
Exemplo n.º 23
0
    def dimension(self, k, ignore=False, debug=0):
        if k < 2 and not ignore:
            raise NotImplementedError("k has to >= 2")
        s = self._signature
        if not (2 * k in ZZ):
            raise ValueError("k has to be integral or half-integral")
        if (2 * k + s) % 2 != 0:
            return 0
        m = self._m
        n2 = self._n2
        if self._v2.has_key(0):
            v2 = self._v2[0]
        else:
            v2 = 1

        if self._g != None:
            if not self._aniso_formula:
                vals = self._g.values()
            #else:
            #print "using aniso_formula"
            M = self._g
        else:
            vals = self._M.values()
            M = self._M

        if (2 * k + s) % 4 == 0:
            d = Integer(1) / Integer(2) * (
                m + n2
            )  # |dimension of the Weil representation on even functions|
            self._d = d
            self._alpha4 = 1 / Integer(2) * (vals[0] + v2
                                             )  # the codimension of SkL in MkL
        else:
            d = Integer(1) / Integer(2) * (
                m - n2
            )  # |dimension of the Weil representation on odd functions|
            self._d = d
            self._alpha4 = 1 / Integer(2) * (vals[0] - v2
                                             )  # the codimension of SkL in MkL

        prec = ceil(max(log(M.order(), 2), 52) + 1) + 17
        #print prec
        RR = RealField(prec)
        CC = ComplexField(prec)

        if debug > 0: print "d, m = {0}, {1}".format(d, m)
        eps = exp(2 * CC.pi() * CC(0, 1) * (s + 2 * k) / Integer(4))
        eps = round(real(eps))
        if self._alpha3 is None or self._last_eps != eps:
            self._last_eps = eps
            if self._aniso_formula:
                self._alpha4 = 1
                self._alpha3 = -sum(
                    [BB(a) * mm for a, mm in self._v2.iteritems() if a != 0])
                #print self._alpha3
                self._alpha3 += Integer(d) - Integer(
                    1) - self._g.beta_formula()
                #print self._alpha3, self._g.a5prime_formula()
                self._alpha3 = self._alpha3 / RR(2)
            else:
                self._alpha3 = eps * sum(
                    [(1 - a) * mm for a, mm in self._v2.iteritems() if a != 0])
                if debug > 0: print "alpha3t = ", self._alpha3
                self._alpha3 += sum([(1 - a) * mm
                                     for a, mm in vals.iteritems() if a != 0])
                #print self._alpha3
                self._alpha3 = self._alpha3 / Integer(2)
        alpha3 = self._alpha3
        alpha4 = self._alpha4
        if debug > 0: print alpha3, alpha4
        g1 = M.char_invariant(1)
        g1 = CC(g1[0] * g1[1])
        #print g1
        g2 = M.char_invariant(2)
        g2 = CC(g2[0] * g2[1])
        if debug > 0: print g2, g2.parent()
        g3 = M.char_invariant(-3)
        g3 = CC(g3[0] * g3[1])
        if debug > 0: print "eps = {0}".format(eps)
        if debug > 0:
            print "d/4 = {0}, m/4 = {1}, e^(2pi i (2k+s)/8) = {2}".format(
                RR(d) / RR(4),
                sqrt(RR(m)) / RR(4),
                CC(exp(2 * CC.pi() * CC(0, 1) * (2 * k + s) / Integer(8))))
        if eps == 1:
            g2_2 = real(g2)
        else:
            g2_2 = imag(g2) * CC(0, 1)
        alpha1 = RR(d) / RR(4) - sqrt(RR(m)) / RR(4) * CC(
            exp(2 * CC.pi() * CC(0, 1) * (2 * k + s) / Integer(8)) * g2_2)
        if debug > 0: print alpha1
        alpha2 = RR(d) / RR(3) + sqrt(RR(m)) / (3 * sqrt(RR(3))) * real(
            exp(CC(2 * CC.pi() * CC(0, 1) * (4 * k + 3 * s - 10) / 24)) *
            (g1 + eps * g3))
        if debug > 0:
            print "alpha1 = {0}, alpha2 = {1}, alpha3 = {2}, g1 = {3}, g2 = {4}, g3 = {5}, d = {6}, k = {7}, s = {8}".format(
                alpha1, alpha2, alpha3, g1, g2, g3, d, k, s)
        dim = real(d + (d * k / Integer(12)) - alpha1 - alpha2 - alpha3)
        if debug > 0:
            print "dimension:", dim
        if abs(dim - round(dim)) > 1e-6:
            raise RuntimeError(
                "Error ({0}) too large in dimension formula for {1} and k={2}".
                format(abs(dim - round(dim)),
                       self._M if self._M is not None else self._g, k))
        dimr = dim
        dim = Integer(round(dim))
        if k >= 2 and dim < 0:
            raise RuntimeError("Negative dimension (= {0}, {1})!".format(
                dim, dimr))
        return dim
Exemplo n.º 24
0
def Interpolacion_Newton_Adelante_Atras(nombre):
    """Funcion que construira la tabla de las diferencias para aplicar la Formula de las Diferencias de Newton"""
    # Primero llena una matriz con los datos contenidos en el documento de texto
    matDatos = LLenar_Matriz_Datos(nombre)
    # Une la matriz 'matDatos' con otra matriz de ceros de orden n x n - 1, donde n es el numero de datos
    matDatos = np.copy(
        np.append(matDatos,
                  np.zeros((matDatos.shape[0], (matDatos.shape[0] - 1)),
                           dtype='f'),
                  axis=1))

    # Bucle que se repetira hasta calcular la ultima diferencia posible
    # Este contador se utilizara para indexar los valores de las columnas de 'matDatos'
    for cont1 in range(1, matDatos.shape[0]):
        #  Este contador se utilizara para indexar los valores de las filas de 'matDatos'
        cont2 = 0
        # Bucle que calcula los elementos de la tabla de diferencias
        for iteracion in range(cont1, matDatos.shape[0]):
            matDatos[cont2, (
                cont1 +
                1)] = matDatos[(cont2 + 1), cont1] - matDatos[cont2, cont1]
            cont2 += 1

    np.set_printoptions(precision=6, suppress=True)

    # Pide al usuario que elija una opcion
    opcion = AlgoritmoNet()

    # Si el usuario elije aplicar la interpolacion de newton hacia adelante entonces necesitamos indexar los valores de la primera fila de la matriz 'matDatos'
    if opcion == 1:
        fila = 0

    # Si el usuario elije aplicar la interpolacion de newton hacia atras entonces necesitamos indexar los valores de la ultima fila de la matriz 'matDatos'
    else:
        fila = matDatos.shape[0] - 1
        matDatos = Modificar_Matriz_DifRegr(matDatos)

    # Imprime la matriz 'matDatos'
    print("\n" + "\n".join([
        ''.join(['{:12}'.format(round(val, 6)) for val in fila])
        for fila in matDatos
    ]) + "\n")

    # Pide al usuario el grado del polinomio
    while True:
        try:
            num = int(
                input(
                    "Ingrese el grado del polinomio que quiera usar para el calculo: "
                ))
            if num > 0 and num < (matDatos.shape[1] - 1):
                break
            print("Entrada invalida")
        except:
            print("Entrada invalida")

    # Calcula 's'
    x = float(input("\nIngresa una abscisa: "))  # Pide al usuario una abscisa
    s = (x - matDatos[fila, 0]) / (matDatos[1, 0] - matDatos[0, 0])

    # Crea la variable que contendra el polinomio en formato'str'
    polinomio = f"({round(matDatos[fila, 1], 8)})+"  # Primero agrega el primer termino del polinomio (constante)
    # Lista que contendra los terminos lineales que se multiplicaran por las deltas
    terminos = ['s']  # Almacena el elemento 's' en la lista
    # Bucle que recorrera las columnas de la fila con la que se desee trabajar (la primera o la ultima)
    for deltas in range(1, num + 1):
        polinomio += f"(({round(matDatos[fila, (deltas + 1)], 8)}"
        # Bucle que agregara los terminos
        for termino in terminos:
            polinomio += f" * {termino}"
        polinomio += f") / (factorial({deltas})))+"

        # Agrega un nuevo termino a la lista
        # Si el usuario eligio aplicar la interpolacion de newton hacia adelante se agregan terminos de la forma: (s - n) [Burden p. 126]
        if opcion == 1:
            terminos.append(f"(s - {deltas})")

        # Si el usuario eligio plicar la interpolacion de newton hacia atras se agregan terminos de la forma: (s + n) [Burden p. 127]
        else:
            terminos.append(f"(s + {deltas})")

    # Elimina el ultimo signo '+' que esta en la cadena que contiene el polinomio
    polinomio = polinomio[:(len(polinomio) - 1)]

    # Sustituye 's' por el valor que se calculo
    polinomio = polinomio.replace('s', f"({str(s)})")

    print(f"\nEl Polinomio Interpolante es: {polinomio}")

    polinomio = SR(polinomio)

    # Simplifica el resultado y lo imprime redondeandolo a 8 decimales
    print(
        f"\n\nEl valor de la funcion en el punto {x} es aproximadamente: {round(polinomio.simplify_full(), 8)}\n"
    )