On Thu, Dec 8, 2011 at 11:25 AM, Mateusz Paprocki <[email protected]> wrote: > Hi, > > On 6 December 2011 08:28, smichr <[email protected]> wrote: >> >> Is there any place in sympy for mixed representation? in pprint, a >> Rational method? >> >> >> Rational(7, 3).mixed >> '2 1/3' >> or >> (2, 1/3) >> >> I was working with a younger math class and wishing for this today. > > > You can implement a printer for this, e.g.: > > class XStrPrinter(StrPrinter): > def _print_Rational(self, r): > p = abs(r.p) > q = r.q > a = p//q > b = p % q > c = q > if not a: > s = "%s/%s" % (b, c) > else: > s = "%s %s/%s" % (a, b, c) > if r.p < 0: > s = "-" + s > return s > > Otherwise you can implement MixedRational class (or similar). >
Ah, the dynamic nature of things: paste the following into an interactive session from sympy.printing import StrPrinter def _print_Rational(self, r): s = sign(r) p, q = s*r.p, r.q w, r = divmod(p, q) return '%s %s/%s' % (s*w, r, q) if w else '%s/%s' % (p, q) old_rat_print = StrPrinter._print_Rational StrPrinter._print_Rational = _print_Rational >>> for i in [-S(12)/5,-S(12)/3,S(0),S(2)/3,S(5)/3]: ... print i ... -2 2/5 -4 0 2/3 1 2/3 >>> StrPrinter._print_Rational = old_rat_print >>> for i in [-S(12)/5,-S(12)/3,S(0),S(2)/3,S(5)/3]: ... print i ... -12/5 -4 0 2/3 5/3 We could write a global switching function for this. I'm not sure how wide the interest is, so I'll just add this to a local library and use it interactively when desired. Thanks for the tip. One could also add a new method to Rational on the fly: >>> def mixed(r): ... s = sign(r) ... p, q = s*r.p, r.q ... w, r = divmod(p, q) ... return '%s %s/%s' % (s*w, r, q) if w else '%s/%s' % (p, q) ... >>> Rational.mixed = mixed >>> [r.mixed() for r in [Rational(12,5),Rational(3,4)]] ['2 2/5', '3/4'] /c /c -- You received this message because you are subscribed to the Google Groups "sympy" 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?hl=en.
