本文整理汇总了Python中sympy.factor函数的典型用法代码示例。如果您正苦于以下问题:Python factor函数的具体用法?Python factor怎么用?Python factor使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了factor函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: simplify
def simplify(self):
self._eqn = sympy.factor(sympy.numer(sympy.factor(self._eqn)))
if isinstance(self._eqn, sympy.Mul):
def is_not_constant(ex):
sym = ex.free_symbols
return x in sym or y in sym or z in sym
self._eqn = sympy.Mul(*(filter(is_not_constant, self._eqn.args)))
示例2: main
def main():
u, v, R = symbols('u v R', real=True)
xi, eta = symbols(r'\xi \eta', cls=Function)
numer = 4*R**2
denom = u**2 + v**2 + numer
# inverse of a stereographic projection from the south pole
# onto the XY plane:
pinv = Matrix([numer * u / denom,
numer * v / denom,
-(2 * R * (u**2 + v**2)) / denom]) # OK
if False:
# textbook style
Dpinv = simplify(pinv.jacobian([u, v]))
print_latex(Dpinv, mat_str='pmatrix', mat_delim=None) # OK?
tDpinvDpinv = factor(Dpinv.transpose() @ Dpinv)
print_latex(tDpinvDpinv, mat_str='pmatrix', mat_delim=None) # OK
tDpinvDpinv = tDpinvDpinv.subs([(u, xi(t)), (v, eta(t))])
dcdt = Matrix([xi(t).diff(), eta(t).diff()])
print_latex(simplify(
sqrt((dcdt.transpose() @ tDpinvDpinv).dot(dcdt))))
else:
# directly
dpinvc = pinv.subs([(u, xi(t)), (v, eta(t))]).diff(t, 1)
print_latex(sqrt(factor(dpinvc.dot(dpinvc))))
示例3: sympy_factor
def sympy_factor(expr_sympy):
try:
result = sympy.together(expr_sympy)
numer, denom = result.as_numer_denom()
if denom == 1:
result = sympy.factor(expr_sympy)
else:
result = sympy.factor(numer) / sympy.factor(denom)
except sympy.PolynomialError:
return expr_sympy
return result
示例4: test_binomial_symbolic
def test_binomial_symbolic():
n = 10 # Because we're using for loops, can't do symbolic n
p = symbols('p', positive=True)
X = Binomial('X', n, p)
assert simplify(E(X)) == n*p
assert simplify(variance(X)) == n*p*(1 - p)
assert factor(simplify(skewness(X))) == factor((1-2*p)/sqrt(n*p*(1-p)))
# Test ability to change success/failure winnings
H, T = symbols('H T')
Y = Binomial('Y', n, p, succ=H, fail=T)
assert simplify(E(Y)) == simplify(n*(H*p + T*(1 - p)))
示例5: test_factor_expand
def test_factor_expand():
A = MatrixSymbol("A", n, n)
B = MatrixSymbol("B", n, n)
expr1 = (A + B)*(C + D)
expr2 = A*C + B*C + A*D + B*D
assert expr1 != expr2
assert expand(expr1) == expr2
assert factor(expr2) == expr1
expr = B**(-1)*(A**(-1)*B**(-1) - A**(-1)*C*B**(-1))**(-1)*A**(-1)
I = Identity(n)
# Ideally we get the first, but we at least don't want a wrong answer
assert factor(expr) in [I - C, B**-1*(A**-1*(I - C)*B**-1)**-1*A**-1]
示例6: apply
def apply(self, expr, evaluation):
'Factor[expr_]'
expr_sympy = expr.to_sympy()
try:
result = sympy.together(expr_sympy)
numer, denom = result.as_numer_denom()
if denom == 1:
result = sympy.factor(expr_sympy)
else:
result = sympy.factor(numer) / sympy.factor(denom)
except sympy.PolynomialError:
return expr
return from_sympy(result)
示例7: _inverse_mellin_transform
def _inverse_mellin_transform(F, s, x_, strip, as_meijerg=False):
""" A helper for the real inverse_mellin_transform function, this one here
assumes x to be real and positive. """
from sympy import (expand, expand_mul, hyperexpand, meijerg, And, Or,
arg, pi, re, factor, Heaviside, gamma, Add)
x = _dummy('t', 'inverse-mellin-transform', F, positive=True)
# Actually, we won't try integration at all. Instead we use the definition
# of the Meijer G function as a fairly general inverse mellin transform.
F = F.rewrite(gamma)
for g in [factor(F), expand_mul(F), expand(F)]:
if g.is_Add:
# do all terms separately
ress = [_inverse_mellin_transform(G, s, x, strip, as_meijerg,
noconds=False) \
for G in g.args]
conds = [p[1] for p in ress]
ress = [p[0] for p in ress]
res = Add(*ress)
if not as_meijerg:
res = factor(res, gens=res.atoms(Heaviside))
return res.subs(x, x_), And(*conds)
try:
a, b, C, e, fac = _rewrite_gamma(g, s, strip[0], strip[1])
except IntegralTransformError:
continue
G = meijerg(a, b, C/x**e)
if as_meijerg:
h = G
else:
h = hyperexpand(G)
if h.is_Piecewise and len(h.args) == 3:
# XXX we break modularity here!
h = Heaviside(x - abs(C))*h.args[0].args[0] \
+ Heaviside(abs(C) - x)*h.args[1].args[0]
# We must ensure that the intgral along the line we want converges,
# and return that value.
# See [L], 5.2
cond = [abs(arg(G.argument)) < G.delta*pi]
# Note: we allow ">=" here, this corresponds to convergence if we let
# limits go to oo symetrically. ">" corresponds to absolute convergence.
cond += [And(Or(len(G.ap) != len(G.bq), 0 >= re(G.nu) + 1),
abs(arg(G.argument)) == G.delta*pi)]
cond = Or(*cond)
if cond is False:
raise IntegralTransformError('Inverse Mellin', F, 'does not converge')
return (h*fac).subs(x, x_), cond
raise IntegralTransformError('Inverse Mellin', F, '')
示例8: test_fourier_transform
def test_fourier_transform():
from sympy import simplify, expand, expand_complex, factor, expand_trig
FT = fourier_transform
IFT = inverse_fourier_transform
def simp(x):
return simplify(expand_trig(expand_complex(expand(x))))
def sinc(x):
return sin(pi*x)/(pi*x)
k = symbols('k', real=True)
f = Function("f")
# TODO for this to work with real a, need to expand abs(a*x) to abs(a)*abs(x)
a = symbols('a', positive=True)
b = symbols('b', positive=True)
posk = symbols('posk', positive=True)
# Test unevaluated form
assert fourier_transform(f(x), x, k) == FourierTransform(f(x), x, k)
assert inverse_fourier_transform(
f(k), k, x) == InverseFourierTransform(f(k), k, x)
# basic examples from wikipedia
assert simp(FT(Heaviside(1 - abs(2*a*x)), x, k)) == sinc(k/a)/a
# TODO IFT is a *mess*
assert simp(FT(Heaviside(1 - abs(a*x))*(1 - abs(a*x)), x, k)) == sinc(k/a)**2/a
# TODO IFT
assert factor(FT(exp(-a*x)*Heaviside(x), x, k), extension=I) == \
1/(a + 2*pi*I*k)
# NOTE: the ift comes out in pieces
assert IFT(1/(a + 2*pi*I*x), x, posk,
noconds=False) == (exp(-a*posk), True)
assert IFT(1/(a + 2*pi*I*x), x, -posk,
noconds=False) == (0, True)
assert IFT(1/(a + 2*pi*I*x), x, symbols('k', negative=True),
noconds=False) == (0, True)
# TODO IFT without factoring comes out as meijer g
assert factor(FT(x*exp(-a*x)*Heaviside(x), x, k), extension=I) == \
1/(a + 2*pi*I*k)**2
assert FT(exp(-a*x)*sin(b*x)*Heaviside(x), x, k) == \
b/(b**2 + (a + 2*I*pi*k)**2)
assert FT(exp(-a*x**2), x, k) == sqrt(pi)*exp(-pi**2*k**2/a)/sqrt(a)
assert IFT(sqrt(pi/a)*exp(-(pi*k)**2/a), k, x) == exp(-a*x**2)
assert FT(exp(-a*abs(x)), x, k) == 2*a/(a**2 + 4*pi**2*k**2)
示例9: tests
def tests():
x, y, z = symbols('x,y,z')
#print(x + x + 1)
expr = x**2 - y**2
factors = factor(expr)
print(factors, " | ", expand(factors))
pprint(expand(factors))
示例10: _as_ratfun_delay
def _as_ratfun_delay(self):
"""Split expr as (N, D, delay)
where expr = (N / D) * exp(var * delay)
Note, delay only represents a delay when var is s."""
expr, var = self.expr, self.var
F = sym.factor(expr).as_ordered_factors()
delay = sympify(0)
ratfun = sympify(1)
for f in F:
b, e = f.as_base_exp()
if b == sym.E and e.is_polynomial(var):
p = sym.Poly(e, var)
c = p.all_coeffs()
if p.degree() == 1:
delay -= c[0]
if c[1] != 0:
ratfun *= sym.exp(c[1])
continue
ratfun *= f
if not ratfun.is_rational_function(var):
raise ValueError('Expression not a product of rational function'
' and exponential')
numer, denom = ratfun.as_numer_denom()
N = sym.Poly(numer, var)
D = sym.Poly(denom, var)
return N, D, delay
示例11: solve_high
def solve_high(self, params):
poly = x**(4+self.num_of_keys)
for n in xrange(4+self.num_of_keys):
poly += params[n]*x**(4+self.num_of_keys-n-1)
if self.debug:
print "[*] factor:", poly
return solve(factor(poly))
示例12: as_ratfun_delay_undef
def as_ratfun_delay_undef(expr, var):
delay = sym.S.Zero
undef = sym.S.One
if expr.is_rational_function(var):
N, D = expr.as_numer_denom()
return N, D, delay, undef
F = sym.factor(expr).as_ordered_factors()
rf = sym.S.One
for f in F:
b, e = f.as_base_exp()
if b == sym.E and e.is_polynomial(var):
p = sym.Poly(e, var)
c = p.all_coeffs()
if p.degree() == 1:
delay -= c[0]
if c[1] != 0:
rf *= sym.exp(c[1])
continue
if isinstance(f, sym.function.AppliedUndef):
undef *= f
continue
rf *= f
if not rf.is_rational_function(var):
raise ValueError('Expression not a product of rational function'
' exponential, and undefined functions')
N, D = rf.as_numer_denom()
return N, D, delay, undef
示例13: deltaproduct
def deltaproduct(f, limit):
"""
Handle products containing a KroneckerDelta.
See Also
========
deltasummation
sympy.functions.special.tensor_functions.KroneckerDelta
sympy.concrete.products.product
"""
from sympy.concrete.products import product
if ((limit[2] - limit[1]) < 0) is True:
return S.One
if not f.has(KroneckerDelta):
return product(f, limit)
if f.is_Add:
# Identify the term in the Add that has a simple KroneckerDelta
delta = None
terms = []
for arg in sorted(f.args, key=default_sort_key):
if delta is None and _has_simple_delta(arg, limit[0]):
delta = arg
else:
terms.append(arg)
newexpr = f.func(*terms)
k = Dummy("kprime", integer=True)
if isinstance(limit[1], int) and isinstance(limit[2], int):
result = deltaproduct(newexpr, limit) + sum([
deltaproduct(newexpr, (limit[0], limit[1], ik - 1)) *
delta.subs(limit[0], ik) *
deltaproduct(newexpr, (limit[0], ik + 1, limit[2])) for ik in range(int(limit[1]), int(limit[2] + 1))]
)
else:
result = deltaproduct(newexpr, limit) + deltasummation(
deltaproduct(newexpr, (limit[0], limit[1], k - 1)) *
delta.subs(limit[0], k) *
deltaproduct(newexpr, (limit[0], k + 1, limit[2])), (k, limit[1], limit[2]), no_piecewise=True
)
return _remove_multiple_delta(result)
delta, _ = _extract_delta(f, limit[0])
if not delta:
g = _expand_delta(f, limit[0])
if f != g:
from sympy import factor
try:
return factor(deltaproduct(g, limit))
except AssertionError:
return deltaproduct(g, limit)
return product(f, limit)
from sympy import Eq
c = Eq(limit[2], limit[1] - 1)
return _remove_multiple_delta(f.subs(limit[0], limit[1])*KroneckerDelta(limit[2], limit[1])) + \
S.One*_simplify_delta(KroneckerDelta(limit[2], limit[1] - 1))
示例14: test_H27
def test_H27():
f = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5
g = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z
h = -2*z*y**7 \
*(6*x**9*y**9*z**3 + 10*x**7*z**6 + 17*y*x**5*z**12 + 40*y**7) \
*(3*x**22 + 47*x**17*y**5*z**8 - 6*x**15*y**9*z**2 - 24*x*y**19*z**8 - 5)
assert factor(expand(f*g)) == h
示例15: test_nsimplify
def test_nsimplify():
x = Symbol("x")
assert nsimplify(0) == 0
assert nsimplify(-1) == -1
assert nsimplify(1) == 1
assert nsimplify(1 + x) == 1 + x
assert nsimplify(2.7) == Rational(27, 10)
assert nsimplify(1 - GoldenRatio) == (1 - sqrt(5))/2
assert nsimplify((1+sqrt(5))/4, [GoldenRatio]) == GoldenRatio/2
assert nsimplify(2/GoldenRatio, [GoldenRatio]) == 2*GoldenRatio - 2
assert nsimplify(exp(5*pi*I/3, evaluate=False)) == sympify('1/2 - sqrt(3)*I/2')
assert nsimplify(sin(3*pi/5, evaluate=False)) == sympify('sqrt(sqrt(5)/8 + 5/8)')
assert nsimplify(sqrt(atan('1', evaluate=False))*(2+I), [pi]) == sqrt(pi) + sqrt(pi)/2*I
assert nsimplify(2 + exp(2*atan('1/4')*I)) == sympify('49/17 + 8*I/17')
assert nsimplify(pi, tolerance=0.01) == Rational(22, 7)
assert nsimplify(pi, tolerance=0.001) == Rational(355, 113)
assert nsimplify(0.33333, tolerance=1e-4) == Rational(1, 3)
assert nsimplify(2.0**(1/3.), tolerance=0.001) == Rational(635, 504)
assert nsimplify(2.0**(1/3.), tolerance=0.001, full=True) == 2**Rational(1, 3)
assert nsimplify(x + .5, rational=True) == Rational(1, 2) + x
assert nsimplify(1/.3 + x, rational=True) == Rational(10, 3) + x
assert nsimplify(log(3).n(), rational=True) == \
sympify('109861228866811/100000000000000')
assert nsimplify(Float(0.272198261287950), [pi,log(2)]) == pi*log(2)/8
assert nsimplify(Float(0.272198261287950).n(3), [pi,log(2)]) == \
-pi/4 - log(2) + S(7)/4
assert nsimplify(x/7.0) == x/7
assert nsimplify(pi/1e2) == pi/100
assert nsimplify(pi/1e2, rational=False) == pi/100.0
assert nsimplify(pi/1e-7) == 10000000*pi
assert not nsimplify(factor(-3.0*z**2*(z**2)**(-2.5) + 3*(z**2)**(-1.5))).atoms(Float)