bpo-26680: Incorporate is_integer in all built-in and standard library numeric types (GH-6121)

* bpo-26680: Adds support for int.is_integer() for compatibility with float.is_integer().

The int.is_integer() method always returns True.

* bpo-26680: Adds a test to ensure that False.is_integer() and True.is_integer() are always True.

* bpo-26680: Adds Real.is_integer() with a trivial implementation using conversion to int.

This default implementation is intended to reduce the workload for subclass
implementers. It is not robust in the presence of infinities or NaNs and
may have suboptimal performance for other types.

* bpo-26680: Adds Rational.is_integer which returns True if the denominator is one.

This implementation assumes the Rational is represented in it's
lowest form, as required by the class docstring.

* bpo-26680: Adds Integral.is_integer which always returns True.

* bpo-26680: Adds tests for Fraction.is_integer called as an instance method.

The tests for the Rational abstract base class use an unbound
method to sidestep the inability to directly instantiate Rational.
These tests check that everything works correct as an instance method.

* bpo-26680: Updates documentation for Real.is_integer and built-ins int and float.

The call x.is_integer() is now listed in the table of operations
which apply to all numeric types except complex, with a reference
to the full documentation for Real.is_integer().  Mention of
is_integer() has been removed from the section 'Additional Methods
on Float'.

The documentation for Real.is_integer() describes its purpose, and
mentions that it should be overridden for performance reasons, or
to handle special values like NaN.

* bpo-26680: Adds Decimal.is_integer to the Python and C implementations.

The C implementation of Decimal already implements and uses
mpd_isinteger internally, we just expose the existing function to
Python.

The Python implementation uses internal conversion to integer
using to_integral_value().

In both cases, the corresponding context methods are also
implemented.

Tests and documentation are included.

* bpo-26680: Updates the ACKS file.

* bpo-26680: NEWS entries for int, the numeric ABCs and Decimal.

Co-authored-by: Robert Smallshire <rob@sixty-north.com>
This commit is contained in:
Robert Smallshire 2020-10-01 18:30:08 +02:00 committed by GitHub
parent 256e54acdb
commit 58a7da9e12
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
19 changed files with 230 additions and 24 deletions

View file

@ -3164,6 +3164,12 @@ class Decimal(object):
"""Return True if self is a zero; otherwise return False."""
return not self._is_special and self._int == '0'
def is_integer(self):
"""Return True is self is finite and integral; otherwise False."""
if self._is_special:
return False
return self.to_integral_value(rounding=ROUND_FLOOR) == self
def _ln_exp_bound(self):
"""Compute a lower bound for the adjusted exponent of self.ln().
In other words, compute r such that self.ln() >= 10**r. Assumes
@ -4659,6 +4665,25 @@ class Context(object):
a = _convert_other(a, raiseit=True)
return a.is_zero()
def is_integer(self, a):
"""Return True if the operand is integral; otherwise return False.
>>> ExtendedContext.is_integer(Decimal('0'))
True
>>> ExtendedContext.is_integer(Decimal('2.50'))
False
>>> ExtendedContext.is_integer(Decimal('-0E+2'))
True
>>> ExtendedContext.is_integer(Decimal('-0.5'))
False
>>> ExtendedContext.is_integer(Decimal('NaN'))
False
>>> ExtendedContext.is_integer(10)
True
"""
a = _convert_other(a, raiseit=True)
return a.is_integer()
def ln(self, a):
"""Returns the natural (base e) logarithm of the operand.

View file

@ -148,7 +148,7 @@ class Real(Complex):
"""To Complex, Real adds the operations that work on real numbers.
In short, those are: a conversion to float, trunc(), divmod,
%, <, <=, >, and >=.
is_integer, %, <, <=, >, and >=.
Real also provides defaults for the derived operations.
"""
@ -242,6 +242,17 @@ class Real(Complex):
"""self <= other"""
raise NotImplementedError
def is_integer(self):
"""Return True if the Real is integral; otherwise return False.
This default implementation can be overridden in subclasses
for performance reasons or to deal with values such as NaN,
which would otherwise cause an exception to be raised.
"""
# Although __int__ is not defined at this level, the int
# constructor falls back to __trunc__, which we do have.
return self == int(self)
# Concrete implementations of Complex abstract methods.
def __complex__(self):
"""complex(self) == complex(float(self), 0)"""
@ -290,6 +301,10 @@ class Rational(Real):
"""
return self.numerator / self.denominator
def is_integer(self):
"""Return True if the Rational is integral; otherwise return False."""
return self.denominator == 1
class Integral(Rational):
"""Integral adds a conversion to int and the bit-string operations."""
@ -386,4 +401,8 @@ class Integral(Rational):
"""Integers have a denominator of 1."""
return 1
def is_integer(self):
"""Return True; all Integrals represent an integral value."""
return True
Integral.register(int)

View file

@ -2346,6 +2346,24 @@ bool2096 iszero sNaN -> 0
bool2097 iszero -sNaN -> 0
bool2098 iszero sNaN123 -> 0
bool2099 iszero -sNaN123 -> 0
bool2100 is_integer -1.0 -> 1
bool2101 is_integer 0.0 -> 1
bool2102 is_integer 1.0 -> 1
bool2103 is_integer 42 -> 1
bool2104 is_integer 1e2 -> 1
bool2105 is_integer 1.5 -> 0
bool2106 is_integer 1e-2 -> 0
bool2107 is_integer NaN -> 0
bool2109 is_integer -NaN -> 0
bool2110 is_integer NaN123 -> 0
bool2111 is_integer -NaN123 -> 0
bool2112 is_integer sNaN -> 0
bool2113 is_integer -sNaN -> 0
bool2114 is_integer sNaN123 -> 0
bool2115 is_integer -sNaN123 -> 0
bool2116 is_integer Infinity -> 0
bool2117 is_integer -Infinity -> 0
------------------------------------------------------------------------
-- The following tests (pwmx0 through pwmx440) are for the --

View file

@ -354,6 +354,11 @@ class BoolTest(unittest.TestCase):
self.assertIs(type(False.real), int)
self.assertIs(type(False.imag), int)
def test_always_is_integer(self):
# Issue #26680: Incorporating number.is_integer into bool
self.assertTrue(all(b.is_integer() for b in (False, True)))
def test_main():
support.run_unittest(BoolTest)

View file

@ -276,6 +276,7 @@ class IBMTestCases(unittest.TestCase):
'is_snan',
'is_subnormal',
'is_zero',
'is_integer',
'same_quantum')
def read_unlimited(self, v, context):
@ -2726,6 +2727,7 @@ class PythonAPItests(unittest.TestCase):
self.assertRaises(TypeError, D(1).is_snan, context=xc)
self.assertRaises(TypeError, D(1).is_signed, context=xc)
self.assertRaises(TypeError, D(1).is_zero, context=xc)
self.assertRaises(TypeError, D(1).is_integer, context=xc)
self.assertFalse(D("0.01").is_normal(context=xc))
self.assertTrue(D("0.01").is_subnormal(context=xc))
@ -3197,6 +3199,15 @@ class ContextAPItests(unittest.TestCase):
self.assertEqual(c.is_zero(10), d)
self.assertRaises(TypeError, c.is_zero, '10')
def test_is_integer(self):
Decimal = self.decimal.Decimal
Context = self.decimal.Context
c = Context()
b = c.is_integer(Decimal(10))
self.assertEqual(c.is_integer(10), b)
self.assertRaises(TypeError, c.is_integer, '10')
def test_ln(self):
Decimal = self.decimal.Decimal
Context = self.decimal.Context
@ -4360,6 +4371,19 @@ class Coverage(unittest.TestCase):
self.assertTrue(Decimal("-1").is_signed())
self.assertTrue(Decimal("0").is_zero())
self.assertTrue(Decimal("0").is_zero())
self.assertTrue(Decimal("-1").is_integer())
self.assertTrue(Decimal("0").is_integer())
self.assertTrue(Decimal("1").is_integer())
self.assertTrue(Decimal("42").is_integer())
self.assertTrue(Decimal("1e2").is_integer())
self.assertFalse(Decimal("1.5").is_integer())
self.assertFalse(Decimal("1e-2").is_integer())
self.assertFalse(Decimal("NaN").is_integer())
self.assertFalse(Decimal("-NaN").is_integer())
self.assertFalse(Decimal("sNaN").is_integer())
self.assertFalse(Decimal("-sNaN").is_integer())
self.assertFalse(Decimal("Inf").is_integer())
self.assertFalse(Decimal("-Inf").is_integer())
# Copy
with localcontext() as c:

View file

@ -724,6 +724,17 @@ class FractionTest(unittest.TestCase):
self.assertEqual(type(f.numerator), myint)
self.assertEqual(type(f.denominator), myint)
def test_is_integer(self):
# Issue #26680: Incorporating number.is_integer into Fraction
self.assertTrue(F(-1, 1).is_integer())
self.assertTrue(F(0, 1).is_integer())
self.assertTrue(F(1, 1).is_integer())
self.assertTrue(F(42, 1).is_integer())
self.assertTrue(F(2, 2).is_integer())
self.assertTrue(F(8, 4).is_integer())
self.assertFalse(F(1, 2).is_integer())
self.assertFalse(F(1, 3).is_integer())
self.assertFalse(F(2, 3).is_integer())
if __name__ == '__main__':
unittest.main()

View file

@ -1381,6 +1381,10 @@ class LongTest(unittest.TestCase):
self.assertEqual(type(numerator), int)
self.assertEqual(type(denominator), int)
def test_int_always_is_integer(self):
# Issue #26680: Incorporating number.is_integer into int
self.assertTrue(all(x.is_integer() for x in (-1, 0, 1, 42)))
if __name__ == "__main__":
unittest.main()

View file

@ -6,6 +6,7 @@ import math
import sys
import operator
from numbers import Real, Rational, Integral
from decimal import Decimal as D
from fractions import Fraction as F
@ -198,5 +199,35 @@ class ComparisonTest(unittest.TestCase):
self.assertRaises(TypeError, op, v, z)
class IsIntegerTest(unittest.TestCase):
def test_real_is_integer(self):
self.assertTrue(Real.is_integer(-1.0))
self.assertTrue(Real.is_integer(0.0))
self.assertTrue(Real.is_integer(1.0))
self.assertTrue(Real.is_integer(42.0))
self.assertFalse(Real.is_integer(-0.5))
self.assertFalse(Real.is_integer(4.2))
def test_rational_is_integer(self):
self.assertTrue(Rational.is_integer(F(-1, 1)))
self.assertTrue(Rational.is_integer(F(0, 1)))
self.assertTrue(Rational.is_integer(F(1, 1)))
self.assertTrue(Rational.is_integer(F(42, 1)))
self.assertTrue(Rational.is_integer(F(2, 2)))
self.assertTrue(Rational.is_integer(F(8, 4)))
self.assertFalse(Rational.is_integer(F(1, 2)))
self.assertFalse(Rational.is_integer(F(1, 3)))
self.assertFalse(Rational.is_integer(F(2, 3)))
def test_integral_is_integer(self):
self.assertTrue(Integral.is_integer(-1))
self.assertTrue(Integral.is_integer(0))
self.assertTrue(Integral.is_integer(1))
self.assertTrue(Integral.is_integer(1729))
if __name__ == '__main__':
unittest.main()