当前位置: 首页>>代码示例>>Python>>正文


Python sympy.expand方法代码示例

本文整理汇总了Python中sympy.expand方法的典型用法代码示例。如果您正苦于以下问题:Python sympy.expand方法的具体用法?Python sympy.expand怎么用?Python sympy.expand使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sympy的用法示例。


在下文中一共展示了sympy.expand方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: optm

# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import expand [as 别名]
def optm(quboh,numM):
	try:
		import sympy
	except ImportError:
		raise ImportError("optm() requires sympy. Please install before call this function.") 
	optm_E = sympy.expand(quboh) 
	symbol_list = ["q"+str(i) for i in range(numM)] 
	sympy.var(' '.join(symbol_list),positive=True) 

	symbol_list_proto = list(optm_E.free_symbols) 
	for i in range(len(symbol_list_proto)): 
		optm_E = optm_E.subs(symbol_list_proto[i]*symbol_list_proto[i],symbol_list_proto[i]) 

	optm_M = np.zeros((numM,numM)) 

	for i in range(numM): 
		for j in range(i+1,numM): 
			optm_M[i][j] = optm_E.coeff(symbol_list[i]+"*"+symbol_list[j]) 

		temp1 = sympy.poly(optm_E.coeff(symbol_list[i])) 
		optm_M[i][i] = sympy.poly(optm_E.coeff(symbol_list[i])).coeff_monomial(1) 

	return optm_M 
开发者ID:Blueqat,项目名称:Blueqat,代码行数:25,代码来源:opt.py

示例2: simplify_surd

# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import expand [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) 
开发者ID:deepmind,项目名称:mathematics_dataset,代码行数:25,代码来源:arithmetic.py

示例3: expand

# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import expand [as 别名]
def expand(value, sample_args, context=None):
  """E.g., "Expand (x**2 + 1)**2."."""
  del value  # not used
  if context is None:
    context = composition.Context()
  variable = sympy.Symbol(context.pop())
  entropy, sample_args = sample_args.peel()

  min_order = 1
  max_order = 5
  order = random.randint(min_order, max_order)
  entropy -= math.log10(max_order - min_order + 1)
  expression_ = polynomials.sample_with_brackets(variable, order, entropy)
  expanded = sympy.expand(expression_)
  template = random.choice([
      'Expand {expression}.'
  ])
  return example.Problem(
      question=example.question(context, template, expression=expression_),
      answer=expanded) 
开发者ID:deepmind,项目名称:mathematics_dataset,代码行数:22,代码来源:polynomials.py

示例4: run_benchmark

# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import expand [as 别名]
def run_benchmark(n):
    a0 = symbols("a0")
    a1 = symbols("a1")
    e = a0 + a1
    f = 0;
    for i in range(2, n):
        s = symbols("a%s" % i)
        e = e + s
        f = f + s
    f = -f
    t1 = clock()
    e = expand(e**2)
    e = e.xreplace({a0: f})
    e = expand(e)
    t2 = clock()
    print("%s ms" % (1000 * (t2 - t1))) 
开发者ID:symengine,项目名称:symengine.py,代码行数:18,代码来源:expand6.py

示例5: run_benchmark

# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import expand [as 别名]
def run_benchmark(n):
    a0 = symbols("a0")
    a1 = symbols("a1")
    e = a0 + a1
    f = 0;
    for i in range(2, n):
        s = symbols("a%s" % i)
        e = e + sin(s)
        f = f + sin(s)
    f = -f
    t1 = clock()
    e = expand(e**2)
    e = e.xreplace({a0: f})
    e = expand(e)
    t2 = clock()
    print("%s ms" % (1000 * (t2 - t1))) 
开发者ID:symengine,项目名称:symengine.py,代码行数:18,代码来源:expand6b.py

示例6: _integrate_exact

# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import expand [as 别名]
def _integrate_exact(f, c2):
    xi = sympy.DeferredVector("xi")
    pxi = (
        c2[0] * 0.25 * (1.0 + xi[0]) * (1.0 + xi[1])
        + c2[1] * 0.25 * (1.0 - xi[0]) * (1.0 + xi[1])
        + c2[2] * 0.25 * (1.0 - xi[0]) * (1.0 - xi[1])
        + c2[3] * 0.25 * (1.0 + xi[0]) * (1.0 - xi[1])
    )
    pxi = [sympy.expand(pxi[0]), sympy.expand(pxi[1])]
    # determinant of the transformation matrix
    det_J = +sympy.diff(pxi[0], xi[0]) * sympy.diff(pxi[1], xi[1]) - sympy.diff(
        pxi[1], xi[0]
    ) * sympy.diff(pxi[0], xi[1])
    # we cannot use abs(), see <https://github.com/sympy/sympy/issues/4212>.
    abs_det_J = sympy.Piecewise((det_J, det_J >= 0), (-det_J, det_J < 0))

    g_xi = f(pxi)

    exact = sympy.integrate(
        sympy.integrate(abs_det_J * g_xi, (xi[1], -1, 1)), (xi[0], -1, 1)
    )
    return float(exact) 
开发者ID:nschloe,项目名称:quadpy,代码行数:24,代码来源:test_c2.py

示例7: _surd_coefficients

# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import expand [as 别名]
def _surd_coefficients(sympy_exp):
  """Extracts coefficients a, b, where sympy_exp = a + b * sqrt(base)."""
  sympy_exp = sympy.simplify(sympy.expand(sympy_exp))

  def extract_b(b_sqrt_base):
    """Returns b from expression of form b * sqrt(base)."""
    if isinstance(b_sqrt_base, sympy.Pow):
      # Just form sqrt(base)
      return 1
    else:
      assert isinstance(b_sqrt_base, sympy.Mul)
      assert len(b_sqrt_base.args) == 2
      assert b_sqrt_base.args[0].is_rational
      assert isinstance(b_sqrt_base.args[1], sympy.Pow)  # should be sqrt.
      return b_sqrt_base.args[0]

  if sympy_exp.is_rational:
    # Form: a.
    return sympy_exp, 0
  elif isinstance(sympy_exp, sympy.Add):
    # Form: a + b * sqrt(base)
    assert len(sympy_exp.args) == 2
    assert sympy_exp.args[0].is_rational
    a = sympy_exp.args[0]
    b = extract_b(sympy_exp.args[1])
    return a, b
  else:
    # Form: b * sqrt(base).
    return 0, extract_b(sympy_exp) 
开发者ID:deepmind,项目名称:mathematics_dataset,代码行数:31,代码来源:arithmetic.py

示例8: _make_modules

# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import expand [as 别名]
def _make_modules(entropy):
  """Returns modules given "difficulty" parameters."""
  sample_args_pure = composition.PreSampleArgs(1, 1, *entropy)
  sample_args_composed = composition.PreSampleArgs(2, 4, *entropy)
  sample_args_mixed = composition.PreSampleArgs(1, 4, *entropy)

  return {
      'coefficient_named':
          functools.partial(coefficient_named, None, sample_args_pure),
      'evaluate':
          functools.partial(evaluate, None, sample_args_pure),
      'evaluate_composed':
          functools.partial(evaluate, None, sample_args_composed),
      # TODO(b/124038948): consider doing pure sample args for 'add'?
      'add':
          functools.partial(add, None, sample_args_mixed),
      'expand':
          functools.partial(expand, None, sample_args_pure),
      'collect':
          functools.partial(collect, None, sample_args_pure),
      'compose':
          functools.partial(compose, None, sample_args_mixed),

      # Rearranging powers:
      'simplify_power':
          functools.partial(simplify_power, None, sample_args_pure),
  } 
开发者ID:deepmind,项目名称:mathematics_dataset,代码行数:29,代码来源:polynomials.py

示例9: run_benchmark

# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import expand [as 别名]
def run_benchmark(n):
    x, y = symbols("x y")
    e = (1 + sqrt(3) * x + sqrt(5) * y) ** n
    f = e * (e + sqrt(7))
    t1 = clock()
    f = expand(f)
    t2 = clock()
    print("%s ms" % (1000 * (t2 - t1))) 
开发者ID:symengine,项目名称:symengine.py,代码行数:10,代码来源:expand7.py

示例10: doit

# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import expand [as 别名]
def doit(self, **hints):
        """Expand the density operator into an outer product format.

        Examples
        =========

        >>> from sympsi.state import Ket
        >>> from sympsi.density import Density
        >>> from sympsi.operator import Operator
        >>> A = Operator('A')
        >>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
        >>> d.doit()
        0.5*|0><0| + 0.5*|1><1|

        """

        terms = []
        for (state, prob) in self.args:
            state = state.expand()  # needed to break up (a+b)*c
            if (isinstance(state, Add)):
                for arg in product(state.args, repeat=2):
                    terms.append(prob *
                                 self._generate_outer_prod(arg[0], arg[1]))
            else:
                terms.append(prob *
                             self._generate_outer_prod(state, state))

        return Add(*terms) 
开发者ID:sympsi,项目名称:sympsi,代码行数:30,代码来源:density.py

示例11: low_rank_hafnian

# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import expand [as 别名]
def low_rank_hafnian(G):
    r"""Returns the hafnian of the low rank matrix :math:`\bm{A} = \bm{G} \bm{G}^T` where :math:`\bm{G}` is rectangular of size
    :math:`n \times r`  with :math:`r \leq n`.

    Note that the rank of :math:`\bm{A}` is precisely :math:`r`.

    The hafnian is calculated using the algorithm described in Appendix C of
    *A faster hafnian formula for complex matrices and its benchmarking on a supercomputer*,
    :cite:`bjorklund2018faster`.

    Args:
        G (array): factorization of the low rank matrix A = G @ G.T.

    Returns:
        (complex): hafnian of A.
    """
    n, r = G.shape
    if n % 2 != 0:
        return 0
    if r == 1:
        return factorial2(n - 1) * np.prod(G)
    poly = 1
    x = symbols("x0:" + str(r))
    for k in range(n):
        term = 0
        for j in range(r):
            term += G[k, j] * x[j]
        poly = expand(poly * term)

    comb = partitions(r, n // 2)
    haf_val = 0.0
    for c in comb:
        monomial = 1
        facts = 1
        for i, pi in enumerate(c):
            monomial *= x[i] ** (2 * pi)
            facts = facts * factorial2(2 * pi - 1)
        haf_val += complex(poly.coeff(monomial) * facts)
    return haf_val 
开发者ID:XanaduAI,项目名称:thewalrus,代码行数:41,代码来源:_low_rank_haf.py

示例12: s_polynomial

# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import expand [as 别名]
def s_polynomial(f, g):
    return expand(lcm(LM(f), LM(g))*(1/LT(f)*f - 1/LT(g)*g)) 
开发者ID:springer-math,项目名称:dynamical-systems-with-applications-using-python,代码行数:4,代码来源:Program_10c.py

示例13: convert_to_dict

# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import expand [as 别名]
def convert_to_dict(node: Node) -> dict:
    children = OrderedDict()
    for node_property in node.properties:
        children[node_property] = convert_to_dict(node[node_property][0])
    simplified = str(sympy.expand(parse_expr(''.join(to_token_sequence(node, [])))))
    if len(children) > 0:
        return dict(Name=node.name, Children=children, Symbol=simplified)
    else:
        return dict(Name=node.name, Symbol=simplified) 
开发者ID:mast-group,项目名称:eqnet,代码行数:11,代码来源:polyexpressions.py

示例14: optx

# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import expand [as 别名]
def optx(quboh): 
	try:
		import sympy
	except ImportError:
		raise ImportError("optx() requires sympy. Please install before call this function.")

	optx_E = sympy.expand(quboh)
	symbol_list = list(optx_E.free_symbols)
	sympy.var(' '.join(map(str,symbol_list)),positive=True)
	for i in range(len(symbol_list)):
		optx_E = optx_E.subs(symbol_list[i]*symbol_list[i],symbol_list[i])
	return optx_E 
开发者ID:Blueqat,项目名称:Blueqat,代码行数:14,代码来源:opt.py

示例15: expand_qubo

# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import expand [as 别名]
def expand_qubo(self,qubo):
		try:
			import sympy
		except ImportError:
			raise ImportError("optm() requires sympy. Please install before call this function.")
		f = sympy.expand(qubo)
		deg = sympy.poly(f).degree()

		for i in range(deg):
			for j in f.free_symbols:
				f = f.subs(j**(deg-i),j)
		return f 
开发者ID:Blueqat,项目名称:Blueqat,代码行数:14,代码来源:opt.py


注:本文中的sympy.expand方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。