本文整理汇总了Python中sympy.solvers.solveset.linsolve函数的典型用法代码示例。如果您正苦于以下问题:Python linsolve函数的具体用法?Python linsolve怎么用?Python linsolve使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了linsolve函数的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_linsolve
def test_linsolve():
x, y, z, u, v, w = symbols("x, y, z, u, v, w")
x1, x2, x3, x4 = symbols('x1, x2, x3, x4')
# Test for different input forms
M = Matrix([[1, 2, 1, 1, 7], [1, 2, 2, -1, 12], [2, 4, 0, 6, 4]])
system1 = A, b = M[:, :-1], M[:, -1]
Eqns = [x1 + 2*x2 + x3 + x4 - 7, x1 + 2*x2 + 2*x3 - x4 - 12,
2*x1 + 4*x2 + 6*x4 - 4]
sol = FiniteSet((-2*x2 - 3*x4 + 2, x2, 2*x4 + 5, x4))
assert linsolve(M, (x1, x2, x3, x4)) == sol
assert linsolve(Eqns, (x1, x2, x3, x4)) == sol
assert linsolve(system1, (x1, x2, x3, x4)) == sol
# raise ValueError if no symbols are given
raises(ValueError, lambda: linsolve(system1))
# raise ValueError if, A & b is not given as tuple
raises(ValueError, lambda: linsolve(A, b, x1, x2, x3, x4))
# raise ValueError for garbage value
raises(ValueError, lambda: linsolve(Eqns[0], x1, x2, x3, x4))
# Fully symbolic test
a, b, c, d, e, f = symbols('a, b, c, d, e, f')
A = Matrix([[a, b], [c, d]])
B = Matrix([[e], [f]])
system2 = (A, B)
sol = FiniteSet((-b*(f - c*e/a)/(a*(d - b*c/a)) + e/a,
(f - c*e/a)/(d - b*c/a)))
assert linsolve(system2, [x, y]) == sol
# Test for Dummy Symbols issue #9667
x1 = Dummy('x1')
x2 = Dummy('x2')
x3 = Dummy('x3')
x4 = Dummy('x4')
assert linsolve(system1, x1, x2, x3, x4) == FiniteSet((-2*x2 - 3*x4 + 2, x2, 2*x4 + 5, x4))
# No solution
A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]])
b = Matrix([0, 0, 1])
assert linsolve((A, b), (x, y, z)) == EmptySet()
# Issue #10121 - Assignment of free variables
a, b, c, d, e = symbols('a, b, c, d, e')
Augmatrix = Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]])
assert linsolve(Augmatrix, a, b, c, d, e) == FiniteSet((a, 0, c, 0, e))
示例2: _transform_explike_DE
def _transform_explike_DE(DE, g, x, order, syms):
"""Converts DE with free parameters into DE with constant coefficients."""
from sympy.solvers.solveset import linsolve
eq = []
highest_coeff = DE.coeff(Derivative(g(x), x, order))
for i in range(order):
coeff = DE.coeff(Derivative(g(x), x, i))
coeff = (coeff / highest_coeff).expand().collect(x)
for t in Add.make_args(coeff):
eq.append(t)
temp = []
for e in eq:
if e.has(x):
break
elif e.has(Symbol):
temp.append(e)
else:
eq = temp
if eq:
sol = dict(zip(syms, (i for s in linsolve(eq, list(syms)) for i in s)))
if sol:
DE = DE.subs(sol)
DE = DE.factor().as_coeff_mul(Derivative)[1][0]
DE = DE.collect(Derivative(g(x)))
return DE
示例3: test_linsolve
def test_linsolve():
x, y, z, u, v, w = symbols("x, y, z, u, v, w")
x1, x2, x3, x4 = symbols("x1, x2, x3, x4")
# Test for different input forms
M = Matrix([[1, 2, 1, 1, 7], [1, 2, 2, -1, 12], [2, 4, 0, 6, 4]])
system = A, b = M[:, :-1], M[:, -1]
Eqns = [x1 + 2 * x2 + x3 + x4 - 7, x1 + 2 * x2 + 2 * x3 - x4 - 12, 2 * x1 + 4 * x2 + 6 * x4 - 4]
sol = FiniteSet((-2 * x2 - 3 * x4 + 2, x2, 2 * x4 + 5, x4))
assert linsolve(M, (x1, x2, x3, x4)) == sol
assert linsolve(Eqns, (x1, x2, x3, x4)) == sol
assert linsolve(system, (x1, x2, x3, x4)) == sol
# raise ValueError if no symbols are given
raises(ValueError, lambda: linsolve(system))
# raise ValueError if, A & b is not given as tuple
raises(ValueError, lambda: linsolve(A, b, x1, x2, x3, x4))
# raise ValueError for garbage value
raises(ValueError, lambda: linsolve(Eqns[0], x1, x2, x3, x4))
# Fully symbolic test
a, b, c, d, e, f = symbols("a, b, c, d, e, f")
A = Matrix([[a, b], [c, d]])
B = Matrix([[e], [f]])
system = (A, B)
sol = FiniteSet((-b * (f - c * e / a) / (a * (d - b * c / a)) + e / a, (f - c * e / a) / (d - b * c / a)))
assert linsolve(system, [x, y]) == sol
示例4: _contains
def _contains(self, other):
from sympy.matrices import Matrix
from sympy.solvers.solveset import solveset, linsolve
from sympy.utilities.iterables import iterable, cartes
L = self.lamda
if self._is_multivariate():
if not iterable(L.expr):
if iterable(other):
return S.false
return other.as_numer_denom() in self.func(
Lambda(L.variables, L.expr.as_numer_denom()), self.base_set)
if len(L.expr) != len(self.lamda.variables):
raise NotImplementedError(filldedent('''
Dimensions of input and output of Lambda are different.'''))
eqs = [expr - val for val, expr in zip(other, L.expr)]
variables = L.variables
free = set(variables)
if all(i.is_number for i in list(Matrix(eqs).jacobian(variables))):
solns = list(linsolve([e - val for e, val in
zip(L.expr, other)], variables))
else:
syms = [e.free_symbols & free for e in eqs]
solns = {}
for i, (e, s, v) in enumerate(zip(eqs, syms, other)):
if not s:
if e != v:
return S.false
solns[vars[i]] = [v]
continue
elif len(s) == 1:
sy = s.pop()
sol = solveset(e, sy)
if sol is S.EmptySet:
return S.false
elif isinstance(sol, FiniteSet):
solns[sy] = list(sol)
else:
raise NotImplementedError
else:
raise NotImplementedError
solns = cartes(*[solns[s] for s in variables])
else:
# assume scalar -> scalar mapping
solnsSet = solveset(L.expr - other, L.variables[0])
if solnsSet.is_FiniteSet:
solns = list(solnsSet)
else:
raise NotImplementedError(filldedent('''
Determining whether an ImageSet contains %s has not
been implemented.''' % func_name(other)))
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
示例5: main
def main():
equations = get_equations(layout)
symbols = set()
for eqn in equations:
symbols = symbols.union(eqn.atoms(Symbol))
symbols = list(symbols)
solved_equations = linsolve(equations, *symbols)
if not solved_equations:
raise OverconstrainedError("A solution could not be found.")
solve = list(solved_equations)[0]
print(list(zip(symbols, solve)))
示例6: _contains
def _contains(self, other):
from sympy.solvers.solveset import solveset, linsolve
L = self.lamda
if self._is_multivariate():
solns = list(linsolve([expr - val for val, expr in zip(other, L.expr)],
L.variables).args[0])
else:
solns = list(solveset(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
示例7: simpleDE
def simpleDE(f, x, g, order=4):
r"""Generates simple DE.
DE is of the form
.. math::
f^k(x) + \sum\limits_{j=0}^{k-1} A_j f^j(x) = 0
where :math:`A_j` should be rational function in x.
Generates DE's upto order 4 (default). DE's can also have free parameters.
By increasing order, higher order DE's can be found.
Yields a tuple of (DE, order).
"""
from sympy.solvers.solveset import linsolve
a = symbols('a:%d' % (order))
def _makeDE(k):
eq = f.diff(x, k) + Add(*[a[i]*f.diff(x, i) for i in range(0, k)])
DE = g(x).diff(x, k) + Add(*[a[i]*g(x).diff(x, i) for i in range(0, k)])
return eq, DE
eq, DE = _makeDE(order)
found = False
for k in range(1, order + 1):
eq, DE = _makeDE(k)
eq = eq.expand()
terms = eq.as_ordered_terms()
ind = rational_independent(terms, x)
if found or len(ind) == k:
sol = dict(zip(a, (i for s in linsolve(ind, a[:k]) for i in s)))
if sol:
found = True
DE = DE.subs(sol)
DE = DE.as_numer_denom()[0]
DE = DE.factor().as_coeff_mul(Derivative)[1][0]
yield DE.collect(Derivative(g(x))), k
示例8: _transform_DE_RE
def _transform_DE_RE(DE, g, k, order, syms):
"""Converts DE with free parameters into RE of hypergeometric type."""
from sympy.solvers.solveset import linsolve
RE = hyper_re(DE, g, k)
eq = []
for i in range(1, order):
coeff = RE.coeff(g(k + i))
eq.append(coeff)
sol = dict(zip(syms, (i for s in linsolve(eq, list(syms)) for i in s)))
if sol:
m = Wild('m')
RE = RE.subs(sol)
RE = RE.factor().as_numer_denom()[0].collect(g(k + m))
RE = RE.as_coeff_mul(g)[1][0]
for i in range(order): # smallest order should be g(k)
if RE.coeff(g(k + i)) and i:
RE = RE.subs(k, k - i)
break
return RE
示例9: _contains
def _contains(self, other):
from sympy.solvers.solveset import solveset, linsolve
L = self.lamda
if self._is_multivariate():
solns = list(linsolve([expr - val for val, expr in
zip(other, L.expr)], L.variables).args[0])
else:
solnsSet = solveset(L.expr-other, L.variables[0])
if solnsSet.is_FiniteSet:
solns = list(solveset(L.expr - other, L.variables[0]))
else:
raise NotImplementedError(filldedent('''
Determining whether an ImageSet contains %s has not
been implemented.''' % func_name(other)))
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
示例10: test_issue_9953
def test_issue_9953():
assert linsolve([ ], x) == S.EmptySet
示例11: intersection
#.........这里部分代码省略.........
>>> l1 = Line3D(Point3D(4,19,12), Point3D(5,25,17))
>>> l2 = Line3D(Point3D(-3, -15, -19), direction_ratio=[2,8,8])
>>> l1.intersection(l2)
[Point3D(1, 1, -3)]
>>> p6, p7 = Point3D(0, 5, 2), Point3D(2, 6, 3)
>>> s1 = Segment3D(p6, p7)
>>> l1.intersection(s1)
[]
"""
if isinstance(o, Point3D):
if o in self:
return [o]
else:
return []
elif isinstance(o, LinearEntity3D):
if self == o:
return [self]
elif self.is_parallel(o):
if isinstance(self, Line3D):
if o.p1 in self:
return [o]
return []
elif isinstance(self, Ray3D):
if isinstance(o, Ray3D):
# case 1, rays in the same direction
if self.xdirection == o.xdirection and \
self.ydirection == o.ydirection and \
self.zdirection == o.zdirection:
return [self] if (self.source in o) else [o]
# case 2, rays in the opposite directions
else:
if o.source in self:
if self.source == o.source:
return [self.source]
return [Segment3D(o.source, self.source)]
return []
elif isinstance(o, Segment3D):
if o.p1 in self:
if o.p2 in self:
return [o]
return [Segment3D(o.p1, self.source)]
elif o.p2 in self:
return [Segment3D(o.p2, self.source)]
return []
elif isinstance(self, Segment3D):
if isinstance(o, Segment3D):
# A reminder that the points of Segments are ordered
# in such a way that the following works. See
# Segment3D.__new__ for details on the ordering.
if self.p1 not in o:
if self.p2 not in o:
# Neither of the endpoints are in o so either
# o is contained in this segment or it isn't
if o in self:
return [o]
return []
else:
# p1 not in o but p2 is. Either there is a
# segment as an intersection, or they only
# intersect at an endpoint
if self.p2 == o.p1:
return [o.p1]
return [Segment3D(o.p1, self.p2)]
elif self.p2 not in o:
# p2 not in o but p1 is. Either there is a
# segment as an intersection, or they only
# intersect at an endpoint
if self.p1 == o.p2:
return [o.p2]
return [Segment3D(o.p2, self.p1)]
# Both points of self in o so the whole segment
# is in o
return [self]
else: # unrecognized LinearEntity
raise NotImplementedError
else:
# If the lines are not parallel then solve their arbitrary points
# to obtain the point of intersection
t = t1, t2 = Dummy(), Dummy()
a = self.arbitrary_point(t1)
b = o.arbitrary_point(t2)
dx = a.x - b.x
c = linsolve([dx, a.y - b.y], t).args[0]
d = linsolve([dx, a.z - b.z], t).args[0]
if len(c.free_symbols) == 1 and len(d.free_symbols) == 1:
return []
e = a.subs(t1, c[0])
if e in self and e in o:
return [e]
else:
return []
return o.intersection(self)
示例12: print
coeff = '1'
Q,rest = str_term.split('*',1)
else:
coeff,Q,rest = str_term.split('*',2)
if Q not in our_Qs:
our_Qs[Q] = [coeff + "*" + rest]
else:
our_Qs[Q].append(coeff + "*" + rest)
for key,value in our_Qs.items():
print("%s: %s" % (key,value))
variables = symbols(" ".join(list(our_Qs))) # assumes our_Qs is an ordered dictionary, not a standard one.
print(variables)
result = linsolve(system_of_eqns,variables)
print("result:",result)
Q_values = OrderedDict()
for k,Q in enumerate(our_Qs):
value = list(result)[0][k]
print("%s: %s" % (Q,value))
Q_values[Q] = value
sys.exit(0)
# bah this is ugly!!!
R_det = R.det()
#det_table = {}
det_table = OrderedDict()
开发者ID:kenorb-contrib,项目名称:Feynman-knowledge-engine,代码行数:31,代码来源:sympy--solve-ds-5-5-polynomial-v3.py
示例13: test_linsolve
def test_linsolve():
x, y, z, u, v, w = symbols("x, y, z, u, v, w")
x1, x2, x3, x4 = symbols("x1, x2, x3, x4")
# Test for different input forms
M = Matrix([[1, 2, 1, 1, 7], [1, 2, 2, -1, 12], [2, 4, 0, 6, 4]])
system1 = A, b = M[:, :-1], M[:, -1]
Eqns = [x1 + 2 * x2 + x3 + x4 - 7, x1 + 2 * x2 + 2 * x3 - x4 - 12, 2 * x1 + 4 * x2 + 6 * x4 - 4]
sol = FiniteSet((-2 * x2 - 3 * x4 + 2, x2, 2 * x4 + 5, x4))
assert linsolve(M, (x1, x2, x3, x4)) == sol
assert linsolve(Eqns, (x1, x2, x3, x4)) == sol
assert linsolve(system1, (x1, x2, x3, x4)) == sol
# raise ValueError if no symbols are given
raises(ValueError, lambda: linsolve(system1))
# raise ValueError if, A & b is not given as tuple
raises(ValueError, lambda: linsolve(A, b, x1, x2, x3, x4))
# raise ValueError for garbage value
raises(ValueError, lambda: linsolve(Eqns[0], x1, x2, x3, x4))
# Fully symbolic test
a, b, c, d, e, f = symbols("a, b, c, d, e, f")
A = Matrix([[a, b], [c, d]])
B = Matrix([[e], [f]])
system2 = (A, B)
sol = FiniteSet(((-b * f + d * e) / (a * d - b * c), (a * f - c * e) / (a * d - b * c)))
assert linsolve(system2, [x, y]) == sol
# Test for Dummy Symbols issue #9667
x1 = Dummy("x1")
x2 = Dummy("x2")
x3 = Dummy("x3")
x4 = Dummy("x4")
assert linsolve(system1, x1, x2, x3, x4) == FiniteSet((-2 * x2 - 3 * x4 + 2, x2, 2 * x4 + 5, x4))
# No solution
A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]])
b = Matrix([0, 0, 1])
assert linsolve((A, b), (x, y, z)) == EmptySet()
# Issue #10056
A, B, J1, J2 = symbols("A B J1 J2")
Augmatrix = Matrix(
[[2 * I * J1, 2 * I * J2, -2 / J1], [-2 * I * J2, -2 * I * J1, 2 / J2], [0, 2, 2 * I / (J1 * J2)], [2, 0, 0]]
)
assert linsolve(Augmatrix, A, B) == FiniteSet((0, I / (J1 * J2)))
# Issue #10121 - Assignment of free variables
a, b, c, d, e = symbols("a, b, c, d, e")
Augmatrix = Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]])
assert linsolve(Augmatrix, a, b, c, d, e) == FiniteSet((a, 0, c, 0, e))
示例14: interpolating_spline
def interpolating_spline(d, x, X, Y):
"""Return spline of degree ``d``, passing through the given ``X``
and ``Y`` values.
This function returns a piecewise function such that each part is
a polynomial of degree not greater than ``d``. The value of ``d``
must be 1 or greater and the values of ``X`` must be strictly
increasing.
Examples
========
>>> from sympy import interpolating_spline
>>> from sympy.abc import x
>>> interpolating_spline(1, x, [1, 2, 4, 7], [3, 6, 5, 7])
Piecewise((3*x, (x >= 1) & (x <= 2)),
(7 - x/2, (x >= 2) & (x <= 4)),
(2*x/3 + 7/3, (x >= 4) & (x <= 7)))
>>> interpolating_spline(3, x, [-2, 0, 1, 3, 4], [4, 2, 1, 1, 3])
Piecewise((-x**3/36 - x**2/36 - 17*x/18 + 2, (x >= -2) & (x <= 1)),
(5*x**3/36 - 13*x**2/36 - 11*x/18 + 7/3, (x >= 1) & (x <= 4)))
See Also
========
bsplines_basis_set, sympy.polys.specialpolys.interpolating_poly
"""
from sympy import symbols, Number, Dummy, Rational
from sympy.solvers.solveset import linsolve
from sympy.matrices.dense import Matrix
# Input sanitization
d = sympify(d)
if not(d.is_Integer and d.is_positive):
raise ValueError(
"Spline degree must be a positive integer, not %s." % d)
if len(X) != len(Y):
raise ValueError(
"Number of X and Y coordinates must be the same.")
if len(X) < d + 1:
raise ValueError(
"Degree must be less than the number of control points.")
if not all(a < b for a, b in zip(X, X[1:])):
raise ValueError(
"The x-coordinates must be strictly increasing.")
# Evaluating knots value
if d.is_odd:
j = (d + 1) // 2
interior_knots = X[j:-j]
else:
j = d // 2
interior_knots = [Rational(a + b, 2) for a, b in
zip(X[j:-j - 1], X[j + 1:-j])]
knots = [X[0]] * (d + 1) + list(interior_knots) + [X[-1]] * (d + 1)
basis = bspline_basis_set(d, knots, x)
A = [[b.subs(x, v) for b in basis] for v in X]
coeff = linsolve((Matrix(A), Matrix(Y)), symbols('c0:{}'.format(
len(X)), cls=Dummy))
coeff = list(coeff)[0]
intervals = set([c for b in basis for (e, c) in b.args
if c != True])
# Sorting the intervals
# ival contains the end-points of each interval
ival = [e.atoms(Number) for e in intervals]
ival = [list(sorted(e))[0] for e in ival]
com = zip(ival, intervals)
com = sorted(com, key=lambda x: x[0])
intervals = [y for x, y in com]
basis_dicts = [dict((c, e) for (e, c) in b.args) for b in basis]
spline = []
for i in intervals:
piece = sum([c*d.get(i, S.Zero) for (c, d) in
zip(coeff, basis_dicts)], S.Zero)
spline.append((piece, i))
return(Piecewise(*spline))