[Python-Dev] Fraction arithmetic (Was: Decimal ... float comparisons in py3k) (original) (raw)

Guido van Rossum guido at python.org
Sat Mar 20 20:04:08 CET 2010


On Sat, Mar 20, 2010 at 4:58 AM, Mark Dickinson <dickinsm at gmail.com> wrote:

On Sat, Mar 20, 2010 at 11:41 AM, Paul Moore <p.f.moore at gmail.com> wrote:

On 20 March 2010 04:20, Nick Coghlan <ncoghlan at gmail.com> wrote:

In the case of floats and Decimals, there's no ambiguity here that creates any temptation to guess - to determine a true/false result for a comparison, floats can be converted explicitly to Decimals without any loss of accuracy. For Fractions, the precedent has already been set by allowing implicit (potentially lossy) conversion to binary floats - a lossy conversion to Decimal wouldn't be any worse.

Hmm, given that a float can be converted losslessly to a fraction, why was the decision taken to convert the fraction to a float rather than the other way round? I'm not sure of the actual reason for this decision, but one argument I've seen used for other languages is that it's desirable for the inexactness of the float type to be contagious:  rationals are perceived as exact, while floats are perceived as approximations.

You hit the nail on the head.

Note that this only applies to arithmetic operations:  for comparisons, an exact conversion is performed.  This is much like what currently happens with ints and floats in the core:  a mixed-type arithmetic operation between an int and a float first converts the int to a float (possibly changing the value in the process).  A mixed-type comparison makes an exact comparison without doing such a conversion. For example (in any non-ancient version of Python):

n = 2**53 + 1 x = 2.**53 n > x   # compares exact values;  no conversion performed True n - x    # converts n to a float before subtracting 0.0 I don't see a PEP for the fractions module, and my google-fu has failed to find anything. Was there a discussion on this? There's PEP 3141 (http://www.python.org/dev/peps/pep-3141/), which was the motivation for adding the fractions module in the first place, and there's the issue tracker item for the fractions module (http://bugs.python.org/issue1682).

-- --Guido van Rossum (python.org/~guido)



More information about the Python-Dev mailing list