Python 3.8中新方法int.as_integer_ratio()的用途是什么

2024-03-29 07:35:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我查看了在Python3.8中实现的新特性,发现了一个新函数numerator, denominator = x.as_integer_ratio()。他们在文件中声明:

Return a pair of integers whose ratio is exactly equal to the original integer and with a positive denominator. The integer ratio of integers (whole numbers) is always the integer as the numerator and 1 as the denominator.

基本上是这个代码

x = 10
numerator, denominator = x.as_integer_ratio()

print(numerator)
print(denominator)

输出

10
1

我只是想知道拥有一个总是返回相同值和1的函数有什么意义?我还看到它以前在float上可用,这是有道理的


Tags: and文件oftheintegers函数声明is
3条回答

docs

这个较小的API扩展使得可以将分子、分母=x.写为_integer_ratio(),并使其跨多个数字类型工作

这种方法已经在几种类型上可用,例如float。现在,使用此方法的代码可以处理更多类型。把它归档在duck-typing下

考虑一个函数,该函数取一个参数并将其作为分数操作:

def foo(x):
    # ...
    num, denom = x.as_integer_ratio()
    # ...

在3.8之前,我们只能将其称为浮点数:

foo(3.14)

但现在我们可以用int来调用它,并获得可靠的行为:

foo(42)

改变的主要原因似乎是为了实现一致性,并为mypy键入,以便int可以是float的子类型

msg313780 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2018-03-13 21:25

Goal: make int() more interoperable with float by making a float/Decimal method also available on ints. This will let mypy treat ints as a subtype of floats.

See: https://mail.python.org/pipermail/python-dev/2018-March/152384.html

Open question: Is this also desired for fractions.Fraction and numbers.Rational?

深入到pipermail中,它似乎有助于通过分解等方式更改类型的域:

[Python-Dev] Symmetry arguments for API expansion Guido van Rossum guido at python.org Tue Mar 13 15:07:15 EDT 2018

Previous message (by thread): [Python-Dev] Symmetry arguments for API expansion
Next message (by thread): [Python-Dev] Symmetry arguments for API expansion
Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]

OK, please make it so.

On Tue, Mar 13, 2018 at 11:39 AM, Raymond Hettinger < raymond.hettinger at gmail.com> wrote:

On Mar 13, 2018, at 10:43 AM, Guido van Rossum wrote:

So let's make as_integer_ratio() the standard protocol for "how to make a Fraction out of a number that doesn't implement numbers.Rational". We already have two examples of this (float and Decimal) and perhaps numpy or the sometimes proposed fixed-width decimal type can benefit from it too. If this means we should add it to int, that's fine with me.

我希望看到这一结果

签名x.as_integer_ratio()->;(int,int)工作起来很愉快 具有输出很容易解释,分母也不受约束 二或十的幂。由于Python int是精确且无限制的,因此 不必担心范围或舍入问题

相比之下,math.frexp(float)——>;(float,int)有点痛苦,因为 仍然将您留在浮动域中,而不是让您分解 到更基本的类型。很高兴能有办法沿着链条向下移动 从…起ℚ, ℝ, 或ℂ 更基本的ℤ (当然,这只是因为 浮点数和复数的实现方式排除了精确的 非理性)

雷蒙德

见:

相关问题 更多 >