本文整理汇总了Python中sympy.core.function._mexpand函数的典型用法代码示例。如果您正苦于以下问题:Python _mexpand函数的具体用法?Python _mexpand怎么用?Python _mexpand使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_mexpand函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _sqrt_symbolic_denest
def _sqrt_symbolic_denest(a, b, r):
"""Given an expression, sqrt(a + b*sqrt(b)), return the denested
expression or None.
Algorithm:
If r = ra + rb*sqrt(rr), try replacing sqrt(rr) in ``a`` with
(y**2 - ra)/rb, and if the result is a quadratic, ca*y**2 + cb*y + cc, and
(cb + b)**2 - 4*ca*cc is 0, then sqrt(a + b*sqrt(r)) can be rewritten as
sqrt(ca*(sqrt(r) + (cb + b)/(2*ca))**2).
Examples
========
>>> from sympy.simplify.sqrtdenest import _sqrt_symbolic_denest, sqrtdenest
>>> from sympy import sqrt, Symbol
>>> from sympy.abc import x
>>> a, b, r = 16 - 2*sqrt(29), 2, -10*sqrt(29) + 55
>>> _sqrt_symbolic_denest(a, b, r)
sqrt(-2*sqrt(29) + 11) + sqrt(5)
If the expression is numeric, it will be simplified:
>>> w = sqrt(sqrt(sqrt(3) + 1) + 1) + 1 + sqrt(2)
>>> sqrtdenest(sqrt((w**2).expand()))
1 + sqrt(2) + sqrt(1 + sqrt(1 + sqrt(3)))
Otherwise, it will only be simplified if assumptions allow:
>>> w = w.subs(sqrt(3), sqrt(x + 3))
>>> sqrtdenest(sqrt((w**2).expand()))
sqrt((sqrt(sqrt(sqrt(x + 3) + 1) + 1) + 1 + sqrt(2))**2)
Notice that the argument of the sqrt is a square. If x is made positive
then the sqrt of the square is resolved:
>>> _.subs(x, Symbol('x', positive=True))
sqrt(sqrt(sqrt(x + 3) + 1) + 1) + 1 + sqrt(2)
"""
a, b, r = map(sympify, (a, b, r))
rval = _sqrt_match(r)
if not rval:
return None
ra, rb, rr = rval
if rb:
y = Dummy('y', positive=True)
try:
newa = Poly(a.subs(sqrt(rr), (y**2 - ra)/rb), y)
except PolynomialError:
return None
if newa.degree() == 2:
ca, cb, cc = newa.all_coeffs()
cb += b
if _mexpand(cb**2 - 4*ca*cc).equals(0):
z = sqrt(ca*(sqrt(r) + cb/(2*ca))**2)
if z.is_number:
z = _mexpand(Mul._from_args(z.as_content_primitive()))
return z
示例2: _sqrtdenest_rec
def _sqrtdenest_rec(expr):
"""Helper that denests the square root of three or more surds.
It returns the denested expression; if it cannot be denested it
throws SqrtdenestStopIteration
Algorithm: expr.base is in the extension Q_m = Q(sqrt(r_1),..,sqrt(r_k));
split expr.base = a + b*sqrt(r_k), where `a` and `b` are on
Q_(m-1) = Q(sqrt(r_1),..,sqrt(r_(k-1))); then a**2 - b**2*r_k is
on Q_(m-1); denest sqrt(a**2 - b**2*r_k) and so on.
See [1], section 6.
Examples
========
>>> from sympy import sqrt
>>> from sympy.simplify.sqrtdenest import _sqrtdenest_rec
>>> _sqrtdenest_rec(sqrt(-72*sqrt(2) + 158*sqrt(5) + 498))
-sqrt(10) + sqrt(2) + 9 + 9*sqrt(5)
>>> w=-6*sqrt(55)-6*sqrt(35)-2*sqrt(22)-2*sqrt(14)+2*sqrt(77)+6*sqrt(10)+65
>>> _sqrtdenest_rec(sqrt(w))
-sqrt(11) - sqrt(7) + sqrt(2) + 3*sqrt(5)
"""
from sympy.simplify.simplify import radsimp, split_surds, rad_rationalize
if not expr.is_Pow:
return sqrtdenest(expr)
if expr.base < 0:
return sqrt(-1)*_sqrtdenest_rec(sqrt(-expr.base))
g, a, b = split_surds(expr.base)
a = a*sqrt(g)
if a < b:
a, b = b, a
c2 = _mexpand(a**2 - b**2)
if len(c2.args) > 2:
g, a1, b1 = split_surds(c2)
a1 = a1*sqrt(g)
if a1 < b1:
a1, b1 = b1, a1
c2_1 = _mexpand(a1**2 - b1**2)
c_1 = _sqrtdenest_rec(sqrt(c2_1))
d_1 = _sqrtdenest_rec(sqrt(a1 + c_1))
num, den = rad_rationalize(b1, d_1)
c = _mexpand(d_1/sqrt(2) + num/(den*sqrt(2)))
else:
c = _sqrtdenest1(sqrt(c2))
if sqrt_depth(c) > 1:
raise SqrtdenestStopIteration
ac = a + c
if len(ac.args) >= len(expr.args):
if count_ops(ac) >= count_ops(expr.base):
raise SqrtdenestStopIteration
d = sqrtdenest(sqrt(ac))
if sqrt_depth(d) > 1:
raise SqrtdenestStopIteration
num, den = rad_rationalize(b, d)
r = d/sqrt(2) + num/(den*sqrt(2))
r = radsimp(r)
return _mexpand(r)
示例3: _sqrtdenest1
def _sqrtdenest1(expr, denester=True):
"""Return denested expr after denesting with simpler methods or, that
failing, using the denester."""
from sympy.simplify.simplify import radsimp
if not is_sqrt(expr):
return expr
a = expr.base
if a.is_Atom:
return expr
val = _sqrt_match(a)
if not val:
return expr
a, b, r = val
# try a quick numeric denesting
d2 = _mexpand(a**2 - b**2*r)
if d2.is_Rational:
if d2.is_positive:
z = _sqrt_numeric_denest(a, b, r, d2)
if z is not None:
return z
else:
# fourth root case
# sqrtdenest(sqrt(3 + 2*sqrt(3))) =
# sqrt(2)*3**(1/4)/2 + sqrt(2)*3**(3/4)/2
dr2 = _mexpand(-d2*r)
dr = sqrt(dr2)
if dr.is_Rational:
z = _sqrt_numeric_denest(_mexpand(b*r), a, r, dr2)
if z is not None:
return z/root(r, 4)
else:
z = _sqrt_symbolic_denest(a, b, r)
if z is not None:
return z
if not denester or not is_algebraic(expr):
return expr
res = sqrt_biquadratic_denest(expr, a, b, r, d2)
if res:
return res
# now call to the denester
av0 = [a, b, r, d2]
z = _denester([radsimp(expr**2)], av0, 0, sqrt_depth(expr))[0]
if av0[1] is None:
return expr
if z is not None:
if sqrt_depth(z) == sqrt_depth(expr) and count_ops(z) > count_ops(expr):
return expr
return z
return expr
示例4: check_solutions
def check_solutions(eq):
"""
Determines whether solutions returned by diophantine() satisfy the original
equation. Hope to generalize this so we can remove functions like check_ternay_quadratic,
check_solutions_normal, check_solutions()
"""
s = diophantine(eq)
terms = factor_list(eq)[1]
var = list(eq.free_symbols)
var.sort(key=default_sort_key)
okay = True
while len(s) and okay:
solution = s.pop()
okay = False
for term in terms:
subeq = term[0]
if simplify(_mexpand(Subs(subeq, var, solution).doit())) == 0:
okay = True
break
return okay
示例5: is_pell_transformation_ok
def is_pell_transformation_ok(eq):
"""
Test whether X*Y, X, or Y terms are present in the equation
after transforming the equation using the transformation returned
by transformation_to_pell(). If they are not present we are good.
Moreover, coefficient of X**2 should be a divisor of coefficient of
Y**2 and the constant term.
"""
A, B = transformation_to_DN(eq)
u = (A*Matrix([X, Y]) + B)[0]
v = (A*Matrix([X, Y]) + B)[1]
simplified = _mexpand(Subs(eq, (x, y), (u, v)).doit())
coeff = dict([reversed(t.as_independent(*[X, Y])) for t in simplified.args])
for term in [X*Y, X, Y]:
if term in coeff.keys():
return False
for term in [X**2, Y**2, Integer(1)]:
if term not in coeff.keys():
coeff[term] = Integer(0)
if coeff[X**2] != 0:
return isinstance(S(coeff[Y**2])/coeff[X**2], Integer) and isinstance(S(coeff[Integer(1)])/coeff[X**2], Integer)
return True
示例6: _minpoly_cos
def _minpoly_cos(ex, x):
"""
Returns the minimal polynomial of ``cos(ex)``
see http://mathworld.wolfram.com/TrigonometryAngles.html
"""
from sympy import sqrt
c, a = ex.args[0].as_coeff_Mul()
if a is pi:
if c.is_rational:
if c.p == 1:
if c.q == 7:
return 8*x**3 - 4*x**2 - 4*x + 1
if c.q == 9:
return 8*x**3 - 6*x + 1
elif c.p == 2:
q = sympify(c.q)
if q.is_prime:
s = _minpoly_sin(ex, x)
return _mexpand(s.subs({x:sqrt((1 - x)/2)}))
# for a = pi*p/q, cos(q*a) =T_q(cos(a)) = (-1)**p
n = int(c.q)
a = dup_chebyshevt(n, ZZ)
a = [x**(n - i)*a[i] for i in range(n + 1)]
r = Add(*a) - (-1)**c.p
_, factors = factor_list(r)
res = _choose_factor(factors, x, ex)
return res
raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex)
示例7: _sqrtdenest0
def _sqrtdenest0(expr):
"""Returns expr after denesting its arguments."""
if is_sqrt(expr):
n, d = expr.as_numer_denom()
if d is S.One: # n is a square root
if n.base.is_Add:
args = sorted(n.base.args, key=default_sort_key)
if len(args) > 2 and all((x**2).is_Integer for x in args):
try:
return _sqrtdenest_rec(n)
except SqrtdenestStopIteration:
pass
expr = sqrt(_mexpand(Add(*[_sqrtdenest0(x) for x in args])))
return _sqrtdenest1(expr)
else:
n, d = [_sqrtdenest0(i) for i in (n, d)]
return n/d
if isinstance(expr, Add):
cs = []
args = []
for arg in expr.args:
c, a = arg.as_coeff_Mul()
cs.append(c)
args.append(a)
if all(c.is_Rational for c in cs) and all(is_sqrt(arg) for arg in args):
return _sqrt_ratcomb(cs, args)
if isinstance(expr, Expr):
args = expr.args
if args:
return expr.func(*[_sqrtdenest0(a) for a in args])
return expr
示例8: find
def find(a):
n = len(a)
for i in range(n - 1):
for j in range(i + 1, n):
s1 = a[i].base
s2 = a[j].base
p = _mexpand(s1 * s2)
s = sqrtdenest(sqrt(p))
if s != sqrt(p):
return s, i, j
示例9: nthroot
def nthroot(expr, n, max_len=4, prec=15):
"""
compute a real nth-root of a sum of surds
Parameters
==========
expr : sum of surds
n : integer
max_len : maximum number of surds passed as constants to ``nsimplify``
Algorithm
=========
First ``nsimplify`` is used to get a candidate root; if it is not a
root the minimal polynomial is computed; the answer is one of its
roots.
Examples
========
>>> from sympy.simplify.simplify import nthroot
>>> from sympy import Rational, sqrt
>>> nthroot(90 + 34*sqrt(7), 3)
sqrt(7) + 3
"""
expr = sympify(expr)
n = sympify(n)
p = expr**Rational(1, n)
if not n.is_integer:
return p
if not _is_sum_surds(expr):
return p
surds = []
coeff_muls = [x.as_coeff_Mul() for x in expr.args]
for x, y in coeff_muls:
if not x.is_rational:
return p
if y is S.One:
continue
if not (y.is_Pow and y.exp == S.Half and y.base.is_integer):
return p
surds.append(y)
surds.sort()
surds = surds[:max_len]
if expr < 0 and n % 2 == 1:
p = (-expr)**Rational(1, n)
a = nsimplify(p, constants=surds)
res = a if _mexpand(a**n) == _mexpand(-expr) else p
return -res
a = nsimplify(p, constants=surds)
if _mexpand(a) is not _mexpand(p) and _mexpand(a**n) == _mexpand(expr):
return _mexpand(a)
expr = _nthroot_solve(expr, n, prec)
if expr is None:
return p
return expr
示例10: rad_rationalize
def rad_rationalize(num, den):
"""
Rationalize num/den by removing square roots in the denominator;
num and den are sum of terms whose squares are rationals
Examples
========
>>> from sympy import sqrt
>>> from sympy.simplify.radsimp import rad_rationalize
>>> rad_rationalize(sqrt(3), 1 + sqrt(2)/3)
(-sqrt(3) + sqrt(6)/3, -7/9)
"""
if not den.is_Add:
return num, den
g, a, b = split_surds(den)
a = a*sqrt(g)
num = _mexpand((a - b)*num)
den = _mexpand(a**2 - b**2)
return rad_rationalize(num, den)
示例11: is_normal_transformation_ok
def is_normal_transformation_ok(eq):
A = transformation_to_normal(eq)
X, Y, Z = A*Matrix([x, y, z])
simplified = _mexpand(Subs(eq, (x, y, z), (X, Y, Z)).doit())
coeff = dict([reversed(t.as_independent(*[X, Y, Z])) for t in simplified.args])
for term in [X*Y, Y*Z, X*Z]:
if term in coeff.keys():
return False
return True
示例12: _lambert
def _lambert(eq, x):
"""
Given an expression assumed to be in the form
``F(X, a..f) = a*log(b*X + c) + d*X + f = 0``
where X = g(x) and x = g^-1(X), return the Lambert solution if possible:
``x = g^-1(-c/b + (a/d)*W(d/(a*b)*exp(c*d/a/b)*exp(-f/a)))``.
"""
eq = _mexpand(expand_log(eq))
mainlog = _mostfunc(eq, log, x)
if not mainlog:
return [] # violated assumptions
other = eq.subs(mainlog, 0)
if (-other).func is log:
eq = (eq - other).subs(mainlog, mainlog.args[0])
mainlog = mainlog.args[0]
if mainlog.func is not log:
return [] # violated assumptions
other = -(-other).args[0]
eq += other
if not x in other.free_symbols:
return [] # violated assumptions
d, f, X2 = _linab(other, x)
logterm = collect(eq - other, mainlog)
a = logterm.as_coefficient(mainlog)
if a is None or x in a.free_symbols:
return [] # violated assumptions
logarg = mainlog.args[0]
b, c, X1 = _linab(logarg, x)
if X1 != X2:
return [] # violated assumptions
u = Dummy('rhs')
sol = []
# check only real solutions:
for k in [-1, 0]:
l = LambertW(d/(a*b)*exp(c*d/a/b)*exp(-f/a), k)
# if W's arg is between -1/e and 0 there is
# a -1 branch real solution, too.
if k and not l.is_real:
continue
rhs = -c/b + (a/d)*l
solns = solve(X1 - u, x)
for i, tmp in enumerate(solns):
solns[i] = tmp.subs(u, rhs)
sol.append(solns[i])
return sol
示例13: _sqrtdenest0
def _sqrtdenest0(expr):
"""Returns expr after denesting its arguments."""
if is_sqrt(expr):
n, d = expr.as_numer_denom()
if d is S.One: # n is a square root
if n.base.is_Add:
args = sorted(n.base.args, key=default_sort_key)
if len(args) > 2 and all((x**2).is_Integer for x in args):
try:
return _sqrtdenest_rec(n)
except SqrtdenestStopIteration:
pass
expr = sqrt(_mexpand(Add(*[_sqrtdenest0(x) for x in args])))
return _sqrtdenest1(expr)
else:
n, d = [_sqrtdenest0(i) for i in (n, d)]
return n/d
if isinstance(expr, Expr):
args = expr.args
if args:
return expr.func(*[_sqrtdenest0(a) for a in args])
return expr
示例14: _nthroot_solve
def _nthroot_solve(p, n, prec):
"""
helper function for ``nthroot``
It denests ``p**Rational(1, n)`` using its minimal polynomial
"""
from sympy.polys.numberfields import _minimal_polynomial_sq
from sympy.solvers import solve
while n % 2 == 0:
p = sqrtdenest(sqrt(p))
n = n // 2
if n == 1:
return p
pn = p**Rational(1, n)
x = Symbol('x')
f = _minimal_polynomial_sq(p, n, x)
if f is None:
return None
sols = solve(f, x)
for sol in sols:
if abs(sol - pn).n() < 1./10**prec:
sol = sqrtdenest(sol)
if _mexpand(sol**n) == p:
return sol
示例15: test_mexpand
def test_mexpand():
from sympy.abc import x
assert _mexpand(None) is None
assert _mexpand(1) is S.One
assert _mexpand(x*(x + 1)**2) == (x*(x + 1)**2).expand()