本文整理汇总了Python中sympy.solvers.solve函数的典型用法代码示例。如果您正苦于以下问题:Python solve函数的具体用法?Python solve怎么用?Python solve使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了solve函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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
示例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}
示例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
示例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)
示例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)
示例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)
示例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)
示例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)
示例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
示例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')
示例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)
示例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]})
示例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)))
示例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