473,769 Members | 6,160 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A Revised Rational Proposal

This version includes the input from various and sundry people. Thanks
to everyone who contributed.

<mike

PEP: XXX
Title: A rational number module for Python
Version: $Revision: 1.4 $
Last-Modified: $Date: 2003/09/22 04:51:50 $
Author: Mike Meyer <mw*@mired.or g>
Status: Draft
Type: Staqndards
Content-Type: text/x-rst
Created: 16-Dec-2004
Python-Version: 2.5
Post-History: 15-Dec-2004, 25-Dec-2004
Contents
========

* Abstract
* Motivation
* Rationale
+ Conversions
+ Python usability
* Specification
+ Explicit Construction
+ Implicit Construction
+ Operations
+ Exceptions
* Open Issues
* Implementation
* References
Abstract
========

This PEP proposes a rational number module to add to the Python
standard library.
Motivation
=========

Rationals are a standard mathematical concept, included in a variety
of programming languages already. Python, which comes with 'batteries
included' should not be deficient in this area. When the subject was
brought up on comp.lang.pytho n several people mentioned having
implemented a rational number module, one person more than once. In
fact, there is a rational number module distributed with Python as an
example module. Such repetition shows the need for such a class in the
standard library.
n
There are currently two PEPs dealing with rational numbers - 'Adding a
Rational Type to Python' [#PEP-239] and 'Adding a Rational Literal to
Python' [#PEP-240], both by Craig and Zadka. This PEP competes with
those PEPs, but does not change the Python language as those two PEPs
do [#PEP-239-implicit]. As such, it should be easier for it to gain
acceptance. At some future time, PEP's 239 and 240 may replace the
``rational`` module.
Rationale
=========

Conversions
-----------

The purpose of a rational type is to provide an exact representation
of rational numbers, without the imprecistion of floating point
numbers or the limited precision of decimal numbers.

Converting an int or a long to a rational can be done without loss of
precision, and will be done as such.

Converting a decimal to a rational can also be done without loss of
precision, and will be done as such.

A floating point number generally represents a number that is an
approximation to the value as a literal string. For example, the
literal 1.1 actually represents the value 1.1000000000000 001 on an x86
one platform. To avoid this imprecision, floating point numbers
cannot be translated to rationals directly. Instead, a string
representation of the float must be used: ''Rational("%.2 f" % flt)''
so that the user can specify the precision they want for the floating
point number. This lack of precision is also why floating point
numbers will not combine with rationals using numeric operations.

Decimal numbers do not have the representation problems that floating
point numbers have. However, they are rounded to the current context
when used in operations, and thus represent an approximation.
Therefore, a decimal can be used to explicitly construct a rational,
but will not be allowed to implicitly construct a rational by use in a
mixed arithmetic expression.
Python Usability
-----------------

* Rational should support the basic arithmetic (+, -, *, /, //, **, %,
divmod) and comparison (==, !=, <, >, <=, >=, cmp) operators in the
following cases (check Implicit Construction to see what types could
OtherType be, and what happens in each case):

+ Rational op Rational
+ Rational op otherType
+ otherType op Rational
+ Rational op= Rational
+ Rational op= otherType
* Rational should support unary operators (-, +, abs).

* repr() should round trip, meaning that:

m = Rational(...)
m == eval(repr(m))

* Rational should be immutable.

* Rational should support the built-in methods:

+ min, max
+ float, int, long
+ str, repr
+ hash
+ bool (0 is false, otherwise true)

When it comes to hashes, it is true that Rational(25) == 25 is True, so
hash(Rational (25)) should be equal to hash(25).

The detail is that you can NOT compare Rational to floats, strings or
decimals, so we do not worry about them giving the same hashes. In
short:

hash(n) == hash(Rational(n )) # Only if n is int, long or Rational

Regarding str() and repr() behaviour, Ka-Ping Yee proposes that repr() have
the same behaviour as str() and Tim Peters proposes that str() behave like the
to-scientific-string operation from the Spec.
Specification
=============

Explicit Construction
---------------------

The module shall be ``rational``, and the class ``Rational``, to
follow the example of the decimal [#PEP-327] module. The class
creation method shall accept as arguments a numerator, and an optional
denominator, which defaults to one. Both the numerator and
denominator - if present - must be of integer or decimal type, or a
string representation of a floating point number. The string
representation of a floating point number will be converted to
rational without being converted to float to preserve the accuracy of
the number. Since all other numeric types in Python are immutable,
Rational objects will be immutable. Internally, the representation
will insure that the numerator and denominator have a greatest common
divisor of 1, and that the sign of the denominator is positive.
Implicit Construction
---------------------

Rationals will mix with integer types. If the other operand is not
rational, it will be converted to rational before the opeation is
performed.

When combined with a floating type - either complex or float - or a
decimal type, the result will be a TypeError. The reason for this is
that floating point numbers - including complex - and decimals are
already imprecise. To convert them to rational would give an
incorrect impression that the results of the operation are
precise. The proper way to add a rational to one of these types is to
convert the rational to that type explicitly before doing the
operation.
Operations
----------

The ``Rational`` class shall define all the standard mathematical
operations mentioned in the ''Python Usability'' section.

Rationals can be converted to floats by float(rational) , and to
integers by int(rational). int(rational) will just do an integer
division of the numerator by the denominator.

If there is not a __decimal__ feature for objects in Python 2.5, the
rational type will provide a decimal() method that returns the value
of self converted to a decimal in the current context.
Exceptions
----------

The module will define and at times raise the following exceptions:

- DivisionByZero: divide by zero.

- OverflowError: overflow attempting to convert to a float.

- TypeError: trying to create a rational from a non-integer or
non-string type, or trying to perform an operation
with a float, complex or decimal.

- ValueError: trying to create a rational from a string value that is
not a valid represetnation of an integer or floating
point number.

Note that the decimal initializer will have to be modified to handle
rationals.
Open Issues
===========

- Should raising a rational to a non-integer rational silently produce
a float, or raise an InvalidOperatio n exception?

Implementation
==============

There is currently a rational module distributed with Python, and a
second rational module in the Python cvs source tree that is not
distributed. While one of these could be chosen and made to conform
to the specification, I am hoping that several people will volunteer
implementatins so that a ''best of breed'' implementation may be
chosen.
References
==========

... [#PEP-239] Adding a Rational Type to Python, Craig, Zadka
(http://www.python.org/peps/pep-0239.html)
... [#PEP-240] Adding a Rational Literal to Python, Craig, Zadka
(http://www.python.org/peps/pep-0240.html)
... [#PEP-327] Decimal Data Type, Batista
(http://www.python.org/peps/pep-0327.html)
... [#PEP-239-implicit] PEP 240 adds a new literal type to Pytbon,
PEP 239 implies that division of integers would
change to return rationals.
Copyright
=========

This document has been placed in the public domain.

...
Local Variables:
mode: indented-text
indent-tabs-mode: nil
sentence-end-double-space: t
fill-column: 70
End:

--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 18 '05
20 2145
"Dan Bishop" <da*****@yahoo. com> writes:
Mike Meyer wrote:
This version includes the input from various and sundry people. Thanks
to everyone who contributed.

<mike

PEP: XXX
Title: A rational number module for Python

...
Implementation
==============

There is currently a rational module distributed with Python, and a
second rational module in the Python cvs source tree that is not
distributed. While one of these could be chosen and made to conform
to the specification, I am hoping that several people will volunteer
implementatins so that a ''best of breed'' implementation may be
chosen.


I'll be the first to volunteer an implementation.


I've already got two implementations . Both vary from the PEP.
I've made the following deviations from your PEP:

* Binary operators with one Rational operand and one float or Decimal
operand will not raise a TypeError, but return a float or Decimal.
* Expressions of the form Decimal op Rational do not work. This is a
bug in the decimal module.
* The constructor only accepts ints and longs. Conversions from float
or Decimal to Rational can be made with the static methods:
- fromExactFloat: exact conversion from float to Rational
- fromExactDecima l: exact conversion from Decimal to Rational
- approxSmallestD enominator: Minimizes the result's denominator,
given a maximum allowed error.
- approxSmallestE rror: Minimizes the result's error, given a
maximum allowed denominator.
For example,


Part of finishing the PEP will be modifying the chosen contribution so
that it matches the PEP. As the PEP champion, I'll take that one (and
also write a test module) before submitting the PEP to the pep list
for inclusion and possible finalization.

If you still wish to contribute your code, please mail it to me as an
attachment.

Thanks,
<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 18 '05 #11
"John Roth" <ne********@jhr othjr.com> writes:
I'd suggest making them public rather than either protected or
private. There's a precident with the complex module, where
the real and imaginary parts are exposed as .real and .imag.


This isn't addressed in the PEP, and is an oversight on my part. I'm
against making them public, as Rational's should be immutable. Making
the two features public invites people to change them, meaning that
machinery has to be put in place to prevent that. That means either
making all attribute access go through __getattribute_ _ for new-style
classes, or making them old-style classes, which is discouraged.

If the class is reimplented in C, making them read-only attributes as
they are in complex makes sense, and should be considered at that
time.
<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 18 '05 #12
Nick Coghlan <nc******@iinet .net.au> writes:
Mike Meyer wrote:
Regarding str() and repr() behaviour, Ka-Ping Yee proposes that repr() have
the same behaviour as str() and Tim Peters proposes that str() behave like the
to-scientific-string operation from the Spec.


This looks like a C & P leftover from the Decimal PEP :)


Yup. Thank you. This now reads:

Regarding str() and repr() behaviour, repr() will be either
''rational(num) '' if the denominator is one, or ''rational(num,
denom)'' if the denominator is not one. str() will be either ''num''
if the denominator is one, or ''(num / denom)'' if the denominator is
not one.

Is that acceptable?

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 18 '05 #13
Mike Meyer wrote:
"John Roth" <ne********@jhr othjr.com> writes:

I'd suggest making them public rather than either protected or
private. There's a precident with the complex module, where
the real and imaginary parts are exposed as .real and .imag.

This isn't addressed in the PEP, and is an oversight on my part. I'm
against making them public, as Rational's should be immutable. Making
the two features public invites people to change them, meaning that
machinery has to be put in place to prevent that. That means either
making all attribute access go through __getattribute_ _ for new-style
classes, or making them old-style classes, which is discouraged.


Can't you just use properties?
class Rational(object ): .... def num():
.... def get(self):
.... return self._num
.... return dict(fget=get)
.... num = property(**num( ))
.... def denom():
.... def get(self):
.... return self._denom
.... return dict(fget=get)
.... denom = property(**deno m())
.... def __init__(self, num, denom):
.... self._num = num
.... self._denom = denom
.... r = Rational(1, 2)
r.denom 2 r.num 1 r.denom = 2

Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
AttributeError: can't set attribute

Steve
Jul 18 '05 #14
Mike Meyer wrote:
Yup. Thank you. This now reads:

Regarding str() and repr() behaviour, repr() will be either
''rational(num) '' if the denominator is one, or ''rational(num,
denom)'' if the denominator is not one. str() will be either ''num''
if the denominator is one, or ''(num / denom)'' if the denominator is
not one.

Is that acceptable?


Sounds fine to me.

On the str() front, I was wondering if Rational("x / y") should be an acceptable
string input format.

Cheers,
Nick.

--
Nick Coghlan | nc******@email. com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #15
Dan Bishop wrote:
Steven Bethard wrote:
Dan Bishop wrote:
Mike Meyer wrote:

PEP: XXX

I'll be the first to volunteer an implementation.


Very cool. Thanks for the quick work!

For stdlib acceptance, I'd suggest a few cosmetic changes:

No problem.

"""Implementati on of rational arithmetic."""

[Yards of unusable code]

I'd also request that you change all leading tabs to four spaces!

regards
Steve
--
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
Holden Web LLC +1 703 861 4237 +1 800 494 3119
Jul 18 '05 #16
Mike> ... or making them old-style classes, which is discouraged.

Since when is use of old-style classes discouraged?

Skip
Jul 18 '05 #17
Skip Montanaro wrote:
Mike> ... or making them old-style classes, which is discouraged.

Since when is use of old-style classes discouraged?


Well, since new-style classes came along, surely? I should have thought
the obvious way to move forward was to only use old-style classes when
their incompatible-with-type-based-classes behavior is absolutely required.

Though personally I should have said "use of new-style classes is
encouraged". I agree that there's no real need to change existing code
just for the sake of it, but it would be interesting to see just how
much existing code fails when preceded by the 1.5.2--to-2.4-compatible (?)

__metaclass__ = type

guessing-not-that-much-ly y'rs - steve
--
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
Holden Web LLC +1 703 861 4237 +1 800 494 3119
Jul 18 '05 #18
Nick Coghlan <nc******@iinet .net.au> writes:
Mike Meyer wrote:
Yup. Thank you. This now reads:
Regarding str() and repr() behaviour, repr() will be either
''rational(num) '' if the denominator is one, or ''rational(num,
denom)'' if the denominator is not one. str() will be either ''num''
if the denominator is one, or ''(num / denom)'' if the denominator is
not one.
Is that acceptable?


Sounds fine to me.

On the str() front, I was wondering if Rational("x / y") should be an
acceptable string input format.


I don't think so, as I don't see it coming up often enough to warrant
implementing. However, Rational("x" / "y") will be an acceptable
string format as fallout from accepting floating point string
representations .

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 18 '05 #19
Skip Montanaro <sk**@pobox.com > writes:
Mike> ... or making them old-style classes, which is discouraged.

Since when is use of old-style classes discouraged?


I was under the imperssion that old-style classes were going away, and
hence discouraged for new library modules.

However, a way to deal with this cleanly has been suggested by Steven
Bethard, so the point is moot for this discussion.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 18 '05 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

31
2997
by: Raymond Hettinger | last post by:
Based on your extensive feedback, PEP 322 has been completely revised. The response was strongly positive, but almost everyone preferred having a function instead of multiple object methods. The updated proposal is at: www.python.org/peps/pep-0322.html In a nutshell, it proposes a builtin function that greatly simplifies reverse iteration. The core concept is that clarity comes from specifying a sequence in a forward direction and...
21
2421
by: Mike Meyer | last post by:
PEP: XXX Title: A rational number module for Python Version: $Revision: 1.4 $ Last-Modified: $Date: 2003/09/22 04:51:50 $ Author: Mike Meyer <mwm@mired.org> Status: Draft Type: Staqndards Content-Type: text/x-rst Created: 16-Dec-2004 Python-Version: 2.5
18
1917
by: Lie | last post by:
I'm very surprised actually, to see that Python rejected the use of fractional/rational numbers. However, when I read the PEP, I know exactly why the proposal was rejected: People compared fractions with integers, while it should be more fairly compared to floats. Arguments against: - When I use the result of / as a sequence index, it's usually an error which should not be hidden by making the program working for some data, since it...
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10211
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9994
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7409
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5299
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3959
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3562
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.