Python has no numeric type with the semantics of an unboundedly precise rational number. This proposal explains the semantics of such a type, and suggests builtin functions and literals to support such a type. This PEP suggests no literals for rational numbers; that is left for another PEP.
RationaleWhile sometimes slower and more memory intensive (in general, unboundedly so) rational arithmetic captures more closely the mathematical ideal of numbers, and tends to have behavior which is less surprising to newbies. Though many Python implementations of rational numbers have been written, none of these exist in the core, or are documented in any way. This has made them much less accessible to people who are less Python-savvy.
RationalTypeThere will be a new numeric type added called RationalType
. Its unary operators will do the obvious thing. Binary operators will coerce integers and long integers to rationals, and rationals to floats and complexes.
The following attributes will be supported: .numerator
and .denominator
. The language definition will promise that:
r.denominator * r == r.numerator
that the GCD of the numerator and the denominator is 1 and that the denominator is positive.
The method r.trim(max_denominator)
will return the closest rational s
to r
such that abs(s.denominator) <= max_denominator
.
This function will have the signature rational(n, d=1)
. n
and d
must both be integers, long integers or rationals. A guarantee is made that:
s[5/3 - 2/3]
be equivalent to s[1]
?shift
and mask
operators be allowed for rational numbers? For rational numbers with integer values?Arguments for unifying ints with rationals:
2 == 2/1
and maybe str(2/1) == '2'
, it reduces surprises where objects seem equal but behave differently./
can be freely used for integer division when I know that there is no remainder (if I am wrong and there is a remainder, there will probably be some exception later).Arguments against:
/
as a sequence index, it’s usually an error which should not be hidden by making the program working for some data, since it will break for other data.This document has been placed in the public domain.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4