PEP239 (Rational Numbers) Reference Implementation and new issues
Bengt Richter
bokr at oz.net
Fri Oct 4 10:28:38 EDT 2002
On 4 Oct 2002 00:45:39 -0700, paul at boddie.net (Paul Boddie) wrote:
>"Chris Gonnerman" <chris.gonnerman at newcenturycomputers.net> wrote in message news:<mailman.1033615625.14473.python-list at python.org>...
>>
>> But I don't want to see rationals if I haven't asked for
>> them.
>
>[...]
>
>> but would it hurt so much to say
>>
>> 1/3R
>>
>> instead?
>
>How about the use of specially formed rational literals using the
>underscore notation, which I'm sure exists in various other systems?
>For example:
>
> 1_3
>
>The standard operators would produce rational results from rational
>inputs:
>
> 1_3 + 2 == 7_3
> 1_3 - 2 == -5_3
> 1_3 / 2 == 1_6
> 1_3 * 2 == 2_3
>
>Use of floating point values in such operations would either produce
>errors:
>
> 1_3 + 2.5 -> TypeError
Why? All floating point numbers can be viewed as exact rationals
of the form n_<2**e> with e>=0
>>> R(1,3)
1_3
>>> R(2.5)
5_2
>>> R(1.0, 3.0)
1_3
>>> import math
>>> R(math.pi)
884279719003555_281474976710656
Multiply by big ten power and divide, and you can recognize it
>>> 884279719003555L*10L**40/281474976710656L
31415926535897931159979634685441851615905L
>>> math.pi
3.1415926535897931
the denominator is 2**48
>>> 2l**48
281474976710656L
>
>Or they could coerce the result to floating point (with the usual
>consequences):
>
> 1_3 + 2.5 -> 1.0 / 3.0 + 2.5 == 2.8333333333333335
>
>One would then need to define operators or functions to produce
>rationals from other types:
>
> rational(1, 3) == 1_3
> rational(1) == 1_1
> rational(1.5) -> TypeError
>>> R(1, 3)
1_3
>>> R(1)
1_1
>>> R(1.5)
3_2
>
>And certain built-in functions would need changing:
>
> int(1_3) == 0
> float(1_3) -> 1.0 / 3.0 == 0.33333333333333331
>
>I'm sure that all this has been discussed over and over again before,
>though.
>
Probably ;-)
Using timbot's fixedpoint.py as a template, it should be relatively easy to
hack together something. Getting all the decisions made is another thing ;-)
Regards,
Bengt Richter
More information about the Python-list
mailing list