本文整理汇总了Python中sympy.Integer方法的典型用法代码示例。如果您正苦于以下问题:Python sympy.Integer方法的具体用法?Python sympy.Integer怎么用?Python sympy.Integer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sympy
的用法示例。
在下文中一共展示了sympy.Integer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: simplify_surd
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Integer [as 别名]
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)
示例2: _mul_op
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Integer [as 别名]
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
示例3: test_dotprint
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Integer [as 别名]
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
示例4: test_conv10
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Integer [as 别名]
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]]))
示例5: _expand_powers
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Integer [as 别名]
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
示例6: test_scalars
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Integer [as 别名]
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
示例7: test_commutator
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Integer [as 别名]
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')))")
示例8: place_value
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Integer [as 别名]
def place_value(value, sample_args, context=None):
"""E.g., "Q: What is the tens digit of 31859? A: 5."""
del value # unused for now
if context is None:
context = composition.Context()
entropy, sample_args = sample_args.peel()
integer = number.integer(entropy, signed=False, min_abs=1)
(entity,) = context.sample(sample_args, [integer])
integer_as_string = str(integer)
num_digits = len(integer_as_string)
firsts = ['', 'ten ', 'hundred ']
seconds = [
'thousands', 'millions', 'billions', 'trillions', 'quadrillions',
'quintillions', 'sextillions', 'septillions', 'octillions', 'nonillions',
'decillions',
]
place_names = ['units', 'tens', 'hundreds']
for second in seconds:
for first in firsts:
place_names.append(first + second)
place = random.randint(1, num_digits) # 1 = units, 2 = tens, etc.
place_name = place_names[place - 1]
answer = sympy.Integer(integer_as_string[num_digits - place])
return example.Problem(
question=example.question(
context,
'What is the {place_name} digit of {integer}?',
place_name=place_name, integer=entity.expression_else_handle),
answer=answer)
# TODO(b/124040078): add to composition system?
示例9: _split_factors
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Integer [as 别名]
def _split_factors(integer):
"""Randomly factors integer into product of two integers."""
assert integer.is_Integer
if integer == 0:
return [1, 0]
# Gives dict of form {factor: multiplicity}
factors = sympy.factorint(integer)
left = sympy.Integer(1)
right = sympy.Integer(1)
for factor, mult in six.iteritems(factors):
left_mult = random.randint(0, mult)
right_mult = mult - left_mult
left *= factor ** left_mult
right *= factor ** right_mult
return left, right
示例10: integer
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Integer [as 别名]
def integer(entropy, signed, min_abs=0, coprime_to=1):
"""Returns an integer from a set of size ceil(10**entropy).
If `signed` is True, then includes negative integers, otherwise includes just
positive integers.
Args:
entropy: Float >= 0.
signed: Boolean. Whether to also return negative numbers.
min_abs: Integer >= 0. The minimum absolute value.
coprime_to: Optional integer >= 1. The returned integer is guaranteed to be
coprime to `coprime_to`, with entropy still accounted for.
Returns:
Integer.
"""
assert isinstance(min_abs, int) and not isinstance(min_abs, bool)
coprime_to = abs(coprime_to)
assert min_abs >= 0
max_ = math.pow(10, entropy)
max_ += min_abs
if coprime_to >= 2:
max_ = max_ / _coprime_density(coprime_to) + 1
if signed:
max_ = int(math.ceil(max_ / 2))
range_ = [-max_, max_]
else:
max_ = int(math.ceil(max_))
range_ = [min_abs, max_]
while True:
value = random.randint(*range_)
if abs(value) >= min_abs and sympy.gcd(value, coprime_to) == 1:
break
return sympy.Integer(value)
示例11: __init__
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Integer [as 别名]
def __init__(self, value):
super(Constant, self).__init__([])
if isinstance(value, six.integer_types):
value = sympy.Integer(value)
self._value = value
示例12: _is_simple
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Integer [as 别名]
def _is_simple(self):
"""Returns whether it's a simple number, rather than a division or neg."""
if isinstance(self._value, sympy.Symbol):
return True
elif (isinstance(self._value, int)
or isinstance(self._value, sympy.Integer)
or isinstance(self._value, display.Decimal)
or isinstance(self._value, np.int64)):
return self._value >= 0
elif isinstance(self._value, sympy.Rational):
return False
elif isinstance(self._value, sympy.Function):
return True
else:
raise ValueError('Unknown type {}'.format(type(self._value)))
示例13: integrate
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Integer [as 别名]
def integrate(coefficients, axis):
"""Integrate coefficients (corresponding to polynomial) along axis."""
coefficients = np.asarray(coefficients)
length = coefficients.shape[axis]
broadcast_shape = np.ones(coefficients.ndim, dtype=np.int32)
broadcast_shape[axis] = length
powers = np.array([sympy.Integer(i) for i in range(1, length + 1)])
powers = powers.reshape(broadcast_shape)
result_unpadded = coefficients / powers
pad = [(1 if i == axis else 0, 0) for i in range(coefficients.ndim)]
return np.pad(result_unpadded, pad, 'constant', constant_values=0)
示例14: _to_string
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Integer [as 别名]
def _to_string(self, number):
"""Converts an integer or rational to words."""
if isinstance(number, sympy.Integer) or isinstance(number, int):
words = self._integer_to_words(number)
join_char = '-' if self._join_number_words_with_hyphens else ' '
return join_char.join(words)
elif isinstance(number, sympy.Rational):
return self._rational_to_string(number)
else:
raise ValueError('Unable to handle number {} with type {}.'
.format(number, type(number)))
示例15: __init__
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Integer [as 别名]
def __init__(self, value, base):
"""Initializes a `NumberInBase`.
Args:
value: Positive or negative integer.
base: Integer in the range [2, 36].
Raises:
ValueError: If base is not in the range [2, 36] (since this is the limit
that can be represented by 10 numbers plus 26 letters).
"""
if not 2 <= base <= 36:
raise ValueError('base={} must be in the range [2, 36]'.format(base))
self._value = value
self._base = base
chars = []
remainder = abs(value)
while True:
digit = remainder % base
char = str(digit) if digit <= 9 else chr(ord('a') + digit - 10)
chars.append(char)
remainder = int(remainder / base)
if remainder == 0:
break
if value < 0:
chars.append('-')
self._str = ''.join(reversed(chars))