本文整理匯總了Python中sympy.solve方法的典型用法代碼示例。如果您正苦於以下問題:Python sympy.solve方法的具體用法?Python sympy.solve怎麽用?Python sympy.solve使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類sympy
的用法示例。
在下文中一共展示了sympy.solve方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: testAlgebraInverse
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import solve [as 別名]
def testAlgebraInverse(self):
dataset_objects = algorithmic_math.math_dataset_init(26)
counter = 0
for d in algorithmic_math.algebra_inverse(26, 0, 3, 10):
counter += 1
decoded_input = dataset_objects.int_decoder(d["inputs"])
solve_var, expression = decoded_input.split(":")
lhs, rhs = expression.split("=")
# Solve for the solve-var.
result = sympy.solve("%s-(%s)" % (lhs, rhs), solve_var)
target_expression = dataset_objects.int_decoder(d["targets"])
# Check that the target and sympy's solutions are equivalent.
self.assertEqual(
0, sympy.simplify(str(result[0]) + "-(%s)" % target_expression))
self.assertEqual(counter, 10)
示例2: solve
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import solve [as 別名]
def solve(jarvis, s):
"""
Prints where expression equals zero
-- Example:
solve x**2 + 5*x + 3
solve x + 3 = 5
"""
x = sympy.Symbol('x')
def _format(solutions):
if solutions == 0:
return "No solution!"
ret = ''
for count, point in enumerate(solutions):
if x not in point:
return "Please use 'x' in expression."
x_value = point[x]
ret += "{}. x: {}\n".format(count, x_value)
return ret
def _calc(expr):
return sympy.solve(expr, x, dict=True)
s = remove_equals(jarvis, s)
calc(jarvis, s, calculator=_calc, formatter=_format, do_evalf=False)
示例3: calc
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import solve [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)
示例4: findomega
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import solve [as 別名]
def findomega(stab_fh):
assert np.array_equal(np.shape(stab_fh), [2, 2]), 'Not 2x2 matrix...'
omega = sympy.Symbol('omega')
func = (sympy.exp(-1j * omega) - stab_fh[0, 0]) * (sympy.exp(-1j * omega) - stab_fh[1, 1]) - \
stab_fh[0, 1] * stab_fh[1, 0]
solsym = sympy.solve(func, omega)
sol0 = complex(solsym[0])
sol1 = complex(solsym[1])
if sol0.real >= 0:
sol = sol0
elif sol1.real >= 0:
sol = sol1
else:
print("Two roots with real part of same sign...")
sol = sol0
return sol
示例5: testLinearSystem
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import solve [as 別名]
def testLinearSystem(self, degree):
for _ in range(100): # test a few times
target = [random.randint(-100, 100) for _ in range(degree)]
variables = [sympy.Symbol(chr(ord('a') + i)) for i in range(degree)]
system = linear_system.linear_system(
variables=variables,
solutions=target,
entropy=10.0)
solved = sympy.solve(system, variables)
solved = [solved[symbol] for symbol in variables]
self.assertEqual(target, solved)
示例6: solow_residual
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import solve [as 別名]
def solow_residual(self):
"""
Symbolic expression for the Solow residual which is used as a measure
of technology.
:getter: Return the symbolic expression.
:type: sympy.Basic
"""
return sym.solve(Y - self.output, A)[0]
示例7: equations
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import solve [as 別名]
def equations(jarvis, term):
"""
Solves linear equations system
Use variables: a, b, c, ..., x, y,z
Example:
~> Hi, what can I do for you?
equations
1. Equation: x**2 + 2y - z = 6
2. Equation: (x-1)(y-1) = 0
3. Equation: y**2 - x -10 = y**2 -y
4. Equation:
[{x: -9, y: 1, z: 77}, {x: 1, y: 11, z: 17}]
"""
a, b, c, d, e, f, g, h, i, j, k, l, m = sympy.symbols(
'a,b,c,d,e,f,g,h,i,j,k,l,m')
n, o, p, q, r, s, t, u, v, w, x, y, z = sympy.symbols(
'n,o,p,q,r,s,t,u,v,w,x,y,z')
equations = []
count = 1
user_input = jarvis.input('{}. Equation: '.format(count))
while user_input != '':
count += 1
user_input = format_expression(user_input)
user_input = remove_equals(jarvis, user_input)
equations.append(user_input)
user_input = jarvis.input('{}. Equation: '.format(count))
calc(
jarvis,
term,
calculator=lambda expr: sympy.solve(
equations,
dict=True))
示例8: solve_y
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import solve [as 別名]
def solve_y(s):
if 'y' in s:
y = sympy.Symbol('y')
try:
results = sympy.solve(s, y)
except NotImplementedError:
return 'unknown'
if len(results) == 0:
return '0'
else:
return results[0]
else:
return solve_y("({}) -y".format(s))
示例9: solow_residual
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import solve [as 別名]
def solow_residual(self):
"""
Symbolic expression for the Solow residual which is used as a
measure of technology.
:getter: Return the symbolic expression.
:type: sym.Basic
"""
return sym.solve(Y - self.output, A)[0]
示例10: DFE
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import solve [as 別名]
def DFE(ode, disease_state):
'''
Returns the disease free equilibrium from an ode object
Parameters
----------
ode: :class:`.BaseOdeModel`
a class object from pygom
diseaseState: array like
name of the disease states
Returns
-------
e: array like
disease free equilibrium
'''
eqn = ode.get_ode_eqn()
index = ode.get_state_index(disease_state)
states = [s for s in ode._iterStateList()]
states_subs = {states[i]: 0 for i in index}
eqn = eqn.subs(states_subs)
DFE_solution = sympy.solve(eqn, states)
if len(DFE_solution) == 0: DFE_solution = {}
for s in states:
if s not in states_subs.keys() and s not in DFE_solution.keys():
DFE_solution.setdefault(s, 0)
return DFE_solution
示例11: test_solveset
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import solve [as 別名]
def test_solveset():
x = Symbol('x')
A = Matrix([[x,2,x*x],[4,5,x],[x,8,9]])
solns = solve(det(A), x)
solns_set = list(solveset(det(A), x))
print(solns)
print('\n')
print(solns_set)
print('\n\n\n')
print((solns[0]))
print('\n')
print((solns_set[0]))
soln_sub = solns[0].subs(x, 1)
solnset_sub = solns_set[0].subs(x, 1)
s1 = soln_sub.evalf()
s1set = solnset_sub.evalf()
s2set = solns_set[1].subs(x, 1).evalf()
print(s1)
print(s1set)
print(s2set)
示例12: compute_fg
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import solve [as 別名]
def compute_fg(self):
n_states = len(self.x)
n_vars = len(self.v)
n_eqs = len(self.eqs)
if n_states + n_vars != n_eqs:
raise RuntimeError('# states: {:d} + # variables: {:d} != # equations {:d}'.format(
n_states, n_vars, n_eqs))
lhs = list(self.x.diff(self.t)) + list(self.v) + list(self.y)
fg_sol = sympy.solve(self.eqs, lhs, dict=True)[0]
self.f = self.x.diff(self.t).subs(fg_sol)
assert len(self.x) == len(self.f)
self.g = self.y.subs(fg_sol)
assert len(self.y) == len(self.g)
示例13: equilibrium_points
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import solve [as 別名]
def equilibrium_points(self, input_=None):
return sp.solve(self.state_equation, self.state, dict=True)
示例14: control_systems
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import solve [as 別名]
def control_systems(request):
ct_sys, ref = request.param
Ac, Bc, Cc = ct_sys.data
Dc = np.zeros((Cc.shape[0], 1))
Q = np.eye(Ac.shape[0])
R = np.eye(Bc.shape[1] if len(Bc.shape) > 1 else 1)
Sc = linalg.solve_continuous_are(Ac, Bc.reshape(-1, 1), Q, R,)
Kc = linalg.solve(R, Bc.T @ Sc).reshape(1, -1)
ct_ctr = LTISystem(Kc)
evals = np.sort(np.abs(
linalg.eig(Ac, left=False, right=False, check_finite=False)
))
dT = 1/(2*evals[-1])
Tsim = (8/np.min(evals[~np.isclose(evals, 0)])
if np.sum(np.isclose(evals[np.nonzero(evals)], 0)) > 0
else 8
)
dt_data = signal.cont2discrete((Ac, Bc.reshape(-1, 1), Cc, Dc), dT)
Ad, Bd, Cd, Dd = dt_data[:-1]
Sd = linalg.solve_discrete_are(Ad, Bd.reshape(-1, 1), Q, R,)
Kd = linalg.solve(Bd.T @ Sd @ Bd + R, Bd.T @ Sd @ Ad)
dt_sys = LTISystem(Ad, Bd, dt=dT)
dt_sys.initial_condition = ct_sys.initial_condition
dt_ctr = LTISystem(Kd, dt=dT)
yield ct_sys, ct_ctr, dt_sys, dt_ctr, ref, Tsim
示例15: test_events
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import solve [as 別名]
def test_events():
# use bouncing ball to test events work
# simulate in block diagram
int_opts = block_diagram.DEFAULT_INTEGRATOR_OPTIONS.copy()
int_opts['rtol'] = 1E-12
int_opts['atol'] = 1E-15
int_opts['nsteps'] = 1000
int_opts['max_step'] = 2**-3
x = x1, x2 = Array(dynamicsymbols('x_1:3'))
mu, g = sp.symbols('mu g')
constants = {mu: 0.8, g: 9.81}
ic = np.r_[10, 15]
sys = SwitchedSystem(
x1, Array([0]),
state_equations=r_[x2, -g],
state_update_equation=r_[sp.Abs(x1), -mu*x2],
state=x,
constants_values=constants,
initial_condition=ic
)
bd = BlockDiagram(sys)
res = bd.simulate(5, integrator_options=int_opts)
# compute actual impact time
tvar = dynamicsymbols._t
impact_eq = (x2*tvar - g*tvar**2/2 + x1).subs(
{x1: ic[0], x2: ic[1], g: 9.81}
)
t_impact = sp.solve(impact_eq, tvar)[-1]
# make sure simulation actually changes velocity sign around impact
abs_diff_impact = np.abs(res.t - t_impact)
impact_idx = np.where(abs_diff_impact == np.min(abs_diff_impact))[0]
assert np.sign(res.x[impact_idx-1, 1]) != np.sign(res.x[impact_idx+1, 1])