本文整理匯總了Python中sympy.sympify方法的典型用法代碼示例。如果您正苦於以下問題:Python sympy.sympify方法的具體用法?Python sympy.sympify怎麽用?Python sympy.sympify使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類sympy
的用法示例。
在下文中一共展示了sympy.sympify方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: calc
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import sympify [as 別名]
def calc(jarvis, s, calculator=sympy.sympify, formatter=None, do_evalf=True):
s = format_expression(s)
try:
result = calculator(s)
except sympy.SympifyError:
jarvis.say("Error: Something is wrong with your expression", Fore.RED)
return
except NotImplementedError:
jarvis.say("Sorry, cannot solve", Fore.RED)
return
if formatter is not None:
result = formatter(result)
if do_evalf:
result = result.evalf()
jarvis.say(str(result), Fore.BLUE)
示例2: print_mathml
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import sympify [as 別名]
def print_mathml(expr, **settings):
"""
Prints a pretty representation of the MathML code for expr
Examples
========
>>> ##
>>> from sympy.printing.mathml import print_mathml
>>> from sympy.abc import x
>>> print_mathml(x+1) #doctest: +NORMALIZE_WHITESPACE
<apply>
<plus/>
<ci>x</ci>
<cn>1</cn>
</apply>
"""
s = MathMLPrinter(settings)
xml = s._print(sympify(expr))
s.apply_patch()
pretty_xml = xml.toprettyxml()
s.restore_patch()
print(pretty_xml)
示例3: sdm_from_vector
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import sympify [as 別名]
def sdm_from_vector(vec, O, K, **opts):
"""
Create an sdm from an iterable of expressions.
Coefficients are created in the ground field ``K``, and terms are ordered
according to monomial order ``O``. Named arguments are passed on to the
polys conversion code and can be used to specify for example generators.
Examples
========
>>> from sympy.polys.distributedmodules import sdm_from_vector
>>> from sympy.abc import x, y, z
>>> from sympy.polys import QQ, lex
>>> sdm_from_vector([x**2+y**2, 2*z], lex, QQ)
[((1, 0, 0, 1), 2), ((0, 2, 0, 0), 1), ((0, 0, 2, 0), 1)]
"""
dics, gens = parallel_dict_from_expr(sympify(vec), **opts)
dic = {}
for i, d in enumerate(dics):
for k, v in d.items():
dic[(i,) + k] = K.convert(v)
return sdm_from_dict(dic, O)
示例4: test_conv7b
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import sympify [as 別名]
def test_conv7b():
x = sympy.Symbol("x")
y = sympy.Symbol("y")
assert sympify(sympy.sin(x/3)) == sin(Symbol("x") / 3)
assert sympify(sympy.sin(x/3)) != cos(Symbol("x") / 3)
assert sympify(sympy.cos(x/3)) == cos(Symbol("x") / 3)
assert sympify(sympy.tan(x/3)) == tan(Symbol("x") / 3)
assert sympify(sympy.cot(x/3)) == cot(Symbol("x") / 3)
assert sympify(sympy.csc(x/3)) == csc(Symbol("x") / 3)
assert sympify(sympy.sec(x/3)) == sec(Symbol("x") / 3)
assert sympify(sympy.asin(x/3)) == asin(Symbol("x") / 3)
assert sympify(sympy.acos(x/3)) == acos(Symbol("x") / 3)
assert sympify(sympy.atan(x/3)) == atan(Symbol("x") / 3)
assert sympify(sympy.acot(x/3)) == acot(Symbol("x") / 3)
assert sympify(sympy.acsc(x/3)) == acsc(Symbol("x") / 3)
assert sympify(sympy.asec(x/3)) == asec(Symbol("x") / 3)
示例5: test_conv10b
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import sympify [as 別名]
def test_conv10b():
A = sympy.Matrix([[sympy.Symbol("x"), sympy.Symbol("y")],
[sympy.Symbol("z"), sympy.Symbol("t")]])
assert sympify(A) == DenseMatrix(2, 2, [Symbol("x"), Symbol("y"),
Symbol("z"), Symbol("t")])
B = sympy.Matrix([[1, 2], [3, 4]])
assert sympify(B) == DenseMatrix(2, 2, [Integer(1), Integer(2), Integer(3),
Integer(4)])
C = sympy.Matrix([[7, sympy.Symbol("y")],
[sympy.Function("g")(sympy.Symbol("z")), 3 + 2*sympy.I]])
assert sympify(C) == DenseMatrix(2, 2, [Integer(7), Symbol("y"),
function_symbol("g",
Symbol("z")),
3 + 2*I])
示例6: test_conv11
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import sympify [as 別名]
def test_conv11():
x = sympy.Symbol("x")
y = sympy.Symbol("y")
x1 = Symbol("x")
y1 = Symbol("y")
f = sympy.Function("f")
f1 = Function("f")
e1 = diff(f(2*x, y), x)
e2 = diff(f1(2*x1, y1), x1)
e3 = diff(f1(2*x1, y1), y1)
assert sympify(e1) == e2
assert sympify(e1) != e3
assert e2._sympy_() == e1
assert e3._sympy_() != e1
示例7: test_tuples_lists
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import sympify [as 別名]
def test_tuples_lists():
x = sympy.Symbol("x")
y = sympy.Symbol("y")
z = sympy.Symbol("z")
L = [x, y, z, x*y, z**y]
t = (x, y, z, x*y, z**y)
x = Symbol("x")
y = Symbol("y")
z = Symbol("z")
l2 = [x, y, z, x*y, z**y]
t2 = (x, y, z, x*y, z**y)
assert sympify(L) == l2
assert sympify(t) == t2
assert sympify(L) != t2
assert sympify(t) != l2
assert L == l2
assert t == t2
assert L != t2
assert t != l2
示例8: test_constants
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import sympify [as 別名]
def test_constants():
assert sympify(sympy.E) == E
assert sympy.E == E._sympy_()
assert sympify(sympy.pi) == pi
assert sympy.pi == pi._sympy_()
assert sympify(sympy.GoldenRatio) == GoldenRatio
assert sympy.GoldenRatio == GoldenRatio._sympy_()
assert sympify(sympy.Catalan) == Catalan
assert sympy.Catalan == Catalan._sympy_()
assert sympify(sympy.EulerGamma) == EulerGamma
assert sympy.EulerGamma == EulerGamma._sympy_()
assert sympify(sympy.oo) == oo
assert sympy.oo == oo._sympy_()
assert sympify(sympy.zoo) == zoo
assert sympy.zoo == zoo._sympy_()
assert sympify(sympy.nan) == nan
assert sympy.nan == nan._sympy_()
示例9: eval
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import sympify [as 別名]
def eval(cls, args):
new_args = args[0], sympify(args[1])
exp = new_args[1]
#simplify hs**1 -> hs
if exp == 1:
return args[0]
#simplify hs**0 -> 1
if exp == 0:
return sympify(1)
#check (and allow) for hs**(x+42+y...) case
if len(exp.atoms()) == 1:
if not (exp.is_Integer and exp >= 0 or exp.is_Symbol):
raise ValueError('Hilbert spaces can only be raised to \
positive integers or Symbols: %r' % exp)
else:
for power in exp.atoms():
if not (power.is_Integer or power.is_Symbol):
raise ValueError('Tensor powers can only contain integers \
or Symbols: %r' % power)
return new_args
示例10: _qsympify_sequence
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import sympify [as 別名]
def _qsympify_sequence(seq):
"""Convert elements of a sequence to standard form.
This is like sympify, but it performs special logic for arguments passed
to QExpr. The following conversions are done:
* (list, tuple, Tuple) => _qsympify_sequence each element and convert
sequence to a Tuple.
* basestring => Symbol
* Matrix => Matrix
* other => sympify
Strings are passed to Symbol, not sympify to make sure that variables like
'pi' are kept as Symbols, not the SymPy built-in number subclasses.
Examples
========
>>> from sympsi.qexpr import _qsympify_sequence
>>> _qsympify_sequence((1,2,[3,4,[1,]]))
(1, 2, (3, 4, (1,)))
"""
return tuple(__qsympify_sequence_helper(seq))
示例11: _sexpr_to_ts
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import sympify [as 別名]
def _sexpr_to_ts (e, dummy_idx=0, strict=False, num_to_sym=False):
'''
A single string expression (sexpr) to Tensor Shape expressions (ts)
Converts shorthand dummy/empty placeholders to dummy TSs
'''
if isinstance(e, DimExpr):
t = e
else:
assert isinstance(e, str)
if e.isdigit() and num_to_sym: e = '_' #convert to dummy var
if e == '' or e =='_':
t = dummy_dvar(dummy_idx)
dummy_idx += 1
elif e == '^':
#TODO: better way to handle '^' ?
t = DimExpr(Symbol(e))
else:
#TODO: strict: check if all dim vars in e are previously declared?
t = DimExpr(sympify(e))
return t, dummy_idx
示例12: _correct_old_unit_registry
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import sympify [as 別名]
def _correct_old_unit_registry(data, sympify=False):
lut = {}
for k, v in data.items():
unsan_v = list(v)
if sympify:
unsan_v[1] = cached_sympify(v[1])
if len(unsan_v) == 4:
# old unit registry so we need to add SI-prefixability to the registry
# entry and correct the base_value to be in MKS units
if k in default_unit_symbol_lut:
unsan_v.append(default_unit_symbol_lut[k][4])
else:
unsan_v.append(False)
dims = unsan_v[1]
for dim_factor in dims.as_ordered_factors():
dim, power = dim_factor.as_base_exp()
if dim == unyt_dims.mass:
unsan_v[0] /= 1000 ** float(power)
if dim == unyt_dims.length:
unsan_v[0] /= 100 ** float(power)
lut[k] = tuple(unsan_v)
for k in default_unit_symbol_lut:
if k not in lut:
lut[k] = default_unit_symbol_lut[k]
return lut
示例13: test_expressions
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import sympify [as 別名]
def test_expressions(expr: str):
qasm = """OPENQASM 2.0;
qreg q[1];
U({}, 2 * pi, pi / 2.0) q[0];
""".format(expr)
parser = QasmParser()
q0 = cirq.NamedQubit('q_0')
expected_circuit = Circuit()
expected_circuit.append(
QasmUGate(float(sympy.sympify(expr)) / np.pi, 2.0, 1 / 2.0)(q0))
parsed_qasm = parser.parse(qasm)
assert parsed_qasm.supportedFormat
assert not parsed_qasm.qelib1Include
ct.assert_allclose_up_to_global_phase(cirq.unitary(parsed_qasm.circuit),
cirq.unitary(expected_circuit),
atol=1e-10)
assert parsed_qasm.qregs == {'q': 1}
示例14: closest
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import sympify [as 別名]
def closest(sample_args, count=None):
"""Ask for the closest to a given value in a list."""
sample_args = sample_args()
context = composition.Context()
entropy, sample_args = sample_args.peel()
if count is None:
count = random.randint(*_closest_count_range(entropy))
display_multichoice = random.choice([False, True])
if display_multichoice:
_mark_choice_letters_used(count, context)
entropy_target, entropy_list = entropy * np.random.dirichlet([1, count])
target = integer_or_rational_or_decimal(entropy_target)
while True:
value_entropies = entropy_list * np.random.dirichlet(np.ones(count))
value_entropies = np.maximum(1, value_entropies)
values = [integer_or_rational_or_decimal(ent) for ent in value_entropies]
differences = [abs(sympy.sympify(value) - target) for value in values]
if len(sympy.FiniteSet(*differences)) == count: # all differences unique
break
target_and_entities = context.sample(sample_args, [target] + values)
target = target_and_entities[0]
entities = target_and_entities[1:]
min_difference = min(differences)
answer_index = differences.index(min_difference)
answer = entities[answer_index]
adjective = random.choice(['closest', 'nearest'])
if display_multichoice:
return _closest_multichoice_question(
context=context, entities=entities, target=target, adjective=adjective,
answer=answer)
else:
return _closest_in_list_question(
context=context, entities=entities, target=target, adjective=adjective,
answer=answer)
示例15: testSurdCoefficients
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import sympify [as 別名]
def testSurdCoefficients(self):
exp = sympy.sympify('1')
self.assertEqual(arithmetic._surd_coefficients(exp),
(1, 0))
exp = sympy.sympify('1/2')
self.assertEqual(arithmetic._surd_coefficients(exp),
(1/2, 0))
exp = sympy.sympify('sqrt(2)')
self.assertEqual(arithmetic._surd_coefficients(exp),
(0, 1))
exp = sympy.sympify('3*sqrt(2)')
self.assertEqual(arithmetic._surd_coefficients(exp),
(0, 3))
exp = sympy.sympify('3*sqrt(5)/2')
self.assertEqual(arithmetic._surd_coefficients(exp),
(0, 3/2))
exp = sympy.sympify('1 + 3 * sqrt(2)')
self.assertEqual(arithmetic._surd_coefficients(exp),
(1, 3))
exp = sympy.sympify('1/2 + 3 * sqrt(5) / 2')
self.assertEqual(arithmetic._surd_coefficients(exp),
(1/2, 3/2))
exp = sympy.sympify('sqrt(2)/(-1 + 2*sqrt(2))**2')
self.assertEqual(arithmetic._surd_coefficients(exp),
(8/49, 9/49))