Python sympy.Integer() Examples

The following are 30 code examples of sympy.Integer(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sympy , or try the search function .
Example #1
Source File: arithmetic.py    From mathematics_dataset with Apache License 2.0 6 votes vote down vote up
def simplify_surd(value, sample_args, context=None):
  """E.g., "Simplify (2 + 5*sqrt(3))**2."."""
  del value  # unused
  if context is None:
    context = composition.Context()

  entropy, sample_args = sample_args.peel()

  while True:
    base = random.randint(2, 20)
    if sympy.Integer(base).is_prime:
      break
  num_primes_less_than_20 = 8
  entropy -= math.log10(num_primes_less_than_20)
  exp = _sample_surd(base, entropy, max_power=2, multiples_only=False)
  simplified = sympy.expand(sympy.simplify(exp))

  template = random.choice([
      'Simplify {exp}.',
  ])
  return example.Problem(
      question=example.question(context, template, exp=exp),
      answer=simplified) 
Example #2
Source File: test_sympy_conv.py    From symengine.py with MIT License 6 votes vote down vote up
def test_conv10():
    A = DenseMatrix(1, 4, [Integer(1), Integer(2), Integer(3), Integer(4)])
    assert (A._sympy_() == sympy.Matrix(1, 4,
                                        [sympy.Integer(1), sympy.Integer(2),
                                         sympy.Integer(3), sympy.Integer(4)]))

    B = DenseMatrix(4, 1, [Symbol("x"), Symbol("y"), Symbol("z"), Symbol("t")])
    assert (B._sympy_() == sympy.Matrix(4, 1,
                                        [sympy.Symbol("x"), sympy.Symbol("y"),
                                         sympy.Symbol("z"), sympy.Symbol("t")])
            )

    C = DenseMatrix(2, 2,
                    [Integer(5), Symbol("x"),
                     function_symbol("f", Symbol("x")), 1 + I])

    assert (C._sympy_() ==
            sympy.Matrix([[5, sympy.Symbol("x")],
                          [sympy.Function("f")(sympy.Symbol("x")),
                           1 + sympy.I]])) 
Example #3
Source File: operatorordering.py    From sympsi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #4
Source File: test_dagger.py    From sympsi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #5
Source File: test_dot.py    From Computable with MIT License 6 votes vote down vote up
def test_dotprint():
    text = dotprint(x+2, repeat=False)
    assert all(e in text for e in dotedges(x+2, repeat=False))
    assert all(n in text for n in map(lambda expr: dotnode(expr, repeat=False), (x, Integer(2), x+2)))
    assert 'digraph' in text
    text = dotprint(x+x**2, repeat=False)
    assert all(e in text for e in dotedges(x+x**2, repeat=False))
    assert all(n in text for n in map(lambda expr: dotnode(expr, repeat=False), (x, Integer(2), x**2)))
    assert 'digraph' in text
    text = dotprint(x+x**2, repeat=True)
    assert all(e in text for e in dotedges(x+x**2, repeat=True))
    assert all(n in text for n in map(lambda expr: dotnode(expr, pos=()), [x + x**2]))
    text = dotprint(x**x, repeat=True)
    assert all(e in text for e in dotedges(x**x, repeat=True))
    assert all(n in text for n in [dotnode(x, pos=(0,)), dotnode(x, pos=(1,))])
    assert 'digraph' in text 
Example #6
Source File: arithmetic.py    From mathematics_dataset with Apache License 2.0 6 votes vote down vote up
def _mul_op(value, sample_args, rationals_allowed):
  """Returns sampled args for `ops.Mul`."""
  if sample_args.count >= 3:
    _, op_args, sample_args = _div_op(value, sample_args, rationals_allowed)
    op_args = [op_args[0], sympy.Integer(1) / op_args[1]]
  elif sample_args.count == 1:
    entropy, sample_args = sample_args.peel()
    assert _entropy_of_factor_split(value) >= entropy
    op_args = _split_factors(value)
  else:
    assert sample_args.count == 2
    entropy, sample_args = sample_args.peel()
    numer = sympy.numer(value)
    denom = sympy.denom(value)
    p1, p2 = _split_factors(numer)
    entropy -= _entropy_of_factor_split(numer)
    mult = number.integer(entropy, signed=True, min_abs=1, coprime_to=p1)
    op_args = [p1 / (mult * denom), p2 * mult]

  if random.choice([False, True]):
    op_args = list(reversed(op_args))

  return ops.Mul, op_args, sample_args 
Example #7
Source File: test_printing.py    From sympsi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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')))") 
Example #8
Source File: pauli.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _eval_commutator_SigmaZ(self, other, **hints):
        if self.name != other.name:
            return Integer(0)
        else:
            return -2 * self 
Example #9
Source File: test_commutator.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _eval_commutator_Bar(self, bar):
        return Integer(0) 
Example #10
Source File: pauli.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _eval_anticommutator_SigmaZ(self, other, **hints):
        return Integer(0) 
Example #11
Source File: pauli.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _eval_anticommutator_SigmaY(self, other, **hints):
        return I * Integer(1) 
Example #12
Source File: test_printing.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_tensorproduct():
    tp = TensorProduct(JzKet(1, 1), JzKet(1, 0))
    assert str(tp) == '|1,1>x|1,0>'
    assert pretty(tp) == '|1,1>x |1,0>'
    assert upretty(tp) == u('❘1,1⟩⨂ ❘1,0⟩')
    assert latex(tp) == \
        r'{{\left|1,1\right\rangle }}\otimes {{\left|1,0\right\rangle }}'
    sT(tp, "TensorProduct(JzKet(Integer(1),Integer(1)), JzKet(Integer(1),Integer(0)))") 
Example #13
Source File: pauli.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _eval_anticommutator_SigmaMinus(self, other, **hints):
        return Integer(1) 
Example #14
Source File: test_represent.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_scalar_numpy():
    if not np:
        skip("numpy not installed.")

    assert represent(Integer(1), format='numpy') == 1
    assert represent(Float(1.0), format='numpy') == 1.0
    assert represent(1.0 + I, format='numpy') == 1.0 + 1.0j 
Example #15
Source File: test_anticommutator.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _eval_anticommutator_Foo(self, foo):
        return Integer(1) 
Example #16
Source File: test_innerproduct.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _eval_innerproduct_FooBra(self, bra):
        return Integer(1) 
Example #17
Source File: test_innerproduct.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_doit():
    f = FooKet('foo')
    b = BarBra('bar')
    assert InnerProduct(b, f).doit() == I
    assert InnerProduct(Dagger(f), Dagger(b)).doit() == -I
    assert InnerProduct(Dagger(f), f).doit() == Integer(1) 
Example #18
Source File: test_represent.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_scalar_sympy():
    assert represent(Integer(1)) == Integer(1)
    assert represent(Float(1.0)) == Float(1.0)
    assert represent(1.0 + I) == 1.0 + I 
Example #19
Source File: pauli.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _eval_commutator_SigmaY(self, other, **hints):
        if self.name != other.name:
            return Integer(0)
        else:
            return I * SigmaZ(self.name) 
Example #20
Source File: pauli.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _eval_commutator_SigmaX(self, other, **hints):
        if self.name != other.name:
            return Integer(0)
        else:
            return SigmaZ(self.name) 
Example #21
Source File: pauli.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __mul__(self, other):

        if isinstance(other, SigmaOpBase) and self.name != other.name:
            # Pauli matrices with different labels commute; sort by name
            if self.name < other.name:
                return Mul(self, other)
            else:
                return Mul(other, self)

        if isinstance(other, SigmaX) and self.name == other.name:
            return (Integer(1) - SigmaZ(self.name))/2

        if isinstance(other, SigmaY) and self.name == other.name:
            return - I * (Integer(1) - SigmaZ(self.name))/2

        if isinstance(other, SigmaZ) and self.name == other.name:
            # (SigmaX(self.name) - I * SigmaY(self.name))/2
            return SigmaMinus(self.name)

        if isinstance(other, SigmaMinus) and self.name == other.name:
            return Integer(0)

        if isinstance(other, SigmaPlus) and self.name == other.name:
            return Integer(1)/2 - SigmaZ(self.name)/2

        if isinstance(other, Mul):
            args1 = tuple(arg for arg in other.args if arg.is_commutative)
            args2 = tuple(arg for arg in other.args if not arg.is_commutative)
            x = self
            for y in args2:
                x = x * y
            return Mul(*args1) * x

        return Mul(self, other) 
Example #22
Source File: pauli.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _eval_anticommutator_SigmaPlus(self, other, **hints):
        return Integer(1) 
Example #23
Source File: pauli.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _eval_anticommutator_SigmaY(self, other, **hints):
        return - I * Integer(1) 
Example #24
Source File: pauli.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _eval_anticommutator_SigmaX(self, other, **hints):
        return Integer(1) 
Example #25
Source File: pauli.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _eval_anticommutator_SigmaZ(self, other, **hints):
        return Integer(0) 
Example #26
Source File: pauli.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _eval_commutator_SigmaY(self, other, **hints):
        if self.name != other.name:
            return Integer(0)
        else:
            return I * SigmaZ(self.name) 
Example #27
Source File: pauli.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __mul__(self, other):

        if isinstance(other, SigmaOpBase) and self.name != other.name:
            # Pauli matrices with different labels commute; sort by name
            if self.name < other.name:
                return Mul(self, other)
            else:
                return Mul(other, self)

        if isinstance(other, SigmaX) and self.name == other.name:
            return I * SigmaY(self.name)

        if isinstance(other, SigmaY) and self.name == other.name:
            return - I * SigmaX(self.name)

        if isinstance(other, SigmaZ) and self.name == other.name:
            return Integer(1)

        if isinstance(other, SigmaMinus) and self.name == other.name:
            return - SigmaMinus(self.name)

        if isinstance(other, SigmaPlus) and self.name == other.name:
            return SigmaPlus(self.name)

        if isinstance(other, Mul):
            args1 = tuple(arg for arg in other.args if arg.is_commutative)
            args2 = tuple(arg for arg in other.args if not arg.is_commutative)
            x = self
            for y in args2:
                x = x * y
            return Mul(*args1) * x

        return Mul(self, other) 
Example #28
Source File: pauli.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _eval_anticommutator_SigmaY(self, other, **hints):
        return Integer(0) 
Example #29
Source File: boson.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _eval_commutator_BosonOp(self, other, **hints):
        if self.name == other.name:
            # [a^\dagger, a] = -1
            if not self.is_annihilation and other.is_annihilation:
                return Integer(-1)

        elif 'independent' in hints and hints['independent']:
            # [a, b] = 0
            return Integer(0)

        return None 
Example #30
Source File: pauli.py    From sympsi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __mul__(self, other):

        if other == Integer(1):
            return self

        if isinstance(other, SigmaOpBase) and self.name != other.name:
            # Pauli matrices with different labels commute; sort by name
            if self.name < other.name:
                return Mul(self, other)
            else:
                return Mul(other, self)

        if isinstance(other, SigmaX) and self.name == other.name:
            return (Integer(1) + SigmaZ(self.name))/2

        if isinstance(other, SigmaY) and self.name == other.name:
            return I * (Integer(1) + SigmaZ(self.name))/2

        if isinstance(other, SigmaZ) and self.name == other.name:
            #-(SigmaX(self.name) + I * SigmaY(self.name))/2
            return -SigmaPlus(self.name)

        if isinstance(other, SigmaMinus) and self.name == other.name:
            return (Integer(1) + SigmaZ(self.name))/2

        if isinstance(other, SigmaPlus) and self.name == other.name:
            return Integer(0)

        if isinstance(other, Mul):
            args1 = tuple(arg for arg in other.args if arg.is_commutative)
            args2 = tuple(arg for arg in other.args if not arg.is_commutative)
            x = self
            for y in args2:
                x = x * y
            return Mul(*args1) * x

        return Mul(self, other)