修订后的Rational提案 [英] A Revised Rational Proposal

查看:61
本文介绍了修订后的Rational提案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此版本包含各种各样的人的意见。谢谢

给所有贡献的人。


< mike


PEP:XXX

标题:Python的有理数模块

版本:$修订版:1.4 $

最后修改日期:$ Date:2003/09/22 04:51:50 $

作者:Mike Meyer< mw*@mired.org>

状态:草稿

类型:Staqndards

内容类型:text / x-rst

创建时间:2004年12月16日

Python版本:2.5

后历史:2004年12月15日,2004年12月25日

目录

========


*摘要

*动机

*理由

+转换

+ Python可用性

*规格

+明确施工

+隐式施工

+操作

+例外

*未解决的问题

*实施

*参考资料

摘要

========


这个PEP为广告提出了一个有理数的模块d到Python

标准库。

动机

=========


Rationals是一个标准的数学概念,已经包含在各种编程语言中。包含''电池

包含''的Python不应该在这方面存在缺陷。当主题是在comp.lang.python上提出
时,有几个人提到

实现了一个有理数模块,一个人不止一次。在

中,有一个有理数的模块与Python一起分发为

示例模块。这样的重复表明在

标准库中需要这样的类。

n

目前有两个处理有理数的PEP - ''将一个

Rational Type添加到Python''[#PEP-239]和''将一个Rational Literal添加到
Python''[#PEP-240],两者都是克雷格和扎德卡。这个PEP与那些PEP竞争,但不会像那两个PEP那样改变Python语言。[#PEP-239-implicit]。因此,它应该更容易获得

接受。在未来的某个时间,PEP的239和240可以取代

`` rational``模块。

理由

=== ======


转换

-----------


理性类型的目的是提供一个有理数的精确表示,而不会忽略浮点数b / b $ b或十进制数的有限精度。


将int或long转换为Rational可以在不损失
精度的情况下完成,并且将会这样做。


将小数转换为有理数也可以在不损失

精度的情况下完成,并且可以这样做。


一般浮点数表示作为文字字符串的值近似值的数字。例如,

literal 1.1实际上代表x86

平台上的值1.1000000000000001。为避免这种不精确,浮点数

不能直接转换为有理数。相反,必须使用float的字符串

表示:''''Rational("%。2f"%flt)''''

以便用户可以为浮动

点数指定所需的精度。这种精度的缺乏也是为什么浮点

数字不会与使用数字运算的有理数结合的原因。

十进制数字没有表示浮动的问题

点数有。但是,它们在操作中使用时会四舍五入到当前上下文中,因此表示近似值。

因此,十进制可用于显式构造一个有理数,

但不允许在

混合算术表达式中隐式构造一个理性。

Python可用性

-----------------


* Rational应支持基本算术(+, - ,*,/,//,*

中的*,%,

divmod)和比较(==,!=,<,>,< =,> =,cmp)运算符以下情况(检查隐式构造以查看哪些类型可以

其他类型,以及每种情况下会发生什么):


+ Rational op Rational

+ Rational op otherType

+ otherType op Rational

+ Rational op = Rational

+ Rational op = otherType

* Rational应该支持一元运算符( - ,+,abs)。


* repr()应该往返,意思是那:


m = Rational(...)

m == eval(repr(m))


* Rational应该是不可变的。


* Rational应该支持内置方法:


+ min,max

+ float,int,long

+ str,repr

+ hash

+ bool(0为假,否则为真)


说到哈希,确实Rational(25)== 25是真的,所以

哈希(Rational(25))应该等于hash(25)。


细节是你不能将Rational与浮点数,字符串或

小数进行比较,所以我们不担心它们给出了相同的哈希。在

简短:


hash(n)== hash(Rational(n))#仅当n是int,long或Rational


关于str()和repr()行为,Ka-Ping Yee建议repr()与str()具有相同的行为,并且Tim Peters提出str( )表现得像Spec的

to-scientific-string操作。

规格

=========== ==


明确施工

---------------------


模块应为``rational``,类``Rational``,以

为例,遵循十进制[#PEP-327]模块的例子。类

创建方法应接受分子和可选的

分母作为参数,默认为1。分子和

分母 - 如果存在 - 必须是整数或十进制类型,或者是浮点数的

字符串表示。字符串

表示浮点数将转换为

rational而不转换为float以保持

数字的准确性。由于Python中的所有其他数值类型都是不可变的,因此
Rational对象将是不可变的。在内部,表示

将确保分子和分母具有最大的共同点数,并且分母的符号为正。

隐式构造

---------------------


Rationals将与整数类型。如果另一个操作数不是理性的,那么它将在操作之前转换为理性值

执行。


当合并时使用浮点类型 - 复数或浮点数 - 或者一个

十进制类型,结果将是一个TypeError。原因是

浮点数 - 包括复数 - 和小数是

已经不精确了。将它们转换为理性会给出一个

错误的印象,即操作的结果是精确的
。在这些类型之一中添加一个理性的正确方法是

在执行

操作之前明确地将理性转换为该类型。

操作

----------


``Rational``类应定义所有标准数学
$ b '''''Python可用性'''部分中提到的$ b操作。


Rational可以通过float(理性)转换为浮点数,并转换为

整数由int(理性)。 int(rational)只用分母做一个整数分元的分数。


如果Python 2.5中的对象没有__decimal__特性,

有理类型将提供一个decimal()方法,该方法返回当前上下文中自转换为小数的值



异常

----------


模块将定义并有时引发以下异常:


- DivisionByZero:除以零。


- 溢出错误:溢出尝试转换为浮点数。


- TypeError:尝试从非整数或

非字符串类型创建一个有理数,或尝试用浮点数,复数或小数执行一个操作




- ValueError:尝试从字符串值创建一个有理数,即

不是整数或浮动

点数的有效表示。


注意小数的初始值izer必须进行修改以处理

的理由。

未解决的问题

===========


- 是否应该将理性提升为非整数理性,默默生成

a浮点数,或者引发InvalidOperation异常?


实现

==============


目前有一个与Python一起发布的合理模块,并且

Python cvs源代码树中的第二个有理模块,它不是
分布式的。虽然其中一个可以选择并使其符合规范,但我希望有几个人能够自愿提供实施,以便做出最好的品种。 ''''实施可能是

选择。

参考资料

==========


... [#PEP-239]将一个Rational Type添加到Python,Craig,Zadka

http://www.python.org/peps/pep-0239.html

.. 。[#PEP-240]将Rational Literal添加到Python,Craig,Zadka

http://www.python.org/peps/pep-0240.html

... [#PEP-327]十进制数据类型,Batista

http:/ /www.python.org/peps/pep-0327.html

... [#PEP-239-implicit] PEP 240为Pytbon添加了一个新的文字类型,

PEP 239暗示整数除法将改为返回有效数据。

版权

==== =====


本文档已被置于公共领域。


...

局部变量:

模式:缩进文本

indent-tabs-mode:nil

句末 - 双空格:t

填充栏:70

结束:


-

Mike Meyer< mw * @ mired.org> http://www.mired.org/home/mwm/

独立的WWW / Perforce / FreeBSD / Unix顾问,电子邮件以获取更多信息。

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.org>
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.python 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.1000000000000001 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("%.2f" % 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 InvalidOperation 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.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

推荐答案

修订:1.4




最后修改:

Last-Modified:


日期:2003/09/22 04:51:50
Date: 2003/09/22 04:51:50


这篇关于修订后的Rational提案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆