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


Python sympy.solve方法代码示例

本文整理汇总了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) 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:19,代码来源:algorithmic_math_test.py

示例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) 
开发者ID:sukeesh,项目名称:Jarvis,代码行数:27,代码来源:evaluator.py

示例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) 
开发者ID:sukeesh,项目名称:Jarvis,代码行数:20,代码来源:evaluator.py

示例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 
开发者ID:Parallel-in-Time,项目名称:pySDC,代码行数:18,代码来源:plot_dispersion.py

示例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) 
开发者ID:deepmind,项目名称:mathematics_dataset,代码行数:13,代码来源:linear_system_test.py

示例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] 
开发者ID:solowPy,项目名称:solowPy,代码行数:12,代码来源:model.py

示例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)) 
开发者ID:sukeesh,项目名称:Jarvis,代码行数:40,代码来源:evaluator.py

示例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)) 
开发者ID:sukeesh,项目名称:Jarvis,代码行数:15,代码来源:evaluator.py

示例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] 
开发者ID:QuantEcon,项目名称:QuantEcon.lectures.code,代码行数:12,代码来源:model.py

示例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 
开发者ID:publichealthengland,项目名称:pygom,代码行数:33,代码来源:epi_analysis.py

示例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) 
开发者ID:jameskeaveney,项目名称:ElecSus,代码行数:29,代码来源:solve_dielectric.py

示例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) 
开发者ID:pymoca,项目名称:pymoca,代码行数:15,代码来源:runtime.py

示例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) 
开发者ID:simupy,项目名称:simupy,代码行数:4,代码来源:symbolic.py

示例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 
开发者ID:simupy,项目名称:simupy,代码行数:34,代码来源:test_block_diagram.py

示例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]) 
开发者ID:simupy,项目名称:simupy,代码行数:37,代码来源:test_block_diagram.py


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