• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python solvers.solve函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sympy.solvers.solve函数的典型用法代码示例。如果您正苦于以下问题:Python solve函数的具体用法?Python solve怎么用?Python solve使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: contains

    def contains(self, other):
        """
        Is the other GeometryEntity contained within this Segment?

        Examples
        ========

        >>> from sympy import Point, Segment
        >>> p1, p2 = Point(0, 1), Point(3, 4)
        >>> s = Segment(p1, p2)
        >>> s2 = Segment(p2, p1)
        >>> s.contains(s2)
        True
        """
        if isinstance(other, Segment):
            return other.p1 in self and other.p2 in self
        elif isinstance(other, Point):
            if Point.is_collinear(self.p1, self.p2, other):
                t = Dummy('t')
                x, y = self.arbitrary_point(t).args
                if self.p1.x != self.p2.x:
                    ti = solve(x - other.x, t)[0]
                else:
                    ti = solve(y - other.y, t)[0]
                if ti.is_number:
                    return 0 <= ti <= 1
                return None

        # No other known entity can be contained in a Ray
        return False
开发者ID:jgoppert,项目名称:sympy,代码行数:30,代码来源:line.py


示例2: solveEquations

def solveEquations(equations, numberSlots, alignedNumbers):
    x0 = Symbol('x0')
    x1 = Symbol('x1')
    #sanitize equation
    sanitized = []
    for eq in equations:
        g = eq.split('=')
        g[1] = g[1].replace('+', '$').replace('-', '+').replace('$', '-')
        eq = g[0] + '-' + g[1]
        #print eq
        for i in range(0, len(numberSlots)):
            eq = eq.replace(numberSlots[i], str(alignedNumbers[i]))
        sanitized.append(eq)

    #print sanitized
    if len(sanitized) == 1:
        result = solve((sanitized[0]), x0)
        #print sanitized
        #print result
        if(len(result)>=1):
            result = {x0: result[0]}
    elif len(sanitized) == 2:
        result = solve((sanitized[0], sanitized[1]), x0, x1)
    #print 'result: ', result
    return result
开发者ID:yeskarthik,项目名称:WordProblemSolver,代码行数:25,代码来源:TemplateParser.py


示例3: parameter_value

    def parameter_value(self, other, u, v=None):
        """Return the parameter(s) corresponding to the given point.

        Examples
        ========

        >>> from sympy import Plane, Point, pi
        >>> from sympy.abc import t, u, v
        >>> p = Plane((2, 0, 0), (0, 0, 1), (0, 1, 0))

        By default, the parameter value returned defines a point
        that is a distance of 1 from the Plane's p1 value and
        in line with the given point:

        >>> on_circle = p.arbitrary_point(t).subs(t, pi/4)
        >>> on_circle.distance(p.p1)
        1
        >>> p.parameter_value(on_circle, t)
        {t: pi/4}

        Moving the point twice as far from p1 does not change
        the parameter value:

        >>> off_circle = p.p1 + (on_circle - p.p1)*2
        >>> off_circle.distance(p.p1)
        2
        >>> p.parameter_value(off_circle, t)
        {t: pi/4}

        If the 2-value parameter is desired, supply the two
        parameter symbols and a replacement dictionary will
        be returned:

        >>> p.parameter_value(on_circle, u, v)
        {u: sqrt(10)/10, v: sqrt(10)/30}
        >>> p.parameter_value(off_circle, u, v)
        {u: sqrt(10)/5, v: sqrt(10)/15}
        """
        from sympy.geometry.point import Point
        from sympy.core.symbol import Dummy
        from sympy.solvers.solvers import solve
        if not isinstance(other, GeometryEntity):
            other = Point(other, dim=self.ambient_dimension)
        if not isinstance(other, Point):
            raise ValueError("other must be a point")
        if other == self.p1:
            return other
        if isinstance(u, Symbol) and v is None:
            delta = self.arbitrary_point(u) - self.p1
            eq = delta - (other - self.p1).unit
            sol = solve(eq, u, dict=True)
        elif isinstance(u, Symbol) and isinstance(v, Symbol):
            pt = self.arbitrary_point(u, v)
            sol = solve(pt - other, (u, v), dict=True)
        else:
            raise ValueError('expecting 1 or 2 symbols')
        if not sol:
            raise ValueError("Given point is not on %s" % func_name(self))
        return sol[0]  # {t: tval} or {u: uval, v: vval}
开发者ID:asmeurer,项目名称:sympy,代码行数:59,代码来源:plane.py


示例4: _contains

    def _contains(self, other):
        L = self.lamda
        if self._is_multivariate():
            solns = solve([expr - val for val, expr in zip(other, L.expr)],
                    L.variables)
        else:
            solns = solve(L.expr - other, L.variables[0])

        for soln in solns:
            try:
                if soln in self.base_set:           return True
            except TypeError:
                if soln.evalf() in self.base_set:   return True
        return False
开发者ID:BDGLunde,项目名称:sympy,代码行数:14,代码来源:fancysets.py


示例5: resolve

def resolve(equation):
    '''Resolve an equation with 1 unknown var'''
    #Find the symbol
    r = re.compile(r"([A-Za-z]{0,})")
    varList = r.findall(equation)
    symbol = ''
    for a in range(0, len(varList)):
        if len(varList[a]) > 0:
            symbol = varList[a]
            break
    
    x = Symbol(symbol)
    #replace 3x -> 3*x for example
    r2 = re.compile(r'([0-9])'+symbol)
    replaceList = r2.findall(equation)
    for a in range(0, len(replaceList)):
        if len(replaceList[a]) > 0:
            equation = re.sub(r''+replaceList[a]+symbol, r''+replaceList[a]+'*'+symbol, equation)
    #rewrite the eq to solve it
    r3 = re.compile(r"(.{0,})\=(.{0,})")
    results = r3.findall(equation)
    mGauche = results[0][0]
    mDroite = results[0][1]

    return solve(mGauche + '-(' + mDroite + ')', x)
开发者ID:AmarOk1412,项目名称:Scripts-CDSB,代码行数:25,代码来源:resolveEq.py


示例6: rewriteUsingEquation

    def rewriteUsingEquation(self,var,varToRemove,equation):
        """
        Rewrites the expression for var to not include varToRemove,
        by solving equation for varToRemove, then substituting that
        into the expression for var.
        """

        if var in equation.getVars():
            self.write("You can't rewrite an expression with the "
                    "original equation.")
            return

        equat = equation.equation
        for var2 in self.equivalenciesOfVariable(varToRemove):
            equat = equat.subs(var2,varToRemove)

        exps = solve(equat,varToRemove)

        outexps = []

        if var not in self.expressions:
            self.findExpression(var)

        for exp1 in self.expressions[var]:
            for exp2 in exps:
                outexps.append(exp1.subs(varToRemove,exp2))
        if outexps:
            self.expressions[var] = [self.unifyVarsInExpression(x)
                        for x in outexps]

            self.tidyExpressions(var)
开发者ID:bshlgrs,项目名称:pyGem,代码行数:31,代码来源:Backend.py


示例7: balance

def balance():
    Ls=list('abcdefghijklmnopqrstuvwxyz')
    eq=eq_enter.get()
    Ss,Os,Es,a,i=defaultdict(list),Ls[:],[],1,1
    for p in eq.split('->'):
        for k in p.split('+'):
            c = [Ls.pop(0), 1]
            for e,m in re.findall('([A-Z][a-z]?)([0-9]*)',k):
                m=1 if m=='' else int(m)
                a*=m
                d=[c[0],c[1]*m*i]
                Ss[e][:0],Es[:0]=[d],[[e,d]]
        i=-1
    Ys=dict((s,eval('Symbol("'+s+'")')) for s in Os if s not in Ls)
    Qs=[eval('+'.join('%d*%s'%(c[1],c[0]) for c in Ss[s]),{},Ys) for s in Ss]+[Ys['a']-a]
    k=solve(Qs,*Ys)
    if k:
        N=[k[Ys[s]] for s in sorted(Ys)]
        g=N[0]
        for a1, a2 in zip(N[0::2],N[1::2]):g=gcd(g,a2)
        N=[i/g for i in N]
        pM=lambda c: str(c) if c!=1 else ''
        ans = '->'.join('+'.join(pM(N.pop(0))+str(t) for t in p.split('+')) for p in eq.split('->'))
    else:ans = 'No Result!'
    eq_result.configure(text='%s' % ans)
开发者ID:usccolumbia,项目名称:CSCE206_Projects,代码行数:25,代码来源:Titration2.py


示例8: calcularEquacio

 def calcularEquacio(self):
     if "x" in self.expresio:
         expr=sympify(self.expresio)
         for symbol in expr.atoms(Symbol):
             if str(symbol)=='x':
                 return solve(expr, symbol)
     elif "y" in self.expresio:
         expr=sympify(self.expresio)
         for symbol in expr.atoms(Symbol):
             if str(symbol)=='y':
                 return solve(expr, symbol)
     else:
         expr=sympify(self.expresio)
         for symbol in expr.atoms(Symbol):
             if str(symbol)=='z':
                 return solve(expr, symbol)
开发者ID:FrancescBagur,项目名称:Ccalc,代码行数:16,代码来源:ClassCalculadoraEquacions.py


示例9: intersection_plane_line

def intersection_plane_line(pP,nP,pL,vL):
    """Computes the intersection of a plane and a line
    INPUT: pPlane: point on plane
           nPlane: normal vector of plane
           pLine: point on line
           vLine: vecotr on line
    OUTPUT: coordinates of intersectionPoint
    """

    plane = lambda x1,x2,x3: (x1-pP[0])*nP[0]+(x2-pP[1])*nP[1]+(x3-pP[2])*nP[2]

    iP=Symbol('iP')

    #intersection 
    iP=solve(plane(pL[0]+iP*vL[0],pL[1]+iP*vL[1],pL[2]+iP*vL[2]),iP)

    #Compute intersection point
    Point = lambda iP: [pL[0]+iP*vL[0],pL[1]+iP*vL[1],pL[2]+iP*vL[2]]

    if iP != []:
        coordsPoint = Point(iP[0])
    else:
        coordsPoint = []

    newCoordsPoint=[]
    for coords in coordsPoint:
        newCoordsPoint.append(np.float(coords))

    return np.array(newCoordsPoint)
开发者ID:Franculino,项目名称:VGM,代码行数:29,代码来源:misc.py


示例10: get_minimum_distance

def get_minimum_distance(arguments):
    delta = arguments[0]
    total_time = arguments[1]
    point = arguments[2]

    T=delta*total_time
    X=point[0]
    Y=point[1]
    a=2; b=-2*X; c=2*T*Y; d=-2*T**2

    x=Symbol("x",real=True)

    #print "================"
    #print "X={0} Y={1} T={2}".format(X,Y,T)
    #print "a={0} b={1} c={2} d={3}".format(a,b,c,d)
    solutions = solve(a*x**4 + b*x**3 + c*x + d, x)
    #print solutions
    #print "================"
    #if len(solutions) == 0:
    #    exit(1)

    # Once we have de solutions we want to get the minimum distance
    min_distance = float("inf")
    min_solution = 0
    for solution in solutions:
        distance = math.sqrt((solution-X)**2 + ((T/solution)-Y)**2)

        if distance < min_distance:
            min_distance = distance
            min_solution = [solution, T/solution]

#    return min_distance, min_solution
    return min_distance**2
开发者ID:frantgn90,项目名称:master,代码行数:33,代码来源:delta_calculation.py


示例11: random_point

    def random_point(self, seed=None):
        """ Returns a random point on the Plane.

        Returns
        =======

        Point3D

        """
        x, y, z = symbols("x, y, z")
        a = self.equation(x, y, z)
        from sympy import Rational
        import random
        if seed is not None:
            rng = random.Random(seed)
        else:
            rng = random
        for i in range(10):
            c = 2*Rational(rng.random()) - 1
            s = sqrt(1 - c**2)
            a = solve(a.subs([(y, c), (z, s)]))
            if a is []:
                d = Point3D(0, c, s)
            else:
                d = Point3D(a[0], c, s)
            if d in self:
                return d
        raise GeometryError(
            'Having problems generating a point in the plane')
开发者ID:akshayah3,项目名称:sympy,代码行数:29,代码来源:plane.py


示例12: g

def g(yieldCurve, zeroRates,n, verbose):
    '''
        generates recursively the zero curve 
        expressions eval('(0.06/1.05)+(1.06/(1+x)**2)-1')
        solves these expressions to get the new rate
        for that period
    
    '''
    if len(zeroRates) >= len(yieldCurve):
        print "\n\n\t+zero curve boot strapped [%d iterations]" % (n)
        return
    else:
        legn = ''
        for i in range(0,len(zeroRates),1):
            if i == 0:
                legn = '%2.6f/(1+%2.6f)**%d'%(yieldCurve[n], zeroRates[i],i+1)
            else:
                legn = legn + ' +%2.6f/(1+%2.6f)**%d'%(yieldCurve[n], zeroRates[i],i+1)
        legn = legn + '+ (1+%2.6f)/(1+x)**%d-1'%(yieldCurve[n], n+1)
        # solve the expression for this iteration
        if verbose:
            print "-[%d] %s" % (n, legn.strip())
        rate1 = solve(eval(legn), x)
        # Abs here since some solutions can be complex
        rate1 = min([Real(abs(r)) for r in rate1])
        if verbose:
            print "-[%d] solution %2.6f" % (n, float(rate1))
        # stuff the new rate in the results, will be 
        # used by the next iteration
        zeroRates.append(rate1)
        g(yieldCurve, zeroRates,n+1, verbose)
开发者ID:jacob-carrier,项目名称:code,代码行数:31,代码来源:recipe-578257.py


示例13: arbitrary_point

    def arbitrary_point(self, t=None):
        """ Returns an arbitrary point on the Plane; varying `t` from 0 to 2*pi
        will move the point in a circle of radius 1 about p1 of the Plane.

        Examples
        ========

        >>> from sympy.geometry.plane import Plane
        >>> from sympy.abc import t
        >>> p = Plane((0, 0, 0), (0, 0, 1), (0, 1, 0))
        >>> p.arbitrary_point(t)
        Point3D(0, cos(t), sin(t))
        >>> _.distance(p.p1).simplify()
        1

        Returns
        =======

        Point3D

        """
        from sympy import cos, sin
        t = t or Dummy('t')
        x, y, z = self.normal_vector
        a, b, c = self.p1.args
        if x == y == 0:
            return Point3D(a + cos(t), b + sin(t), c)
        elif x == z == 0:
            return Point3D(a + cos(t), b, c + sin(t))
        elif y == z == 0:
            return Point3D(a, b + cos(t), c + sin(t))
        m = Dummy()
        p = self.projection(Point3D(self.p1.x + cos(t), self.p1.y + sin(t), 0)*m)
        return p.xreplace({m: solve(p.distance(self.p1) - 1, m)[0]})
开发者ID:helpin,项目名称:sympy,代码行数:34,代码来源:plane.py


示例14: singularities

def singularities(expr, sym):
    """
    Finds singularities for a function.
    Currently supported functions are:
    - univariate real rational functions

    Examples
    ========

    >>> from sympy.calculus.singularities import singularities
    >>> from sympy import Symbol
    >>> x = Symbol('x', real=True)
    >>> singularities(x**2 + x + 1, x)
    ()
    >>> singularities(1/(x + 1), x)
    (-1,)

    References
    ==========

    .. [1] http://en.wikipedia.org/wiki/Mathematical_singularity

    """
    if not expr.is_rational_function(sym):
        raise NotImplementedError("Algorithms finding singularities for"
                                  " non rational functions are not yet"
                                  " implemented")
    else:
        return tuple(sorted(solve(simplify(1/expr), sym)))
开发者ID:AdrianPotter,项目名称:sympy,代码行数:29,代码来源:singularities.py


示例15: matrix_eigenvalues

def matrix_eigenvalues(m):
    """
        Module B3, page 14

        This is one example of something easier with just using the libaries!
        You could just do Matrix(m).eigen_values()! m should be a sympy
        Matrix, e.g. Matrix([[0, 1], [1, 0]]).
    """

    k = symbols('k')

    # To make it clearer, lets assign out the matrix elements
    a, b, c, d = m[0, 0], m[0, 1], m[1, 0], m[1, 1]
    # See B3 page 19, equation 2.5 for this definition
    characteristic_equation = k ** 2 - (a + d) * k + (a * d - b * c)
    roots = solve(characteristic_equation)

    print "Characteristic equation:\n\n%s\n" % pp(characteristic_equation)

    if len(roots) == 1:
        # Make dupe of repeated root
        roots = roots * 2

    if roots[0].is_real:
        print "Eigenvalues: %s\n" % pp(roots)
        return roots
    else:
        # Note that the statement 'no eigenvalues' is by definition
        print "Roots are complex, no eigenvalues"
        return None
开发者ID:jaymzcd,项目名称:oucode,代码行数:30,代码来源:eigen.py


示例16: _eval_subs

 def _eval_subs(self, old, new):
     if old in self.variables:
         newexpr = self.expr.subs(old, new)
         i = self.variables.index(old)
         newvars = list(self.variables)
         newpt = list(self.point)
         if new.is_Symbol:
             newvars[i] = new
         else:
             syms = new.free_symbols
             if len(syms) == 1 or old in syms:
                 if old in syms:
                     var = self.variables[i]
                 else:
                     var = syms.pop()
                 # First, try to substitute self.point in the "new"
                 # expr to see if this is a fixed point.
                 # E.g.  O(y).subs(y, sin(x))
                 point = new.subs(var, self.point[i])
                 if point != self.point[i]:
                     from sympy.solvers import solve
                     d = Dummy()
                     res = solve(old - new.subs(var, d), d, dict=True)
                     point = d.subs(res[0]).limit(old, self.point[i])
                 newvars[i] = var
                 newpt[i] = point
             elif old not in syms:
                 del newvars[i], newpt[i]
                 if not syms and new == self.point[i]:
                     newvars.extend(syms)
                     newpt.extend([S.Zero]*len(syms))
             else:
                 return
         return Order(newexpr, *zip(newvars, newpt))
开发者ID:SungSingSong,项目名称:sympy,代码行数:34,代码来源:order.py


示例17: matrix_eigenlines

def matrix_eigenlines(m):
    """
        Module B3, page 21
    """

    eigenvalues = matrix_eigenvalues(m)
    # Now make sure we've got something to work with!
    assert(eigenvalues is not None)

    # Now to work out the eignlines we use the eigenvector equation
    # Ax = kx where A is our matrix m, k is a particular eigenvalue
    # and x represents the (x, y) vector
    x, y = symbols('x, y')
    x_vector = Matrix([x, y])

    eigenlines = list()
    for eigenvalue in eigenvalues:
        # Now we evaluate Ax = kx, since we can't do a 'a = b' style expression
        # in sympy/python we subtract the right hand side so we are basically
        # skipping a small step and writing Ax - kx = 0
        equations = m * x_vector - eigenvalue * x_vector
        print "Set of equations for eigenvalue %s:\n\n%s" % (eigenvalue, pp(equations))

        # For a given eigenvalue the equations returned above both reduce
        # to the same expression, so we can pick the first one, simplify it
        # down to the lowest terms. Then we solve for y which basically
        # rearranged it into standard form. This is the eigenline equation.
        # As we're dealing with solve, we take the first (only) result
        eigenline = solve(simplify(equations[0]), y)[0]
        print "Eigenline equation for eigenvalue %s:\n\n%s\n" % (eigenvalue, pp(eigenline))
        eigenlines.append(eigenline)

    return eigenlines
开发者ID:jaymzcd,项目名称:oucode,代码行数:33,代码来源:eigen.py


示例18: _remove_multiple_delta

def _remove_multiple_delta(expr):
    """
    Evaluate products of KroneckerDelta's.
    """
    from sympy.solvers import solve
    if expr.is_Add:
        return expr.func(*map(_remove_multiple_delta, expr.args))
    if not expr.is_Mul:
        return expr
    eqs = []
    newargs = []
    for arg in expr.args:
        if isinstance(arg, KroneckerDelta):
            eqs.append(arg.args[0] - arg.args[1])
        else:
            newargs.append(arg)
    if not eqs:
        return expr
    solns = solve(eqs, dict=True)
    if len(solns) == 0:
        return S.Zero
    elif len(solns) == 1:
        for key in solns[0].keys():
            newargs.append(KroneckerDelta(key, solns[0][key]))
        expr2 = expr.func(*newargs)
        if expr != expr2:
            return _remove_multiple_delta(expr2)
    return expr
开发者ID:alhirzel,项目名称:sympy,代码行数:28,代码来源:delta.py


示例19: _contains

    def _contains(self, other):
        from sympy.solvers import solve
        L = self.lamda
        if self._is_multivariate():
            solns = solve([expr - val for val, expr in zip(other, L.expr)],
                    L.variables)
        else:
            solns = solve(L.expr - other, L.variables[0])

        for soln in solns:
            try:
                if soln in self.base_set:
                    return S.true
            except TypeError:
                return self.base_set.contains(soln.evalf())
        return S.false
开发者ID:atsao72,项目名称:sympy,代码行数:16,代码来源:fancysets.py


示例20: test_nfloat

def test_nfloat():
    from sympy.core.basic import _aresame
    from sympy.polys.rootoftools import RootOf

    x = Symbol("x")
    eq = x**(S(4)/3) + 4*x**(S(1)/3)/3
    assert _aresame(nfloat(eq), x**(S(4)/3) + (4.0/3)*x**(S(1)/3))
    assert _aresame(nfloat(eq, exponent=True), x**(4.0/3) + (4.0/3)*x**(1.0/3))
    eq = x**(S(4)/3) + 4*x**(x/3)/3
    assert _aresame(nfloat(eq), x**(S(4)/3) + (4.0/3)*x**(x/3))
    big = 12345678901234567890
    Float_big = Float(big)
    assert _aresame(nfloat(x**big, exponent=True),
                    x**Float_big)
    assert _aresame(nfloat(big), Float_big)
    assert nfloat({x: sqrt(2)}) == {x: nfloat(sqrt(2))}
    assert nfloat({sqrt(2): x}) == {sqrt(2): x}
    assert nfloat(cos(x + sqrt(2))) == cos(x + nfloat(sqrt(2)))

    # issue 6342
    f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4')
    assert not any(a.free_symbols for a in solve(f.subs(x, -0.139)))

    # issue 6632
    assert nfloat(-100000*sqrt(2500000001) + 5000000001) == \
        9.99999999800000e-11

    # issue 7122
    eq = cos(3*x**4 + y)*RootOf(x**5 + 3*x**3 + 1, 0)
    assert str(nfloat(eq, exponent=False, n=1)) == '-0.7*cos(3.0*x**4 + y)'
开发者ID:Jeyatharsini,项目名称:sympy,代码行数:30,代码来源:test_function.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python solvers.solve_undetermined_coeffs函数代码示例发布时间:2022-05-27
下一篇:
Python solvers.nsolve函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap