本文整理汇总了Python中sympy.factor函数的典型用法代码示例。如果您正苦于以下问题:Python factor函数的具体用法?Python factor怎么用?Python factor使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了factor函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)))
开发者ID:Delfad0r,项目名称:python-bary,代码行数:7,代码来源:bary.py
示例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))))
开发者ID:showa-yojyo,项目名称:notebook,代码行数:28,代码来源:stereograph.py
示例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
开发者ID:0xffea,项目名称:Mathics,代码行数:11,代码来源:algebra.py
示例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)))
开发者ID:FireJade,项目名称:sympy,代码行数:12,代码来源:test_finite_rv.py
示例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]
开发者ID:asmeurer,项目名称:sympy,代码行数:13,代码来源:test_matexpr.py
示例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)
开发者ID:0xffea,项目名称:Mathics,代码行数:14,代码来源:algebra.py
示例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, '')
开发者ID:ALGHeArT,项目名称:sympy,代码行数:49,代码来源:transforms.py
示例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)
开发者ID:FedericoV,项目名称:sympy,代码行数:49,代码来源:test_transforms.py
示例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))
开发者ID:JSONMartin,项目名称:codingChallenges,代码行数:7,代码来源:sympy_math.py
示例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
开发者ID:bcbnz,项目名称:lcapy,代码行数:34,代码来源:core.py
示例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))
开发者ID:pheehs,项目名称:QuinticEncrypt,代码行数:7,代码来源:quintic_encrypt.py
示例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
开发者ID:mph-,项目名称:lcapy,代码行数:33,代码来源:ratfun.py
示例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))
开发者ID:alhirzel,项目名称:sympy,代码行数:60,代码来源:delta.py
示例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
开发者ID:batya239,项目名称:sympy,代码行数:7,代码来源:test_wester.py
示例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)
开发者ID:Vance-Turner,项目名称:sympy,代码行数:31,代码来源:test_simplify.py
示例16: apply_list
def apply_list(self, expr, vars, evaluation):
'FactorTermsList[expr_, vars_List]'
if expr == Integer(0):
return Expression('List', Integer(1), Integer(0))
elif isinstance(expr, Number):
return Expression('List', expr, Integer(1))
for x in vars.leaves:
if not(isinstance(x, Atom)):
return evaluation.message('CoefficientList', 'ivar', x)
sympy_expr = expr.to_sympy()
if sympy_expr is None:
return Expression('List', Integer(1), expr)
sympy_expr = sympy.together(sympy_expr)
sympy_vars = [x.to_sympy() for x in vars.leaves if isinstance(x, Symbol) and sympy_expr.is_polynomial(x.to_sympy())]
result = []
numer, denom = sympy_expr.as_numer_denom()
try:
from sympy import factor, factor_list, Poly
if denom == 1:
# Get numerical part
num_coeff, num_polys = factor_list(Poly(numer))
result.append(num_coeff)
# Get factors are independent of sub list of variables
if (sympy_vars and isinstance(expr, Expression)
and any(x.free_symbols.issubset(sympy_expr.free_symbols) for x in sympy_vars)):
for i in reversed(range(len(sympy_vars))):
numer = factor(numer) / factor(num_coeff)
num_coeff, num_polys = factor_list(Poly(numer), *[x for x in sympy_vars[:(i+1)]])
result.append(sympy.expand(num_coeff))
# Last factor
numer = factor(numer) / factor(num_coeff)
result.append(sympy.expand(numer))
else:
num_coeff, num_polys = factor_list(Poly(numer))
den_coeff, den_polys = factor_list(Poly(denom))
result = [num_coeff / den_coeff, sympy.expand(factor(numer)/num_coeff / (factor(denom)/den_coeff))]
except sympy.PolynomialError: # MMA does not raise error for non poly
result.append(sympy.expand(numer))
# evaluation.message(self.get_name(), 'poly', expr)
return Expression('List', *[from_sympy(i) for i in result])
开发者ID:Piruzzolo,项目名称:Mathics,代码行数:47,代码来源:algebra.py
示例17: test_factor_nc
def test_factor_nc():
x, y = symbols('x,y')
k = symbols('k', integer=True)
n, m, o = symbols('n,m,o', commutative=False)
# mul and multinomial expansion is needed
from sympy.simplify.simplify import _mexpand
e = x*(1 + y)**2
assert _mexpand(e) == x + x*2*y + x*y**2
def factor_nc_test(e):
ex = _mexpand(e)
assert ex.is_Add
f = factor_nc(ex)
assert not f.is_Add and _mexpand(f) == ex
factor_nc_test(x*(1 + y))
factor_nc_test(n*(x + 1))
factor_nc_test(n*(x + m))
factor_nc_test((x + m)*n)
factor_nc_test(n*m*(x*o + n*o*m)*n)
s = Sum(x, (x, 1, 2))
factor_nc_test(x*(1 + s))
factor_nc_test(x*(1 + s)*s)
factor_nc_test(x*(1 + sin(s)))
factor_nc_test((1 + n)**2)
factor_nc_test((x + n)*(x + m)*(x + y))
factor_nc_test(x*(n*m + 1))
factor_nc_test(x*(n*m + x))
factor_nc_test(x*(x*n*m + 1))
factor_nc_test(x*n*(x*m + 1))
factor_nc_test(x*(m*n + x*n*m))
factor_nc_test(n*(1 - m)*n**2)
factor_nc_test((n + m)**2)
factor_nc_test((n - m)*(n + m)**2)
factor_nc_test((n + m)**2*(n - m))
factor_nc_test((m - n)*(n + m)**2*(n - m))
assert factor_nc(n*(n + n*m)) == n**2*(1 + m)
assert factor_nc(m*(m*n + n*m*n**2)) == m*(m + n*m*n)*n
eq = m*sin(n) - sin(n)*m
assert factor_nc(eq) == eq
# for coverage:
from sympy.physics.secondquant import Commutator
from sympy import factor
eq = 1 + x*Commutator(m, n)
assert factor_nc(eq) == eq
eq = x*Commutator(m, n) + x*Commutator(m, o)*Commutator(m, n)
assert factor(eq) == x*(1 + Commutator(m, o))*Commutator(m, n)
# issue 3435
assert (2*n + 2*m).factor() == 2*(n + m)
# issue 3602
assert factor_nc(n**k + n**(k + 1)) == n**k*(1 + n)
assert factor_nc((m*n)**k + (m*n)**(k + 1)) == (1 + m*n)*(m*n)**k
开发者ID:Abhityagi16,项目名称:sympy,代码行数:59,代码来源:test_exprtools.py
示例18: 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
开发者ID:cklb,项目名称:sympy,代码行数:8,代码来源:test_matexpr.py
示例19: test_issue_841
def test_issue_841():
a,b,c,d = symbols('a:d', positive=True, bounded=True)
assert integrate(exp(-x**2 + I*c*x), x) == sqrt(pi)*erf(x - I*c/2)*exp(-c**S(2)/4)/2
assert integrate(exp(a*x**2 + b*x + c), x) == I*sqrt(pi)*erf(-I*x*sqrt(a) - I*b/(2*sqrt(a)))*exp(c)*exp(-b**2/(4*a))/(2*sqrt(a))
a,b,c,d = symbols('a:d', positive=True)
i = integrate(exp(-a*x**2 + 2*d*x), (x, -oo, oo))
ans = sqrt(pi)*exp(d**2/a)*(1 + erf(oo - d/sqrt(a)))/(2*sqrt(a))
n, d = i.as_numer_denom()
assert factor(n, expand=False)/d == ans
开发者ID:josephmisiti,项目名称:sympy,代码行数:9,代码来源:test_integrals.py
示例20: __factor
def __factor(self):
try:
print("Factoring..")
expr = sympy.sympify(self.ent.get())
fexpr = sympy.factor(expr)
print(str(fexpr))
self.res["text"] = "Your expression factors as %s" % str(fexpr)
except Exception as e:
showerror("ERROR!", str(e))
开发者ID:BookOwl,项目名称:pymath,代码行数:9,代码来源:factorWidget.py
注:本文中的sympy.factor函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论