PEP 327: Decimal Data Type
danb_83 at yahoo.com
Sat Feb 7 02:53:28 CET 2004
Josiah Carlson <jcarlson at nospam.uci.edu> wrote in message news:<bvjj49$c94$1 at news.service.uci.edu>...
> > Was your implementation [of rationals] the 'not too bad to get working' or
> > the 'doing it well'?
> For all the standard operations on a rational type, all you need is to
> make sure all you have is two pairs of numerators and denominators, then
> all the numeric manipulation is trivial:
> a + b = rational(a.n*b.d + b.n*a.d, a.d*b.d)
> a - b = rational(a.n*b.d - b.n*a.d, a.d*b.d)
> a * b = rational(a.n*b.n, a.d*b.d)
> a / b = rational(a.n*b.d, a.d*b.n)
floor(a) = a.n // a.d
a // b = floor(a / b)
> a ** b, b is an integer >= 1 (binary exponentiation)
It's even more trivial when b=0: The result is 1.
And when b < 0, a ** b can be calculated as (1 / a) ** (-b)
More information about the Python-list