Comment #1 on issue 2191 by [email protected]: Collecting numerical prefactors
http://code.google.com/p/sympy/issues/detail?id=2191

Yes, that's correct. This is the "2 arg mul" behavior. The only ways to get this to persist and be factored that way (without using symbol trickery) is to use evaluate=True to keep this from happening:

If the value is extractable from the whole expression factor will already give the evaluate=False expression for you
    >>> factor(.5*x+.5*y)
    0.5*(x + y)

Otherwise something like this can work:


    def ncollect(eq, n):
        """collect on a number n"""
        from sympy import collect, sympify, C, Add, Mul
        n = sympify(n)
        if not isinstance(n, Number):
            return collect(eq, n)
        # replace n with symbol
        dn = C.Dummy('')
        c = collect(eq.subs(n, dn), dn)
        args = list(Add.make_args(c))
        for i, a in enumerate(args):
            if a.is_Mul:
                margs = list(a.args)
                for j, m in enumerate(margs):
                    if m == dn:
                        args[i] = Mul(*([n] + margs[:j] + margs[j+1:]),
                                      evaluate=False)
                        return Add(*args, evaluate=False)
        return eq

    >>> ncollect(.5*x + .5*y + z, .5)
    z + 0.5*(x + y)

As soon as you do an operation with that result, the spell will be broken:

    >>> _ + a
    a + z + 0.5*x + 0.5*y

Collect does not support collecting on a number; my t2 branch allows you to ask for coefficients of numbers so you can do (2*x+2*y+z).coeff(2) and get x+y -- that would make the code above a little trimmer. In the meantime, perhaps the code above will help.

If you or anyone else is interested in having this be part of sympy's collect behavior and are willing to review it, let me know and I will submit work for review.

/c

--
You received this message because you are subscribed to the Google Groups 
"sympy-issues" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/sympy-issues?hl=en.

Reply via email to