Ask Your Question
2

Pretty print factorizations as fractions

asked 2019-06-08 16:31:28 +0100

liu.henry.hl gravatar image

Hi all,

If I have an object whose factorization makes sense when expressed as a fraction, how do I get Sage to pretty print its factorization as a fraction instead of a product of factors? For example,

sage: R.<x> = PolynomialRing(QQ)
sage: f = (x - 1)^2 / (x + 1)
sage: f
(x^2 - 2*x + 1)/(x + 1)
sage: f.factor()
(x + 1)^-1 * (x - 1)^2

but ideally I would like some way to pretty print f as (x - 1)^2/(x + 1).

Thanks,

Henry

edit retag flag offensive close merge delete

2 Answers

Sort by » oldest newest most voted
1

answered 2019-06-09 10:46:43 +0100

FrédéricC gravatar image

Convert to the symbolic ring ?

sage: x = polygen(QQ, 'x')
sage: unicode_art((x**3+4)/(x**7-66))
(x^3 + 4)/(x^7 - 66)
sage: unicode_art(SR((x**3+4)/(x**7-66)))
  3    
 x  + 4
───────
 7     
x  - 66

sage: unicode_art(SR(factor((x**3+4)/(x**4-1))))
          3             
         x  + 4         
────────────────────────
                ⎛ 2    ⎞
(x - 1)⋅(x + 1)⋅⎝x  + 1⎠
edit flag offensive delete link more
2

answered 2019-06-08 16:55:51 +0100

slelievre gravatar image

updated 2019-06-30 14:34:29 +0100

One way to do that is to factor the numerator and then the denominator:

sage: print('({})/({})'.format(f.numerator().factor(), f.denominator().factor()))
((x - 1)^2)/(x + 1)

One could turn this into a function with a special case for no denominator:

def pretty_print_factor(f):
    d = f.denominator()
    if d == 1:
        print(f.factor())
    else:
        n = f.numerator().factor()
        print('({})/({})'.format(n, d.factor()))

Using this function, we get:

sage: pretty_print_factor(f)
((x - 1)^2)/(x + 1)

The function could be improved to leave out parenthesis when not needed.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2019-06-08 16:31:28 +0100

Seen: 1,964 times

Last updated: Jun 30 '19