本文整理汇总了Python中sympy.var方法的典型用法代码示例。如果您正苦于以下问题:Python sympy.var方法的具体用法?Python sympy.var怎么用?Python sympy.var使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sympy
的用法示例。
在下文中一共展示了sympy.var方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: optm
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import var [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
示例2: R3
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import var [as 别名]
def R3():
var('x y z')
f = x+y+z
t1 = clock()
a = [bool(f==f) for _ in range(10)]
t2 = clock()
return t2 - t1
示例3: compose
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import var [as 别名]
def compose(value, sample_args, context=None):
"""E.g., "Let f(x)=2x+1, let g(x)=3x+10. What is f(g(x))?"."""
del value # unused
if context is None:
context = composition.Context()
entropy, sample_args = sample_args.peel()
entropy_f, entropy_g = entropy * np.random.dirichlet([1, 1])
coeffs_f = polynomials.sample_coefficients([random.randint(1, 2)], entropy_f)
coeffs_g = polynomials.sample_coefficients([random.randint(1, 2)], entropy_g)
entity_f, entity_g = context.sample(
sample_args,
[composition.Polynomial(coeffs_f), composition.Polynomial(coeffs_g)])
variable = sympy.var(context.pop())
poly_f = polynomials.coefficients_to_polynomial(coeffs_f, variable)
poly_g = polynomials.coefficients_to_polynomial(coeffs_g, variable)
poly_f_g = poly_f.sympy().subs(variable, poly_g.sympy()).expand()
expression = composition.FunctionHandle(entity_f, entity_g).apply(variable)
template = random.choice(_TEMPLATES)
return example.Problem(
question=example.question(context, template, composed=expression),
answer=poly_f_g)
示例4: R2
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import var [as 别名]
def R2():
def hermite(n,y):
if n == 1: return 2*y
if n == 0: return 1
return (2*y*hermite(n-1,y) - 2*(n-1)*hermite(n-2,y)).expand()
t1 = clock()
hermite(15, var('y'))
t2 = clock()
return t2 - t1
示例5: R5
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import var [as 别名]
def R5():
def blowup(L,n):
for i in range(n):
L.append( (L[i] + L[i+1]) * L[i+2] )
def uniq(x):
v = list(set(x))
return v
var('x y z')
L = [x,y,z]
blowup(L,8)
t1 = clock()
L = uniq(L)
t2 = clock()
return t2 - t1
示例6: S1
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import var [as 别名]
def S1():
var("x y z")
e = (x+y+z+1)**7
f = e*(e+1)
t1 = clock()
f = f.expand()
t2 = clock()
return t2 - t1
示例7: S2
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import var [as 别名]
def S2():
var("x y z")
e = (x**sin(x) + y**cos(y) + z**(x + y))**100
t1 = clock()
f = e.expand()
t2 = clock()
return t2 - t1
示例8: S3a
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import var [as 别名]
def S3a():
var("x y z")
e = (x**y + y**z + z**x)**500
e = e.expand()
t1 = clock()
f = e.diff(x)
t2 = clock()
return t2 - t1
示例9: get_generating_function
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import var [as 别名]
def get_generating_function(f, T=None):
"""
Get the generating function
:param f: function addr
:param T: edges matrix of the function f
:return: the generating function
"""
if not T:
edges = [(a[0].addr, a[1].addr) for a in f.graph.edges()]
N = sorted([x for x in f.block_addrs])
T = []
for b1 in N:
T.append([])
for b2 in N:
if b1 == b2 or (b1, b2) in edges:
T[-1].append(1)
else:
T[-1].append(0)
else:
N = T[0]
T = sympy.Matrix(T)
z = sympy.var('z')
I = sympy.eye(len(N))
tmp = I - z * T
tmp.row_del(len(N) - 1)
tmp.col_del(0)
det_num = tmp.det()
det_den = (I - z * T).det()
quot = det_num / det_den
g_z = ((-1) ** (len(N) + 1)) * quot
return g_z
示例10: optx
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import var [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
示例11: add
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import var [as 别名]
def add(value, sample_args, context=None):
"""E.g., "Let f(x)=2x+1, g(x)=3x+2. What is 5*f(x) - 7*g(x)?"."""
is_question = context is None
if context is None:
context = composition.Context()
entropy, sample_args = sample_args.peel()
if value is None:
max_degree = 3
degree = random.randint(1, max_degree)
entropy -= math.log10(max_degree)
entropy_value = entropy / 2
entropy -= entropy_value
value = polynomials.sample_coefficients(
degree, entropy=entropy_value, min_non_zero=random.randint(1, 3))
value = composition.Polynomial(value)
c1, c2, coeffs1, coeffs2 = polynomials.coefficients_linear_split(
value.coefficients, entropy)
coeffs1 = polynomials.trim(coeffs1)
coeffs2 = polynomials.trim(coeffs2)
c1, c2, fn1, fn2 = context.sample(
sample_args,
[c1, c2, composition.Polynomial(coeffs1), composition.Polynomial(coeffs2)]
)
var = sympy.var(context.pop())
expression = (
c1.handle * fn1.handle.apply(var) + c2.handle * fn2.handle.apply(var))
if is_question:
answer = polynomials.coefficients_to_polynomial(value.coefficients, var)
answer = answer.sympy()
template = random.choice(_TEMPLATES)
return example.Problem(
question=example.question(context, template, composed=expression),
answer=answer)
else:
intermediate_symbol = context.pop()
intermediate = sympy.Function(intermediate_symbol)(var)
return composition.Entity(
context=context,
value=value,
description='Let {intermediate} = {composed}.',
handle=composition.FunctionHandle(intermediate_symbol),
intermediate=intermediate,
composed=expression)
示例12: __init__
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import var [as 别名]
def __init__(self, context, value, description='', handle=None,
expression=None, polynomial_variables=None,
**description_kwargs):
"""Initializes an entity.
Args:
context: Instance of `Context` keeping track of used symbols and child
entities (that may not explicitly occur in `description_kwargs`).
value: The value represented by this Entity.
description: String, describing this Entity. This can contain '{self}' as
a substring, in which case it will be substituted with a new handle
(and `context` must be non-None).
handle: Optional string/symbol that refers to this Entity. This must
always be provided if '{self}' does not occur in `description`.
expression: Optional string (or something that can be converted to a
string, like ops.Op or sympy.expr) representing the value of this
Entity, that can be used directly instead of using `handle`.
polynomial_variables: If `expression` provided, then for polynomial
entities, the variables used.
**description_kwargs: Dict of substitutions (including entities) for use
in `description`.
Raises:
ValueError: If handle specified and '{self}' in description; or neither.
"""
self._value = value
child_description, description_kwargs = expand_entities(
context, **description_kwargs)
if '{self}' in description:
if handle is not None:
raise ValueError('Cannot specify handle if {self} in description')
handle = context.pop()
description_kwargs['self'] = handle
handle = sympy.var(handle)
else:
if handle is None:
raise ValueError('Must specify handle if {self} not in description')
if isinstance(handle, str):
handle = sympy.var(handle)
if (isinstance(value, Polynomial)
and expression is not None
and polynomial_variables is None):
raise ValueError('Must provided polynomial_variables')
self._child_description = child_description
self._description = description.format(**description_kwargs)
self._handle = handle
self._expression = expression
self._polynomial_variables = polynomial_variables
# For checking that we don't use both the handle and the expression form of
# this entity.
self._handle_used = False
self._expression_used = False
示例13: get_path_n
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import var [as 别名]
def get_path_n(f, T=None):
# TODO cire paper here
"""
Get the formula to estimate the number of path of a function, given its longest path.
:param f: function addr
:param T: edges matrix of the function f
:return: formula to estimate the number of paths
"""
g_z = get_generating_function(f, T)
expr = g_z.as_numer_denom()[1]
rs = sympy.roots(expr)
D = len(set(rs.keys())) # number of distinct roots
d = sum(rs.values()) # number of roots
# get taylor coefficients
f = sympy.utilities.lambdify(list(g_z.free_symbols), g_z)
taylor_coeffs = mpmath.taylor(f, 0, d - 1) # get the first d terms of taylor expansion
#
# calculate path_n
#
n = sympy.var('n')
e_path_n = 0
e_upper_n = 0
coeff = []
for i in xrange(1, D + 1):
ri, mi = rs.items()[i - 1]
for j in xrange(mi):
c_ij = sympy.var('c_' + str(i) + str(j))
coeff.append(c_ij)
e_path_n += c_ij * (n ** j) * ((1 / ri) ** n)
if ri.is_complex:
ri = sympy.functions.Abs(ri)
e_upper_n += c_ij * (n ** j) * ((1 / ri) ** n)
equations = []
for i, c in enumerate(taylor_coeffs):
equations.append(sympy.Eq(e_path_n.subs(n, i), c))
coeff_sol = sympy.linsolve(equations, coeff)
# assert unique solution
assert type(coeff_sol) == sympy.sets.FiniteSet, "Zero or more solutions returned for path_n coefficients"
coeff_sol = list(coeff_sol)[0]
coeff_sol = [sympy.N(c, ROUND) for c in coeff_sol]
for val, var in zip(coeff_sol, coeff):
name = var.name
e_path_n = e_path_n.subs(name, val)
e_upper_n = e_upper_n.subs(name, val)
return sympy.utilities.lambdify(list(e_path_n.free_symbols), e_path_n), sympy.utilities.lambdify(
list(e_upper_n.free_symbols), e_upper_n)