1

I am trying to factor a polynomial of booleans to get the minimal form of a logic net. My variables are a1, a2, a3 ... and the negative counterparts na1, na2, na3 ...

If would expect a function

f = a1*a2*b2*nb1 + a1*b1*na2*nb2 + a1*b1*na2 + a2*b2*na1*nb1 

to be factored like this (at least) :

f = a1*b1*(b2*nb1 + na2*(nb2 + 1)) + a2*b2*na1*nb1

I run this script:

import sympy
a1,a2,b1,b2,b3,na1,na2,na3,nb1,nb2,nb3 = \
            sympy.symbols("a1:3, b1:4, na1:4, nb1:4", bool=True)
f = "a1*na2*b1 + a1*a2*nb1*b2 + a1*na2*b1*nb2 + na1*a2*nb1*b2"
sympy.init_printing(use_unicode=True)
sympy.factor(f)

and this returns me the same function, not factored.

a1*a2*b2*nb1 + a1*b1*na2*nb2 + a1*b1*na2 + a2*b2*na1*nb1

What am I doing wrong ?

Ecir Hana
  • 10,864
  • 13
  • 67
  • 117
angelo.mastro
  • 1,680
  • 17
  • 14
  • Does this help? http://docs.sympy.org/latest/modules/polys/wester.html#advanced-factoring-over-finite-fields – PM 2Ring Nov 13 '17 at 11:22
  • have you tested the outcome ? – angelo.mastro Nov 13 '17 at 12:04
  • No, I don't use sympy, although I know a few things about finite fields. I just figured it might be helpful. – PM 2Ring Nov 13 '17 at 12:11
  • Yes I read the doc. I can't make it work. If you add other comments, test the outcome first, so we are talking about the same issue ... – angelo.mastro Nov 13 '17 at 12:36
  • 1
    Sorry, I don't have an answer to your question. If I did, I'd write an answer. In my first comment I wasn't claiming to have the solution to your problem, I was simply asking a question which I felt may be helpful to you, and I figured your answer to my question could be helpful to the Sympy users who have the knowledge required to give a proper answer to your question. – PM 2Ring Nov 13 '17 at 12:46
  • Related: [Partially factoring an expression in Sympy](https://stackoverflow.com/q/52046815). The function given in my answer there rewrites this `f` as `a2*b2*nb1*(a1 + na1) + b1*(a1*na2*nb2 + a1*na2)`. –  Aug 27 '18 at 22:08

1 Answers1

2

Your expected output

f = a1*b1*(b2*nb1 + na2*(nb2 + 1)) + a2*b2*na1*nb1

is not a factorization of f, so factor is not going to produce it. To factor something means to write it as a product, not "a product plus some other stuff".

If you give a polynomial that can actually be factored, say f = a1*na2*b1 + a1*a2*nb1*b2 + a1*na2*b1*nb2, then factor(f) has an effect.

What you are looking for is closer to collecting the terms with the same variable, which is done with collect.

f = a1*na2*b1 + a1*a2*nb1*b2 + a1*na2*b1*nb2 + na1*a2*nb1*b2
collect(f, a1)

outputs

a1*(a2*b2*nb1 + b1*na2*nb2 + b1*na2) + a2*b2*na1*nb1

The method coeff also works in that direction, e.g., f.coeff(a1) returns the contents of the parentheses in the previous formula.

  • ah. good stuff. my mistake was to use sympy with a string argument 'a1*na2*b1 + ... ', so "collect" and other stuff I had tried didn't work. Thanks this helped – angelo.mastro Nov 14 '17 at 22:45