How about adding rational fraction to Python?

Lie Lie.1296 at gmail.com
Sun Mar 2 07:53:56 EST 2008


On Mar 2, 2:02 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> Lie <Lie.1... at gmail.com> writes:
> > So basically they refused to satisfy everything that is still possible
> > individually but would conflict if done together.
>
> I can't understand that.
>
> > x = 1
> > a = x + 1    << decides it's an int
>
> No, so far a and x are both Num (indeterminate)
>
> > b = x + 1.0  << error? or redefine to be float?
>
> This determines that a, b, and x are all floats.  It's not "redefined"
> since the types were unknown prior to this.
>
> Actually, I'm slightly wrong, 1.0 is not a float, it's a "Fractional"
> which is a narrower class than Num but it could still be Float, Double,
> or Rational.  Nums support addition, subtraction, multiplication, but
> not necessarily division.  So int/int is an error.  Fractionals support
> division.
>
> > c = x + 1    << would this cause error while it worked in line 2?
>
> No, c is also a float (actually Fractional)
>
> > A slightly obfuscated example:
> > l = [1, 1.0, 1]
>
> This is the same as l = [1.0, 1.0, 1.0].  In Haskell, all elements
> of a list must have the same type, so the 1.0 determines that l is
> a list of fractionals.
>
> > x = 1
> > for n in l:
> >   c = x + n
>
> Haskell does not have loops, but if it did, all these values would be
> fractionals.

That's quite complex and restrictive, but probably it's because my
mind is not tuned to Haskell yet. Anyway, I don't think Python should
work that way, because Python have a plan for numerical integration
which would unify all numerical types into an apparent single type,
which requires removal of operator's limitations.

On Mar 2, 2:23 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> Steven D'Aprano <st... at REMOVE-THIS-cybersource.com.au> writes:
> > def mean(data): return sum(data)/len(data)
>
> > That does the right thing for data, no matter of what it consists of:
> > floats, ints, Decimals, rationals, complex numbers, or a mix of all of
> > the above.
>
> One of those types is not like the others: for all of them except int,
> the quotient operation actually is the inverse of multiplication.
> So I'm unpersuaded that the "mean" operation above does the "right
> thing" for ints.  If the integers being averaged were prices
> in dollars, maybe the result type should even be decimal.

In __future__ Python or Python 3.0, that mean function would work for
all types. And divisions on int is also inverse of multiplications,
just like subtraction is the inverse of addition:
from __future import division
a = 10
b = 5
c = a / b
if c * b == a: print 'multiplication is inverse of division'



More information about the Python-list mailing list