def mp_convert_constant(obj, **kwargs): if isinstance(obj, mpmath.ctx_mp_python._constant): prec = kwargs.get("prec", None) if prec is not None: return sympy.Float(obj(prec=prec)) return sympy.Float(obj) return obj
def simpson13(self): """ Metodo de Simpson 1/3 Este metodo se utiliza cuando n = 2 """ # Obtenemos los valores de X0 y X1 x0 = sp.Float(self.inicial) x2 = sp.Float(self.final) fx0 = self.f(x0) fx2 = self.f(x2) # Obtenemos h h = (x2 - x0) / 2 # Obtenemos x1 x1 = x0 + h # Obtenemos f(x1) fx1 = self.f(x1) # Obtenemos el area a = (h / 3) * (fx0 + (4 * fx1) + fx2) # Armamos cadena self.res += "\nn=2 -> x0=" + str(round(x0, 2)) + ", x1=" + str( round(x1, 2)) self.res += ", x2=" + str(round(x2, 2)) self.res += " f(x1)=" + str(round(fx1, 2)) + " -> a=" + str(round( a, 4))
def _estimate(self, treeView, count): """ Con el subintervalo ya definido, estimamos la raiz de f(x) hasta cierto margen de error """ # Estimacion inicial de la raiz r = (self.intervaloInicial + self.intervaloFinal) / 2.0 # Mostramos la informacion item = treeView.insert( "", (count - 1), text=str(count), values=("[" + str(sp.Float(self.intervaloInicial, 8)) + ", " + str(sp.Float(self.intervaloFinal, 8)) + "]", "f(" + str(sp.Float(r, 8)) + ") = " + str(self._f(r, self.ec)), str(r))) # Verificamos el resultado de f(x) y ajustamos el intervalo if self._f(r, self.ec) > 0: self.intervaloFinal = r else: self.intervaloInicial = r # Verificamos la raiz con el error estimado count += 1 # Aumentamos el contador treeView.selection_set(item) # Seleccionamos la ultima fila if abs(self._f(r, self.ec)) > self.error: return self._estimate(treeView, count) else: return r
def question3c(A): A_RREF = A.rref()[0] A_det = sp.Float(A.det(), 4) detA_s = sp.latex(A) detAr_s = sp.latex(A_RREF) Ar_det = sp.Float(A_RREF.det(), 4) button = widgets.Button(description='Solution', disabled=False) box = HBox(children=[button]) out = widgets.Output() @out.capture() def solution(e): out.clear_output() display( Latex("$" + "\det C" + "=" + "\det" + detA_s + "=" + "k \cdot" + "\det" + detAr_s + "= k \cdot" + "{}".format(Ar_det) + "=" + "{}".format(A_det) + "$")) display( Latex("Où $k$ est une constante qui n'est pas égale à zéro. ")) if sp.det(A) == 0: display( Latex( "$\det C$ est égal à zéro, donc la matrice $C$ est singulière." )) else: display( Latex( "$\det C $ n'est pas égal à zéro, donc la matrice $C$ est inversible." )) button.on_click(solution) display(box) display(out)
def do_cmp(x1, x2): real1, real2 = x1.get_real_value(), x2.get_real_value() inf1 = inf2 = None if x1.has_form('DirectedInfinity', 1): inf1 = x1.leaves[0].get_int_value() if x2.has_form('DirectedInfinity', 1): inf2 = x2.leaves[0].get_int_value() if real1 is not None and get_type(real1) != 'f': real1 = sympy.Float(real1) if real2 is not None and get_type(real2) != 'f': real2 = sympy.Float(real2) # Bus error when not converting to mpf if real1 is not None and real2 is not None: if x1 == x2: return 0 elif x1 < x2: return -1 else: return 1 elif inf1 is not None and inf2 is not None: return cmp(inf1, inf2) elif inf1 is not None and real2 is not None: return inf1 elif real1 is not None and inf2 is not None: return -inf2 else: return None
def test_split_factors_1(): test = { kz * Psi: (1, kz, Psi), A * kx**2 * Psi: (A * kx, kx, Psi), A * kx**2 * ky * Psi: (A * kx**2, ky, Psi), ky * A * kx * B * Psi: (ky * A, kx, B * Psi), kx: (1, kx, 1), kx**2: (kx, kx, 1), A: (1, 1, A), A**2: (1, 1, A**2), kx * A**2: (1, kx, A**2), kx**2 * A**2: (kx, kx, A**2), A(x, y, z): (1, 1, A(x, y, z)), Psi: (1, 1, Psi), np.int(5): (1, 1, np.int(5)), np.float(5): (1, 1, np.float(5)), sympy.Integer(5): (1, 1, sympy.Integer(5)), sympy.Float(5): (1, 1, sympy.Float(5)), 1: (1, 1, 1), 1.0: (1, 1, 1.0), 5: (1, 1, 5), 5.0: (1, 1, 5.0), } for inp, out in test.items(): got = split_factors(inp, discrete_coordinates={'x', 'y', 'z'}) assert got == out,\ "Should be: split_factors({})=={}. Not {}".format(inp, out, got)
def createMatrix(self): """ Creamos la matriz """ # verificamos el grado if self.grado > 3: # creamos la matriz vacia n = self.grado + 1 A = [[0 for x in range(n)] for y in range(n)] b = [] # Recorremos para llenar la matriz for k in range(0, self.grado + 1): # Llenamos la matriz for i in range(self.init + 1, self.init + self.grado + 2): # Creamos las n matrices aux = [] # llenamos cada columna for j in range(0, self.grado + 1): aux.append(mt.pow(sp.Float(self.dato2[i].get()), j)) A[i - (self.init + 1)] = aux b.append(sp.Float(self.dato1[k + 1].get())) # Obtenemos los valores gj = GausJordan() self.sol = gj.solve(A, b) # verificamos el resultado if len(self.sol) > 0: return True else: return False else: return self.crammer()
def evalf(self, prec): randfloat = sympy.Float(random.random(), dps=prec) / 2.7 ** (prec / 7 - random.random()) temp = (sympy.Float(random.random(), dps=prec) / (randfloat + time.time() % 1)) % 1 temp *= self.b - self.a temp += self.a if self.isint: temp = sympy.Integer(temp) return temp
def evaluate_binet(n_val): Phi = sp.symbols('Phi') # Golden ratio n = sp.symbols('n') # Binet's formula for calculating n'th fibonnacci symbol binet = (Phi**n - ((-1)**n) / (Phi**n)) / Pow(sp.Integer(5), sp.Float(0.5)) Phi_val = (sp.Integer(1) + Pow(sp.Integer(5), sp.Float(0.5))) / sp.Integer(2) return binet.evalf(subs={'Phi': Phi_val, 'n': n_val})
def crammer(self): """ Creamos las matrices para trabajar """ matrix = [] # creamos una lista para matrices determinant = [] # creamos una lista para las determinantes # creamos la matriz de la determinante d = np.zeros(shape=(self.grado + 1, self.grado + 1)) # Creamos las matrices (determinante + n matrices) for k in range(0, self.grado + 1): # Creamos una matriz vacia a = np.zeros(shape=(self.grado + 1, self.grado + 1)) if k == 0: # Llenamos la matriz for i in range(self.init + 1, self.init + self.grado + 2): # Creamos las n matrices aux = [] # llenamos cada columna for j in range(0, self.grado + 1): aux.append(mt.pow(sp.Float(self.dato2[i].get()), j)) d[i - (self.init + 1)] = aux if np.linalg.det(d) == 0: return False #print d #print np.linalg.det(d) matrix.append(d) # Almacenamos la matriz determinant.append( np.linalg.det(d)) # Almacenamos la determinante # Llenamos la matriz for i in range(self.init + 1, self.init + self.grado + 2): # Creamos las n matrices aux = [] # llenamos cada columna for j in range(0, self.grado + 1): if k == j: aux.append(sp.Float(self.dato1[i].get())) else: aux.append(mt.pow(sp.Float(self.dato2[i].get()), j)) a[i - (self.init + 1)] = aux #print a #print np.linalg.det(a) matrix.append(a) # Almacenamos la matriz determinant.append(np.linalg.det(a)) # Almacenamos la determinante # Guardamos la informacion self.matrix = matrix self.determinant = determinant return True
def exaseq(n): # retourne les cent premières valeurs de la suite avec un précision de 1000 décimales u_0 = sm.Float(1 / np.pi) cpval = [u_0] temp = sm.Float(0) for i in range(1, 100): temp = (22 * cpval[i - 1] * (1 - cpval[i - 1])).evalf(1000) cpval.append(temp - sm.floor(temp)) return cpval
def fcode_double(x, assign_to=None, **settings): if isinstance(x, (int, float)): return fcode(sympy.Float(x), assign_to=assign_to, **settings) else: return fcode(x.subs([(si, sympy.Float(si)) for si in x.atoms(sympy.Integer)]), assign_to=assign_to, **settings)
def difFin(self): """ Obtenemos a1, a2, ..., an medinate el metodo de diferencias finitas """ controlInicial = self.pares - 1 # Control de primeros ciclos data = [] # Guardamos los datos obtenidos expr = "" # resultados a mostrar # Empezamos a llenar la información expr += "D. F. 1: " # Obtenemos primeras finitas for i in range(0, controlInicial): # Obtenemos el f(x) de la dif finita expr += "f[" + str(i) + "] = " # Obtenemos el valor val = sp.Float(self.dato1[i + 2].get()) - sp.Float( self.dato1[i + 1].get()) # Agregamos el valor a la expresion expr += str(round(val, 4)) + ", " # Almacenamos el valor data.append(val) control = 0 # Controla el acceso a data controlPares = self.pares # control para datos pares # Obtenemos las segundas finitas en delante for j in range(2, self.pares): # Obtenemos el rango de finitas expr += "\nD. F. " + str(j) + ": " ctr = 0 # control para finitas de un solo rango # Recorremos el rango de pares de un rango de finitas for i in range(j, self.pares): # Obtenemos el f(x) de la dif finitas expr += "f[" + str(ctr) + "] = " # Obtenemos el valor val = sp.Float(data[control + i - 1]) - sp.Float( data[control + i - 2]) ctr += 1 # Aumentamos el control de rango de finitas data.append(val) # Almacenamos el dato expr += str(round(val, 4)) + ", " # Agregamos el valor a la expresion controlPares = controlPares - 1 control += controlPares - 1 # guardamos los datos self.data = data self.expr = expr
def expr(self): """ get function/expression of a circle with a given mid point Returns: sympy.core.expr.Expr: function of the circle """ return sy.sqrt(sy.Float(self.r) ** 2 - (x - sy.Float(self.x_m)) ** 2) * (-1 if self.clockwise else 1) + \ sy.Float(self.y_m)
def s(self, x): """ Obtenemos el valor de s x = valor a buscar """ # Obtenemos h h = sp.Float(self.dato2[2].get()) - sp.Float(self.dato2[1].get()) return (x - sp.Float(self.dato2[self.init + 1].get())) / h
def expr(self, x): """ get function/expression of a power function with a given mid point Returns: sympy.core.expr.Expr: function of the circle """ import sympy as sy return sy.Float(self.p) * x**sy.Float(self.exponent)
def mpmath2sympy(value, prec): if isinstance(value, mpmath.mpc): return (sympy.Float(str(value.real), dps(prec)) + sympy.I * sympy.Float(str(value.imag), dps(prec))) elif isinstance(value, mpmath.mpf): if str(value) in ('+inf', '-inf'): raise SpecialValueError('ComplexInfinity') return sympy.Float(str(value), dps(prec)) else: return None
def test_parameter_field_container(self): """Test InstructionParameter with container types.""" dog = Dog(barking=[0.1, 2.3]) dog_numpy = Dog(barking=numpy.array([0.1, 2.3])) dog_sympy = Dog(barking=[sympy.Float(0.1), sympy.Float(2.3)]) dog_complex = Dog(barking=complex(0.1, 2.3)) self.assertEqual(dog.to_dict(), dog_numpy.to_dict()) self.assertEqual(dog.to_dict(), dog_sympy.to_dict()) self.assertEqual(dog.to_dict(), dog_complex.to_dict())
def testComplex(self): self.compare( mathics.Complex(mathics.Real('1.0'), mathics.Real('1.0')), sympy.Add(sympy.Float('1.0'), sympy.Float('1.0') * sympy.I)) self.compare(mathics.Complex(mathics.Integer(0), mathics.Integer(1)), sympy.I) self.compare(mathics.Complex(mathics.Integer(-1), mathics.Integer(1)), sympy.Integer(-1) + sympy.I)
def Rlam(x, lam=None): v1 = kve(lam + 1, x) * np.exp(x) v0 = kve(lam, x) * np.exp(x) val = v1 / v0 if np.isinf(v1) or np.isinf(v0) or v0 == 0 or v1 == 0: lv1 = np.log(sympy.Float(mpmath.besselk(np.abs(lam + 1), x))) lv0 = np.log(sympy.Float(mpmath.besselk(np.abs(lam), x))) val = np.exp(lv1 - lv0) return val
def yieldLine(lx, ly, p, mx1=None, mx2=None, my1=None, my2=None, beta=2.0): ''' :param lx: :param ly: :param p: :param mx1: :param mx2: :param my1: :param my2: :param beta: :return: yield line method ''' n = ly / lx alp = 1 / (n * n) x = sympy.Symbol('x') if mx1 == None: mx1 = beta * ly * x if mx2 == None: mx2 = beta * ly * x if my1 == None: my1 = beta * alp * lx * x if my2 == None: my2 = beta * alp * lx * x f = 2 * (ly * x + alp * lx * x) + mx1 + mx2 + my1 + my2 - p * lx * lx * ( 3 * ly - lx) / 12 res = sympy.solve(f, x) m = res[0] if isinstance(mx1, (type(sympy.Float(1)), int)): mx1 = mx1 / ly else: mx1 = beta * m if isinstance(mx2, (type(sympy.Float(1)), int)): mx2 = mx2 / ly else: mx2 = beta * m if isinstance(my1, (type(sympy.Float(1)), int)): my1 = my1 / lx else: my1 = beta * m if isinstance(my2, (type(sympy.Float(1)), int)): my2 = my2 / lx else: my2 = beta * m return [alp, m, alp * m, mx1, mx2, my1, my2]
def testComplex(self): self.compare( mathics.Complex(mathics.Real("1.0"), mathics.Real("1.0")), sympy.Add(sympy.Float("1.0"), sympy.Float("1.0") * sympy.I), ) self.compare(mathics.Complex(mathics.Integer(0), mathics.Integer(1)), sympy.I) self.compare( mathics.Complex(mathics.Integer(-1), mathics.Integer(1)), sympy.Integer(-1) + sympy.I, )
def mpmath2sympy(value, prec=None): if prec is None: from mathics.builtin.numeric import machine_precision prec = machine_precision if isinstance(value, mpmath.mpc): return sympy.Float(str(value.real), dps(prec)) + sympy.I * sympy.Float(str(value.imag), dps(prec)) elif isinstance(value, mpmath.mpf): if str(value) in ('+inf', '-inf'): raise SpecialValueError('ComplexInfinity') return sympy.Float(str(value), dps(prec)) else: return None
def __init__(self, inicial, ecuacion, err=0.001, treeView=None): """ Constructor de la clase """ self.inicial = sp.sympify(sp.Float(inicial)) # valor inicial self.err = sp.sympify(sp.Float(err)) # margen de error self.ec = str(ecuacion).lower() # ecuacion self.root = 0 # raices racionales self.real = [] # raices reales self.complex = [] # raices complejas self.tree = treeView # Arbol de resultados
def split_lin_inhom_nonlin(expr, x, parameters=None): r""" Split an expression into a linear, inhomogeneous and nonlinear part. For example, in the expression :: x''' = c0 + c1*x + c2*x' + c3*x'' + x*y + x**2 :python:`lin_factors` would contain the linear part in the form of the list :python:`[c1, c2, c3]`, the inhomogeneous term would be :python:`c0` and the nonlinear part :python:`x*y + x**2` is returned as :python:`nonlin_term`. All parameters in :python:`parameters` are assumed to be constants. """ assert all([_is_sympy_type(sym) for sym in x]) if parameters is None: parameters = {} logging.debug("Splitting expression " + str(expr) + " (symbols " + str(x) + ")") lin_factors = sympy.zeros(len(x), 1) inhom_term = sympy.Float(0) nonlin_term = sympy.Float(0) expr = expr.expand() if expr.is_Add: terms = expr.args else: terms = [expr] for term in terms: if is_constant_term(term, parameters=parameters): inhom_term += term else: # check if the term is linear in any of the symbols in `x` is_lin = False for j, sym in enumerate(x): if is_constant_term(term / sym, parameters=parameters): lin_factors[j] += term / sym is_lin = True break if not is_lin: nonlin_term += term logging.debug("\tlinear factors: " + str(lin_factors)) logging.debug("\tinhomogeneous term: " + str(inhom_term)) logging.debug("\tnonlinear term: " + str(nonlin_term)) return lin_factors, inhom_term, nonlin_term
def prepareMatrix(self): """ Preparamos los valores para la matriz grado 1 - 2 ecuaciones de 2 - y grado 2 - 3 ecuaciones de 3 - y*x grado 3 - 4 ecuaciones de 4 - y*x^2 """ sumx = [] # sumatorias de x sumy = [] # sumatorias de y potencias = 0 # limite de potencias a obtener yx = self.grado # limite de f(x)*x # Obtenemos el limite de potencias if self.grado == 1: # si es grado uno potencias = 4 else: # Si es grado mayor a uno potencias = (self.grado * 2) + 1 # Obtenemos las sumatorias de x for i in range(1, potencias + 1): # suma sum = 0 # recorremos todos los pares de datos para la sumatoria for j in range(1, self.pares + 1): # sumamos sum += mt.pow(sp.Float(self.dato2[j].get()), i) # Añadimos la sumatoria a la lista sumx.append(sum) # Obtenemos las sumatorias de y for i in range(0, yx + 1): # suma sum = 0 # recorremos todos los pares de datos para la sumatoria for j in range(1, self.pares + 1): # sumamos if i == 0: sum += sp.Float(self.dato1[j].get()) else: sum += sp.Float(self.dato1[j].get()) * mt.pow( sp.Float(self.dato2[j].get()), i) # Añadimos la sumatoria a la lista sumy.append(sum) # Almacenamos los datos self.sumx = sumx self.sumy = sumy
def __init__(self): # always include this line, to define a sympy voltage symbol self.sp_v = sp.symbols('v') # basic factors to construct channel open probability self.factors = np.array([5., 1.]) self.powers = np.array([[3, 3, 1], [2, 2, 1]]) self.varnames = np.array([['a00', 'a01', 'a02'], ['a10', 'a11', 'a12']]) # asomptotic state variable functions self.varinf = np.array([[ 1. / (1. + sp_exp((self.sp_v - 30.) / 100.)), 1. / (1. + sp_exp( (-self.sp_v + 30.) / 100.)), sp.Float(-10.) ], [ 2. / (1. + sp_exp( (self.sp_v - 30.) / 100.)), 2. / (1. + sp_exp( (-self.sp_v + 30.) / 100.)), sp.Float(-30.) ]]) # state variable relaxation time scale self.tauinf = np.array([[sp.Float(1.), sp.Float(2.), sp.Float(1.)], [sp.Float(2.), sp.Float(2.), sp.Float(3.)]]) # base class instructor super(TestChannel, self).__init__()
def __init__(self): # always include this line, to define a sympy voltage symbol self.sp_v = sp.symbols('v') # basic factors to construct channel open probability self.factors = np.array([.9, .1]) self.powers = np.array([[3, 2], [2, 1]]) self.varnames = np.array([['a00', 'a01'], ['a10', 'a11']]) # asomptotic state variable functions self.varinf = np.array([[sp.Float(.3), sp.Float(.5)], [sp.Float(.4), sp.Float(.6)]]) # state variable relaxation time scale self.tauinf = np.array([[1., 2.], [2., 2.]]) # base class instructor super(TestChannel2, self).__init__()
def main(): x = sympy.Symbol("x") y = sympy.Symbol("y") e = 1 / sympy.cos(x) print() pprint(e) print("\n") pprint(e.subs(sympy.cos(x), y)) print("\n") pprint(e.subs(sympy.cos(x), y).subs(y, x**2)) e = 1 / sympy.log(x) e = e.subs(x, sympy.Float("2.71828")) print("\n") pprint(e) print("\n") pprint(e.evalf()) print() a = sympy.Symbol("a") b = sympy.Symbol("b") e = a * 2 + a**b / a print("\n") pprint(e) a = 2 print("\n") pprint(e.subs(a, 8)) print()
def replace_constants(sympy_expr, variables=None): ''' Replace constant values in a sympy expression with their numerical value. Parameters ---------- sympy_expr : `sympy.Expr` The expression variables : dict-like, optional Dictionary of `Variable` objects Returns ------- new_expr : `sympy.Expr` Expressions with all constants replaced ''' if variables is None: return sympy_expr symbols = set([ symbol for symbol in sympy_expr.atoms() if isinstance(symbol, sympy.Symbol) ]) for symbol in symbols: symbol_str = str(symbol) if symbol_str in variables: var = variables[symbol_str] if (getattr(var, 'scalar', False) and getattr(var, 'constant', False)): # TODO: We should handle variables of other data types better float_val = var.get_value() sympy_expr = sympy_expr.xreplace( {symbol: sympy.Float(float_val)}) return sympy_expr