我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sympy.Integer()。
def test_quadratic_perfect_square(): # B**2 - 4*A*C > 0 # B**2 - 4*A*C is a perfect square assert diop_solve(48*x*y) == set([(Integer(0), t), (t, Integer(0))]) assert diop_solve(4*x**2 - 5*x*y + y**2 + 2) == \ set([(-Integer(1), -Integer(3)),(-Integer(1), -Integer(2)),(Integer(1), Integer(2)),(Integer(1), Integer(3))]) assert diop_solve(-2*x**2 - 3*x*y + 2*y**2 -2*x - 17*y + 25) == set([(Integer(4), Integer(15))]) assert diop_solve(12*x**2 + 13*x*y + 3*y**2 - 2*x + 3*y - 12) == \ set([(-Integer(6), Integer(9)), (-Integer(2), Integer(5)), (Integer(4), -Integer(4)), (-Integer(6), Integer(16))]) assert diop_solve(8*x**2 + 10*x*y + 2*y**2 - 32*x - 13*y - 23) == \ set([(-Integer(44), Integer(47)), (Integer(22), -Integer(85))]) assert diop_solve(4*x**2 - 4*x*y - 3*y- 8*x - 3) == \ set([(-Integer(1), -Integer(9)), (-Integer(6), -Integer(9)), (Integer(0), -Integer(1)), (Integer(1), -Integer(1))]) assert diop_solve(- 4*x*y - 4*y**2 - 3*y- 5*x - 10) == \ set([(-Integer(2), Integer(0)), (-Integer(11), -Integer(1)), (-Integer(5), Integer(5))]) assert diop_solve(x**2 - y**2 - 2*x - 2*y) == set([(t, -t), (-t, -t - 2)]) assert diop_solve(x**2 - 9*y**2 - 2*x - 6*y) == set([(-3*t + 2, -t), (3*t, -t)]) assert diop_solve(4*x**2 - 9*y**2 - 4*x - 12*y - 3) == set([(-3*t - 3, -2*t - 3), (3*t + 1, -2*t - 1)])
def test_commutator(): A = Operator('A') B = Operator('B') c = Commutator(A, B) c_tall = Commutator(A**2, B) assert str(c) == '[A,B]' assert pretty(c) == '[A,B]' assert upretty(c) == u('[A,B]') assert latex(c) == r'\left[A,B\right]' sT(c, "Commutator(Operator(Symbol('A')),Operator(Symbol('B')))") assert str(c_tall) == '[A**2,B]' ascii_str = \ """\ [ 2 ]\n\ [A ,B]\ """ ucode_str = \ u("""\ ? 2 ?\n\ ?A ,B?\ """) assert pretty(c_tall) == ascii_str assert upretty(c_tall) == ucode_str assert latex(c_tall) == r'\left[\left(A\right)^{2},B\right]' sT(c_tall, "Commutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))")
def test_scalars(): x = symbols('x', complex=True) assert Dagger(x) == conjugate(x) assert Dagger(I*x) == -I*conjugate(x) i = symbols('i', real=True) assert Dagger(i) == i p = symbols('p') assert isinstance(Dagger(p), adjoint) i = Integer(3) assert Dagger(i) == i A = symbols('A', commutative=False) assert Dagger(A).is_commutative is False
def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format', 'sympy') options['spmatrix'] = 'lil' vector = matrix_zeros(ndim_info, 1, **options) if isinstance(self.n, Integer): if self.n >= ndim_info: return ValueError("N-Dimension too small") value = Integer(1) if format == 'scipy.sparse': vector[int(self.n), 0] = 1.0 vector = vector.tocsr() elif format == 'numpy': vector[int(self.n), 0] = 1.0 else: vector[self.n, 0] = Integer(1) return vector else: return ValueError("Not Numerical State")
def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format', 'sympy') options['spmatrix'] = 'lil' vector = matrix_zeros(1, ndim_info, **options) if isinstance(self.n, Integer): if self.n >= ndim_info: return ValueError("N-Dimension too small") if format == 'scipy.sparse': vector[0, int(self.n)] = 1.0 vector = vector.tocsr() elif format == 'numpy': vector[0, int(self.n)] = 1.0 else: vector[0, self.n] = Integer(1) return vector else: return ValueError("Not Numerical State")
def eval(cls, a, b): if not (a and b): return S.Zero if a == b: return Integer(2)*a**2 if a.is_commutative or b.is_commutative: return Integer(2)*a*b # [xA,yB] -> xy*[A,B] # from sympy.physics.qmul import QMul ca, nca = a.args_cnc() cb, ncb = b.args_cnc() c_part = ca + cb if c_part: return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb))) # Canonical ordering of arguments #The Commutator [A,B] is on canonical form if A < B. if a.compare(b) == 1: return cls(b, a)
def do_arg(a): if isinstance(a, str): arg = Symbol(a, integer=True) elif isinstance(a, (Integer, Float)): arg = a elif isinstance(a, ArithmeticExpression): arg = a.expr if isinstance(arg, (Symbol, Variable)): arg = Symbol(arg.name, integer=True) else: arg = convert_to_integer_expression(arg) else: raise Exception('Wrong instance in do_arg') return arg # ... # ... TODO improve. this version is not working with function calls
def extract_arg(self, name): """ returns an argument as a variable, given its name name: str variable name """ if name is None: return None var = None if isinstance(name, (Integer, Float)): var = Integer(name) elif isinstance(name, str): if name in namespace: var = namespace[name] else: raise Exception("could not find {} in namespace ".format(name)) elif isinstance(name, ArithmeticExpression): var = do_arg(name) else: raise Exception("Unexpected type {0} for {1}".format(type(name), name)) return var
def monomial_basis(*degrees): """ Returns the product basis of (kx, ky, kz), with monomials of the given degrees. :param degrees: Degree of the monomials. Multiple degrees can be given, in which case the basis consists of the monomials of all given degrees. :type degrees: int Example: >>> import kdotp_symmetry as kp >>> kp.monomial_basis(*range(3)) [1, kx, ky, kz, kx**2, kx*ky, kx*kz, ky**2, ky*kz, kz**2] """ if any(deg < 0 for deg in degrees): raise ValueError('Degrees must be non-negative integers') basis = [] for deg in sorted(degrees): monomial_tuples = combinations_with_replacement(K_VEC, deg) basis.extend( reduce(operator.mul, m, sp.Integer(1)) for m in monomial_tuples ) return basis
def has_integer_powers(self): """ Check if the dimension object has only integer powers. All the dimension powers should be integers, but rational powers may appear in intermediate steps. This method may be used to check that the final result is well-defined. """ for dpow in self.get_dimensional_dependencies().values(): if not isinstance(dpow, (int, Integer)): return False else: return True # base dimensions (MKS)
def test_commutator(): A = Operator('A') B = Operator('B') c = Commutator(A, B) c_tall = Commutator(A**2, B) assert str(c) == '[A,B]' assert pretty(c) == '[A,B]' assert upretty(c) == u'[A,B]' assert latex(c) == r'\left[A,B\right]' sT(c, "Commutator(Operator(Symbol('A')),Operator(Symbol('B')))") assert str(c_tall) == '[A**2,B]' ascii_str = \ """\ [ 2 ]\n\ [A ,B]\ """ ucode_str = \ u("""\ ? 2 ?\n\ ?A ,B?\ """) assert pretty(c_tall) == ascii_str assert upretty(c_tall) == ucode_str assert latex(c_tall) == r'\left[A^{2},B\right]' sT(c_tall, "Commutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))")
def test_IntQubit(): iqb = IntQubit(8) assert iqb.as_int() == 8 assert iqb.qubit_values == (1, 0, 0, 0) iqb = IntQubit(7, 4) assert iqb.qubit_values == (0, 1, 1, 1) assert IntQubit(3) == IntQubit(3, 2) #test Dual Classes iqb = IntQubit(3) iqb_bra = IntQubitBra(3) assert iqb.dual_class() == IntQubitBra assert iqb_bra.dual_class() == IntQubit iqb = IntQubit(5) iqb_bra = IntQubitBra(5) assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(1) iqb = IntQubit(4) iqb_bra = IntQubitBra(5) assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(0) raises(ValueError, lambda: IntQubit(4, 1))
def _expand_powers(factors): """ Helper function for normal_ordered_form and normal_order: Expand a power expression to a multiplication expression so that that the expression can be handled by the normal ordering functions. """ new_factors = [] for factor in factors.args: if (isinstance(factor, Pow) and isinstance(factor.args[1], Integer) and factor.args[1] > 0): for n in range(factor.args[1]): new_factors.append(factor.args[0]) else: new_factors.append(factor) return new_factors
def intify(base): def inner(string): left, right = re.split('[^0-9]', string, 1) return sympy.Integer(int(right, base) * (base ** int(left))) return inner
def test_acceleration(): e = (1 + 1/n)**n assert round(richardson(e, n, 10, 20).evalf(), 10) == round(E.evalf(), 10) A = Sum(Integer(-1)**(k + 1) / k, (k, 1, n)) assert round(shanks(A, n, 25).evalf(), 4) == round(log(2).evalf(), 4) assert round(shanks(A, n, 25, 5).evalf(), 10) == round(log(2).evalf(), 10)
def shanks(A, k, n, m=1): """ Calculate an approximation for lim k->oo A(k) using the n-term Shanks transformation S(A)(n). With m > 1, calculate the m-fold recursive Shanks transformation S(S(...S(A)...))(n). The Shanks transformation is useful for summing Taylor series that converge slowly near a pole or singularity, e.g. for log(2): >>> from sympy.abc import k, n >>> from sympy import Sum, Integer >>> from sympy.series.acceleration import shanks >>> A = Sum(Integer(-1)**(k+1) / k, (k, 1, n)) >>> print(round(A.subs(n, 100).doit().evalf(), 10)) 0.6881721793 >>> print(round(shanks(A, n, 25).evalf(), 10)) 0.6931396564 >>> print(round(shanks(A, n, 25, 5).evalf(), 10)) 0.6931471806 The correct value is 0.6931471805599453094172321215. """ table = [A.subs(k, Integer(j)).doit() for j in range(n + m + 2)] table2 = table[:] for i in range(1, m + 1): for j in range(i, n + m + 1): x, y, z = table[j - 1], table[j], table[j + 1] table2[j] = (z*x - y**2) / (z + x - 2*y) table = table2[:] return table[n]
def test_Tuple_mul(): assert Tuple(1, 2, 3)*2 == Tuple(1, 2, 3, 1, 2, 3) assert 2*Tuple(1, 2, 3) == Tuple(1, 2, 3, 1, 2, 3) assert Tuple(1, 2, 3)*Integer(2) == Tuple(1, 2, 3, 1, 2, 3) assert Integer(2)*Tuple(1, 2, 3) == Tuple(1, 2, 3, 1, 2, 3) raises(TypeError, lambda: Tuple(1, 2, 3)*S.Half) raises(TypeError, lambda: S.Half*Tuple(1, 2, 3))
def test_sympy__core__numbers__Integer(): from sympy.core.numbers import Integer assert _test_args(Integer(7))
def set_v_steps(self, v_steps): if v_steps is None: self._v_steps = None return if isinstance(v_steps, int): v_steps = Integer(v_steps) elif not isinstance(v_steps, Integer): raise ValueError("v_steps must be an int or sympy Integer.") if v_steps <= Integer(0): raise ValueError("v_steps must be positive.") self._v_steps = v_steps
def vrange(self): """ Yields v_steps+1 sympy numbers ranging from v_min to v_max. """ d = (self.v_max - self.v_min) / self.v_steps for i in xrange(self.v_steps + 1): a = self.v_min + (d * Integer(i)) yield a
def vrange2(self): """ Yields v_steps pairs of sympy numbers ranging from (v_min, v_min + step) to (v_max - step, v_max). """ d = (self.v_max - self.v_min) / self.v_steps a = self.v_min + (d * Integer(0)) for i in xrange(self.v_steps): b = self.v_min + (d * Integer(i + 1)) yield a, b a = b
def __setitem__(self, i, args): """ Parses and adds a PlotMode to the function list. """ if not (isinstance(i, (int, Integer)) and i >= 0): raise ValueError("Function index must " "be an integer >= 0.") if isinstance(args, PlotObject): f = args else: if (not is_sequence(args)) or isinstance(args, GeometryEntity): args = [args] if len(args) == 0: return # no arguments given kwargs = dict(bounds_callback=self.adjust_all_bounds) f = PlotMode(*args, **kwargs) if f: self._render_lock.acquire() self._functions[i] = f self._render_lock.release() else: raise ValueError("Failed to parse '%s'." % ', '.join(str(a) for a in args))
def test_univariate(): assert diop_solve((x - 1)*(x - 2)**2) == set([(Integer(1),), (Integer(2),)]) assert diop_solve((x - 1)*(x - 2)) == set([(Integer(1),), (Integer(2),)])
def test_quadratic_elliptical_case(): # Elliptical case: B**2 - 4AC < 0 # Two test cases highlighted require lot of memory due to quadratic_congruence() method. # This above method should be replaced by Pernici's square_mod() method when his PR gets merged. #assert diop_solve(42*x**2 + 8*x*y + 15*y**2 + 23*x + 17*y - 4915) == set([(-Integer(11), -Integer(1))]) assert diop_solve(4*x**2 + 3*y**2 + 5*x - 11*y + 12) == set([]) assert diop_solve(x**2 + y**2 + 2*x + 2*y + 2) == set([(-Integer(1), -Integer(1))]) #assert diop_solve(15*x**2 - 9*x*y + 14*y**2 - 23*x - 14*y - 4950) == set([(-Integer(15), Integer(6))]) assert diop_solve(10*x**2 + 12*x*y + 12*y**2 - 34) == \ set([(Integer(1), -Integer(2)), (-Integer(1), -Integer(1)),(Integer(1), Integer(1)), (-Integer(1), Integer(2))])
def is_pell_transformation_ok(eq): """ Test whether X*Y, X, or Y terms are present in the equation after transforming the equation using the transformation returned by transformation_to_pell(). If they are not present we are good. Moreover, coefficient of X**2 should be a divisor of coefficient of Y**2 and the constant term. """ A, B = transformation_to_DN(eq) u = (A*Matrix([X, Y]) + B)[0] v = (A*Matrix([X, Y]) + B)[1] simplified = _mexpand(Subs(eq, (x, y), (u, v)).doit()) coeff = dict([reversed(t.as_independent(*[X, Y])) for t in simplified.args]) for term in [X*Y, X, Y]: if term in coeff.keys(): return False for term in [X**2, Y**2, Integer(1)]: if term not in coeff.keys(): coeff[term] = Integer(0) if coeff[X**2] != 0: return isinstance(S(coeff[Y**2])/coeff[X**2], Integer) and isinstance(S(coeff[Integer(1)])/coeff[X**2], Integer) return True
def test_solve_poly_system(): assert solve_poly_system([x - 1], x) == [(S.One,)] assert solve_poly_system([y - x, y - x - 1], x, y) is None assert solve_poly_system([y - x**2, y + x**2], x, y) == [(S.Zero, S.Zero)] assert solve_poly_system([2*x - 3, 3*y/2 - 2*x, z - 5*y], x, y, z) == \ [(Rational(3, 2), Integer(2), Integer(10))] assert solve_poly_system([x*y - 2*y, 2*y**2 - x**2], x, y) == \ [(0, 0), (2, -sqrt(2)), (2, sqrt(2))] assert solve_poly_system([y - x**2, y + x**2 + 1], x, y) == \ [(-I*sqrt(S.Half), -S.Half), (I*sqrt(S.Half), -S.Half)] f_1 = x**2 + y + z - 1 f_2 = x + y**2 + z - 1 f_3 = x + y + z**2 - 1 a, b = sqrt(2) - 1, -sqrt(2) - 1 assert solve_poly_system([f_1, f_2, f_3], x, y, z) == \ [(0, 0, 1), (0, 1, 0), (1, 0, 0), (a, a, a), (b, b, b)] solution = [(1, -1), (1, 1)] assert solve_poly_system([Poly(x**2 - y**2), Poly(x - 1)]) == solution assert solve_poly_system([x**2 - y**2, x - 1], x, y) == solution assert solve_poly_system([x**2 - y**2, x - 1]) == solution assert solve_poly_system( [x + x*y - 3, y + x*y - 4], x, y) == [(-3, -2), (1, 2)] raises(NotImplementedError, lambda: solve_poly_system([x**3 - y**3], x, y)) raises(PolynomialError, lambda: solve_poly_system([1/x], x))
def __new__(cls, *args, **hints): if not len(args) in [1, 2]: raise ValueError('1 or 2 parameters expected, got %s' % args) if len(args) == 1: args = (args[0], Integer(1)) if len(args) == 2: args = (args[0], Integer(args[1])) return Operator.__new__(cls, *args)
def _eval_commutator_FermionOp(self, other, **hints): return Integer(0)
def _eval_innerproduct_BosonCoherentBra(self, bra, **hints): if self.alpha == bra.alpha: return Integer(1) else: return exp(-(abs(self.alpha)**2 + abs(bra.alpha)**2 - 2 * conjugate(bra.alpha) * self.alpha)/2)
def _eval_innerproduct_QubitBra(self, bra, **hints): if self.label == bra.label: return Integer(1) else: return Integer(0)
def get_target_matrix(self, format='sympy'): if format == 'sympy': return Matrix([[1, 0], [0, exp(Integer(2)*pi*I/(Integer(2)**self.k))]]) raise NotImplementedError( 'Invalid format for the R_k gate: %r' % format)
def _eval_commutator(self, other, **hints): if isinstance(other, OneQubitGate): if self.targets != other.targets or self.__class__ == other.__class__: return Integer(0) return Operator._eval_commutator(self, other, **hints)
def _eval_anticommutator(self, other, **hints): if isinstance(other, OneQubitGate): if self.targets != other.targets or self.__class__ == other.__class__: return Integer(2)*self*other return Operator._eval_anticommutator(self, other, **hints)
def _eval_commutator(self, other, **hints): return Integer(0)
def _eval_anticommutator(self, other, **hints): return Integer(2)*other
def _eval_anticommutator_YGate(self, other, **hints): return Integer(0)
def _eval_anticommutator_XGate(self, other, **hints): return Integer(2)*IdentityGate(self.targets[0])
def _eval_anticommutator_ZGate(self, other, **hints): return Integer(0)
def _eval_commutator_ZGate(self, other, **hints): return Integer(2)*I*XGate(self.targets[0])
def _eval_anticommutator_YGate(self, other, **hints): return Integer(2)*IdentityGate(self.targets[0])
def _eval_commutator_XGate(self, other, **hints): return Integer(2)*I*YGate(self.targets[0])
def _eval_commutator_ZGate(self, other, **hints): return Integer(0)
def _eval_commutator_TGate(self, other, **hints): return Integer(0)
def _eval_commutator_ZGate(self, other, **hints): """[CNOT(i, j), Z(i)] == 0.""" if self.controls[0] == other.targets[0]: return Integer(0) else: raise NotImplementedError('Commutator not implemented: %r' % other)
def _eval_commutator_XGate(self, other, **hints): """[CNOT(i, j), X(j)] == 0.""" if self.targets[0] == other.targets[0]: return Integer(0) else: raise NotImplementedError('Commutator not implemented: %r' % other)
def _eval_commutator_CNotGate(self, other, **hints): """[CNOT(i, j), CNOT(i,k)] == 0.""" if self.controls[0] == other.controls[0]: return Integer(0) else: raise NotImplementedError('Commutator not implemented: %r' % other)