aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/Lib/test/test_float.py
diff options
context:
space:
mode:
Diffstat (limited to 'Lib/test/test_float.py')
-rw-r--r--Lib/test/test_float.py380
1 files changed, 143 insertions, 237 deletions
diff --git a/Lib/test/test_float.py b/Lib/test/test_float.py
index 42463713cdc..4d7bbbae170 100644
--- a/Lib/test/test_float.py
+++ b/Lib/test/test_float.py
@@ -1,13 +1,12 @@
import unittest, struct
import os
-from test import test_support
+import sys
+from test import support
import math
from math import isinf, isnan, copysign, ldexp
import operator
-import random
-import fractions
-import sys
+import random, fractions
INF = float("inf")
NAN = float("nan")
@@ -17,10 +16,6 @@ requires_getformat = unittest.skipUnless(have_getformat,
"requires __getformat__")
requires_setformat = unittest.skipUnless(hasattr(float, "__setformat__"),
"requires __setformat__")
-# decorator for skipping tests on non-IEEE 754 platforms
-requires_IEEE_754 = unittest.skipUnless(have_getformat and
- float.__getformat__("double").startswith("IEEE"),
- "test requires IEEE 754 doubles")
#locate file with float format test values
test_dir = os.path.dirname(__file__) or os.curdir
@@ -31,8 +26,8 @@ class GeneralFloatCases(unittest.TestCase):
def test_float(self):
self.assertEqual(float(3.14), 3.14)
self.assertEqual(float(314), 314.0)
- self.assertEqual(float(314L), 314.0)
self.assertEqual(float(" 3.14 "), 3.14)
+ self.assertEqual(float(b" 3.14 "), 3.14)
self.assertRaises(ValueError, float, " 0x3.1 ")
self.assertRaises(ValueError, float, " -0x3.p-1 ")
self.assertRaises(ValueError, float, " +0x3.p-1 ")
@@ -40,61 +35,35 @@ class GeneralFloatCases(unittest.TestCase):
self.assertRaises(ValueError, float, "+-3.14")
self.assertRaises(ValueError, float, "-+3.14")
self.assertRaises(ValueError, float, "--3.14")
+ self.assertRaises(ValueError, float, ".nan")
+ self.assertRaises(ValueError, float, "+.inf")
+ self.assertRaises(ValueError, float, ".")
+ self.assertRaises(ValueError, float, "-.")
+ self.assertRaises(ValueError, float, b"-")
+ self.assertRaises(TypeError, float, {})
+ # Lone surrogate
+ self.assertRaises(UnicodeEncodeError, float, '\uD8F0')
# check that we don't accept alternate exponent markers
self.assertRaises(ValueError, float, "-1.7d29")
self.assertRaises(ValueError, float, "3D-14")
- if test_support.have_unicode:
- self.assertEqual(float(unicode(" 3.14 ")), 3.14)
- self.assertEqual(float(unicode(" \u0663.\u0661\u0664 ",'raw-unicode-escape')), 3.14)
-
- # extra long strings should no longer be a problem
- # (in 2.6, long unicode inputs to float raised ValueError)
+ self.assertEqual(float(" \u0663.\u0661\u0664 "), 3.14)
+ self.assertEqual(float("\N{EM SPACE}3.14\N{EN SPACE}"), 3.14)
+ # extra long strings should not be a problem
+ float(b'.' + b'1'*1000)
float('.' + '1'*1000)
- float(unicode('.' + '1'*1000))
-
- def check_conversion_to_int(self, x):
- """Check that int(x) has the correct value and type, for a float x."""
- n = int(x)
- if x >= 0.0:
- # x >= 0 and n = int(x) ==> n <= x < n + 1
- self.assertLessEqual(n, x)
- self.assertLess(x, n + 1)
- else:
- # x < 0 and n = int(x) ==> n >= x > n - 1
- self.assertGreaterEqual(n, x)
- self.assertGreater(x, n - 1)
-
- # Result should be an int if within range, else a long.
- if -sys.maxint-1 <= n <= sys.maxint:
- self.assertEqual(type(n), int)
- else:
- self.assertEqual(type(n), long)
-
- # Double check.
- self.assertEqual(type(int(n)), type(n))
-
- def test_conversion_to_int(self):
- # Check that floats within the range of an int convert to type
- # int, not long. (issue #11144.)
- boundary = float(sys.maxint + 1)
- epsilon = 2**-sys.float_info.mant_dig * boundary
-
- # These 2 floats are either side of the positive int/long boundary on
- # both 32-bit and 64-bit systems.
- self.check_conversion_to_int(boundary - epsilon)
- self.check_conversion_to_int(boundary)
-
- # These floats are either side of the negative long/int boundary on
- # 64-bit systems...
- self.check_conversion_to_int(-boundary - 2*epsilon)
- self.check_conversion_to_int(-boundary)
-
- # ... and these ones are either side of the negative long/int
- # boundary on 32-bit systems.
- self.check_conversion_to_int(-boundary - 1.0)
- self.check_conversion_to_int(-boundary - 1.0 + 2*epsilon)
-
- @test_support.run_with_locale('LC_NUMERIC', 'fr_FR', 'de_DE')
+
+ def test_error_message(self):
+ testlist = ('\xbd', '123\xbd', ' 123 456 ')
+ for s in testlist:
+ try:
+ float(s)
+ except ValueError as e:
+ self.assertIn(s.strip(), e.args[0])
+ else:
+ self.fail("Expected int(%r) to raise a ValueError", s)
+
+
+ @support.run_with_locale('LC_NUMERIC', 'fr_FR', 'de_DE')
def test_float_with_comma(self):
# set locale to something that doesn't use '.' for the decimal point
# float must not accept the locale specific decimal point but
@@ -119,7 +88,7 @@ class GeneralFloatCases(unittest.TestCase):
self.assertRaises(ValueError, float, " -0x3.p-1 ")
self.assertRaises(ValueError, float, " +0x3.p-1 ")
self.assertEqual(float(" 25.e-1 "), 2.5)
- self.assertEqual(test_support.fcmp(float(" .25e-1 "), .025), 0)
+ self.assertEqual(support.fcmp(float(" .25e-1 "), .025), 0)
def test_floatconversion(self):
# Make sure that calls to __float__() work properly
@@ -152,16 +121,11 @@ class GeneralFloatCases(unittest.TestCase):
def __float__(self):
return float(str(self)) + 1
- class FooUnicode(unicode):
- def __float__(self):
- return float(unicode(self)) + 1
-
self.assertAlmostEqual(float(Foo0()), 42.)
self.assertAlmostEqual(float(Foo1()), 42.)
self.assertAlmostEqual(float(Foo2()), 42.)
self.assertAlmostEqual(float(Foo3(21)), 42.)
self.assertRaises(TypeError, float, Foo4(42))
- self.assertAlmostEqual(float(FooUnicode('8')), 9.)
self.assertAlmostEqual(float(FooStr('8')), 9.)
def test_is_integer(self):
@@ -203,13 +167,38 @@ class GeneralFloatCases(unittest.TestCase):
self.assertRaises(OverflowError, float('-inf').as_integer_ratio)
self.assertRaises(ValueError, float('nan').as_integer_ratio)
+ def test_float_containment(self):
+ floats = (INF, -INF, 0.0, 1.0, NAN)
+ for f in floats:
+ self.assertIn(f, [f])
+ self.assertIn(f, (f,))
+ self.assertIn(f, {f})
+ self.assertIn(f, {f: None})
+ self.assertEqual([f].count(f), 1, "[].count('%r') != 1" % f)
+ self.assertIn(f, floats)
+
+ for f in floats:
+ # nonidentical containers, same type, same contents
+ self.assertTrue([f] == [f], "[%r] != [%r]" % (f, f))
+ self.assertTrue((f,) == (f,), "(%r,) != (%r,)" % (f, f))
+ self.assertTrue({f} == {f}, "{%r} != {%r}" % (f, f))
+ self.assertTrue({f : None} == {f: None}, "{%r : None} != "
+ "{%r : None}" % (f, f))
+
+ # identical containers
+ l, t, s, d = [f], (f,), {f}, {f: None}
+ self.assertTrue(l == l, "[%r] not equal to itself" % f)
+ self.assertTrue(t == t, "(%r,) not equal to itself" % f)
+ self.assertTrue(s == s, "{%r} not equal to itself" % f)
+ self.assertTrue(d == d, "{%r : None} not equal to itself" % f)
+
def assertEqualAndEqualSign(self, a, b):
# fail unless a == b and a and b have the same sign bit;
# the only difference from assertEqual is that this test
# distinguishes -0.0 and 0.0.
self.assertEqual((a, copysign(1.0, a)), (b, copysign(1.0, b)))
- @requires_IEEE_754
+ @support.requires_IEEE_754
def test_float_mod(self):
# Check behaviour of % operator for IEEE 754 special cases.
# In particular, check signs of zeros.
@@ -229,7 +218,7 @@ class GeneralFloatCases(unittest.TestCase):
self.assertEqualAndEqualSign(mod(1e-100, -1.0), -1.0)
self.assertEqualAndEqualSign(mod(1.0, -1.0), -0.0)
- @requires_IEEE_754
+ @support.requires_IEEE_754
def test_float_pow(self):
# test builtin pow and ** operator for IEEE 754 special cases.
# Special cases taken from section F.9.4.4 of the C99 specification
@@ -319,13 +308,14 @@ class GeneralFloatCases(unittest.TestCase):
self.assertEqualAndEqualSign(pow_op(INF, -0.0), 1.0)
self.assertEqualAndEqualSign(pow_op(NAN, -0.0), 1.0)
- # x**y raises ValueError for finite negative x and non-integral y
- self.assertRaises(ValueError, pow_op, -2.0, -0.5)
- self.assertRaises(ValueError, pow_op, -2.0, 0.5)
- self.assertRaises(ValueError, pow_op, -1.0, -0.5)
- self.assertRaises(ValueError, pow_op, -1.0, 0.5)
- self.assertRaises(ValueError, pow_op, -0.5, -0.5)
- self.assertRaises(ValueError, pow_op, -0.5, 0.5)
+ # x**y defers to complex pow for finite negative x and
+ # non-integral y.
+ self.assertEqual(type(pow_op(-2.0, -0.5)), complex)
+ self.assertEqual(type(pow_op(-2.0, 0.5)), complex)
+ self.assertEqual(type(pow_op(-1.0, -0.5)), complex)
+ self.assertEqual(type(pow_op(-1.0, 0.5)), complex)
+ self.assertEqual(type(pow_op(-0.5, -0.5)), complex)
+ self.assertEqual(type(pow_op(-0.5, 0.5)), complex)
# x**-INF is INF for abs(x) < 1
self.assertEqualAndEqualSign(pow_op(-0.5, -INF), INF)
@@ -404,13 +394,13 @@ class GeneralFloatCases(unittest.TestCase):
# check sign for results that underflow to 0
self.assertEqualAndEqualSign(pow_op(-2.0, -2000.0), 0.0)
- self.assertRaises(ValueError, pow_op, -2.0, -2000.5)
+ self.assertEqual(type(pow_op(-2.0, -2000.5)), complex)
self.assertEqualAndEqualSign(pow_op(-2.0, -2001.0), -0.0)
self.assertEqualAndEqualSign(pow_op(2.0, -2000.0), 0.0)
self.assertEqualAndEqualSign(pow_op(2.0, -2000.5), 0.0)
self.assertEqualAndEqualSign(pow_op(2.0, -2001.0), 0.0)
self.assertEqualAndEqualSign(pow_op(-0.5, 2000.0), 0.0)
- self.assertRaises(ValueError, pow_op, -0.5, 2000.5)
+ self.assertEqual(type(pow_op(-0.5, 2000.5)), complex)
self.assertEqualAndEqualSign(pow_op(-0.5, 2001.0), -0.0)
self.assertEqualAndEqualSign(pow_op(0.5, 2000.0), 0.0)
self.assertEqualAndEqualSign(pow_op(0.5, 2000.5), 0.0)
@@ -468,15 +458,15 @@ class FormatFunctionsTestCase(unittest.TestCase):
self.assertRaises(ValueError, float.__setformat__,
'chicken', 'unknown')
-BE_DOUBLE_INF = '\x7f\xf0\x00\x00\x00\x00\x00\x00'
-LE_DOUBLE_INF = ''.join(reversed(BE_DOUBLE_INF))
-BE_DOUBLE_NAN = '\x7f\xf8\x00\x00\x00\x00\x00\x00'
-LE_DOUBLE_NAN = ''.join(reversed(BE_DOUBLE_NAN))
+BE_DOUBLE_INF = b'\x7f\xf0\x00\x00\x00\x00\x00\x00'
+LE_DOUBLE_INF = bytes(reversed(BE_DOUBLE_INF))
+BE_DOUBLE_NAN = b'\x7f\xf8\x00\x00\x00\x00\x00\x00'
+LE_DOUBLE_NAN = bytes(reversed(BE_DOUBLE_NAN))
-BE_FLOAT_INF = '\x7f\x80\x00\x00'
-LE_FLOAT_INF = ''.join(reversed(BE_FLOAT_INF))
-BE_FLOAT_NAN = '\x7f\xc0\x00\x00'
-LE_FLOAT_NAN = ''.join(reversed(BE_FLOAT_NAN))
+BE_FLOAT_INF = b'\x7f\x80\x00\x00'
+LE_FLOAT_INF = bytes(reversed(BE_FLOAT_INF))
+BE_FLOAT_NAN = b'\x7f\xc0\x00\x00'
+LE_FLOAT_NAN = bytes(reversed(BE_FLOAT_NAN))
# on non-IEEE platforms, attempting to unpack a bit pattern
# representing an infinity or a NaN should raise an exception.
@@ -515,7 +505,7 @@ class UnknownFormatTestCase(unittest.TestCase):
class IEEEFormatTestCase(unittest.TestCase):
- @requires_IEEE_754
+ @support.requires_IEEE_754
def test_double_specials_do_unpack(self):
for fmt, data in [('>d', BE_DOUBLE_INF),
('>d', BE_DOUBLE_NAN),
@@ -523,7 +513,7 @@ class IEEEFormatTestCase(unittest.TestCase):
('<d', LE_DOUBLE_NAN)]:
struct.unpack(fmt, data)
- @requires_IEEE_754
+ @support.requires_IEEE_754
def test_float_specials_do_unpack(self):
for fmt, data in [('>f', BE_FLOAT_INF),
('>f', BE_FLOAT_NAN),
@@ -531,25 +521,7 @@ class IEEEFormatTestCase(unittest.TestCase):
('<f', LE_FLOAT_NAN)]:
struct.unpack(fmt, data)
- @requires_IEEE_754
- def test_negative_zero(self):
- def pos_pos():
- return 0.0, math.atan2(0.0, -1)
- def pos_neg():
- return 0.0, math.atan2(-0.0, -1)
- def neg_pos():
- return -0.0, math.atan2(0.0, -1)
- def neg_neg():
- return -0.0, math.atan2(-0.0, -1)
- self.assertEqual(pos_pos(), neg_pos())
- self.assertEqual(pos_neg(), neg_neg())
-
- @requires_IEEE_754
- def test_underflow_sign(self):
- # check that -1e-1000 gives -0.0, not 0.0
- self.assertEqual(math.atan2(-1e-1000, -1), math.atan2(-0.0, -1))
- self.assertEqual(math.atan2(float('-1e-1000'), -1),
- math.atan2(-0.0, -1))
+class FormatTestCase(unittest.TestCase):
def test_format(self):
# these should be rewritten to use both format(x, spec) and
@@ -598,18 +570,16 @@ class IEEEFormatTestCase(unittest.TestCase):
self.assertRaises(ValueError, format, 1e-100, format_spec)
self.assertRaises(ValueError, format, -1e-100, format_spec)
- # issue 3382: 'f' and 'F' with inf's and nan's
- self.assertEqual('{0:f}'.format(INF), 'inf')
- self.assertEqual('{0:F}'.format(INF), 'INF')
- self.assertEqual('{0:f}'.format(-INF), '-inf')
- self.assertEqual('{0:F}'.format(-INF), '-INF')
- self.assertEqual('{0:f}'.format(NAN), 'nan')
- self.assertEqual('{0:F}'.format(NAN), 'NAN')
+ # issue 3382
+ self.assertEqual(format(NAN, 'f'), 'nan')
+ self.assertEqual(format(NAN, 'F'), 'NAN')
+ self.assertEqual(format(INF, 'f'), 'inf')
+ self.assertEqual(format(INF, 'F'), 'INF')
- @requires_IEEE_754
+ @support.requires_IEEE_754
def test_format_testfile(self):
with open(format_testfile) as testfile:
- for line in open(format_testfile):
+ for line in testfile:
if line.startswith('--'):
continue
line = line.strip()
@@ -618,10 +588,8 @@ class IEEEFormatTestCase(unittest.TestCase):
lhs, rhs = map(str.strip, line.split('->'))
fmt, arg = lhs.split()
- arg = float(arg)
- self.assertEqual(fmt % arg, rhs)
- if not math.isnan(arg) and copysign(1.0, arg) > 0.0:
- self.assertEqual(fmt % -arg, '-' + rhs)
+ self.assertEqual(fmt % float(arg), rhs)
+ self.assertEqual(fmt % -float(arg), '-' + rhs)
def test_issue5864(self):
self.assertEqual(format(123.456, '.4'), '123.5')
@@ -688,33 +656,17 @@ class ReprTestCase(unittest.TestCase):
negs = '-'+s
self.assertEqual(s, repr(float(s)))
self.assertEqual(negs, repr(float(negs)))
+ # Since Python 3.2, repr and str are identical
+ self.assertEqual(repr(float(s)), str(float(s)))
+ self.assertEqual(repr(float(negs)), str(float(negs)))
-
-@requires_IEEE_754
+@support.requires_IEEE_754
class RoundTestCase(unittest.TestCase):
- def test_second_argument_type(self):
- # any type with an __index__ method should be permitted as
- # a second argument
- self.assertAlmostEqual(round(12.34, True), 12.3)
-
- class MyIndex(object):
- def __index__(self): return 4
- self.assertAlmostEqual(round(-0.123456, MyIndex()), -0.1235)
- # but floats should be illegal
- self.assertRaises(TypeError, round, 3.14159, 2.0)
def test_inf_nan(self):
- # rounding an infinity or nan returns the same number;
- # (in py3k, rounding an infinity or nan raises an error,
- # since the result can't be represented as a long).
- self.assertEqual(round(INF), INF)
- self.assertEqual(round(-INF), -INF)
- self.assertTrue(math.isnan(round(NAN)))
- for n in range(-5, 5):
- self.assertEqual(round(INF, n), INF)
- self.assertEqual(round(-INF, n), -INF)
- self.assertTrue(math.isnan(round(NAN, n)))
-
+ self.assertRaises(OverflowError, round, INF)
+ self.assertRaises(OverflowError, round, -INF)
+ self.assertRaises(ValueError, round, NAN)
self.assertRaises(TypeError, round, INF, 0.0)
self.assertRaises(TypeError, round, -INF, 1.0)
self.assertRaises(TypeError, round, NAN, "ceci n'est pas un integer")
@@ -744,103 +696,56 @@ class RoundTestCase(unittest.TestCase):
self.assertRaises(OverflowError, round, -1.7e308, -308)
@unittest.skipUnless(getattr(sys, 'float_repr_style', '') == 'short',
- "test applies only when using short float repr style")
+ "applies only when using short float repr style")
def test_previous_round_bugs(self):
# particular cases that have occurred in bug reports
self.assertEqual(round(562949953421312.5, 1),
562949953421312.5)
self.assertEqual(round(56294995342131.5, 3),
56294995342131.5)
-
- @unittest.skipUnless(getattr(sys, 'float_repr_style', '') == 'short',
- "test applies only when using short float repr style")
- def test_halfway_cases(self):
- # Halfway cases need special attention, since the current
- # implementation has to deal with them specially. Note that
- # 2.x rounds halfway values up (i.e., away from zero) while
- # 3.x does round-half-to-even.
- self.assertAlmostEqual(round(0.125, 2), 0.13)
- self.assertAlmostEqual(round(0.375, 2), 0.38)
- self.assertAlmostEqual(round(0.625, 2), 0.63)
- self.assertAlmostEqual(round(0.875, 2), 0.88)
- self.assertAlmostEqual(round(-0.125, 2), -0.13)
- self.assertAlmostEqual(round(-0.375, 2), -0.38)
- self.assertAlmostEqual(round(-0.625, 2), -0.63)
- self.assertAlmostEqual(round(-0.875, 2), -0.88)
-
- self.assertAlmostEqual(round(0.25, 1), 0.3)
- self.assertAlmostEqual(round(0.75, 1), 0.8)
- self.assertAlmostEqual(round(-0.25, 1), -0.3)
- self.assertAlmostEqual(round(-0.75, 1), -0.8)
-
- self.assertEqual(round(-6.5, 0), -7.0)
- self.assertEqual(round(-5.5, 0), -6.0)
- self.assertEqual(round(-1.5, 0), -2.0)
- self.assertEqual(round(-0.5, 0), -1.0)
- self.assertEqual(round(0.5, 0), 1.0)
- self.assertEqual(round(1.5, 0), 2.0)
- self.assertEqual(round(2.5, 0), 3.0)
- self.assertEqual(round(3.5, 0), 4.0)
- self.assertEqual(round(4.5, 0), 5.0)
- self.assertEqual(round(5.5, 0), 6.0)
- self.assertEqual(round(6.5, 0), 7.0)
-
- # same but without an explicit second argument; in 3.x these
- # will give integers
- self.assertEqual(round(-6.5), -7.0)
- self.assertEqual(round(-5.5), -6.0)
- self.assertEqual(round(-1.5), -2.0)
- self.assertEqual(round(-0.5), -1.0)
- self.assertEqual(round(0.5), 1.0)
- self.assertEqual(round(1.5), 2.0)
- self.assertEqual(round(2.5), 3.0)
- self.assertEqual(round(3.5), 4.0)
- self.assertEqual(round(4.5), 5.0)
- self.assertEqual(round(5.5), 6.0)
- self.assertEqual(round(6.5), 7.0)
-
- self.assertEqual(round(-25.0, -1), -30.0)
- self.assertEqual(round(-15.0, -1), -20.0)
- self.assertEqual(round(-5.0, -1), -10.0)
- self.assertEqual(round(5.0, -1), 10.0)
- self.assertEqual(round(15.0, -1), 20.0)
- self.assertEqual(round(25.0, -1), 30.0)
+ # round-half-even
+ self.assertEqual(round(25.0, -1), 20.0)
self.assertEqual(round(35.0, -1), 40.0)
- self.assertEqual(round(45.0, -1), 50.0)
+ self.assertEqual(round(45.0, -1), 40.0)
self.assertEqual(round(55.0, -1), 60.0)
- self.assertEqual(round(65.0, -1), 70.0)
+ self.assertEqual(round(65.0, -1), 60.0)
self.assertEqual(round(75.0, -1), 80.0)
- self.assertEqual(round(85.0, -1), 90.0)
+ self.assertEqual(round(85.0, -1), 80.0)
self.assertEqual(round(95.0, -1), 100.0)
- self.assertEqual(round(12325.0, -1), 12330.0)
-
- self.assertEqual(round(350.0, -2), 400.0)
- self.assertEqual(round(450.0, -2), 500.0)
-
- self.assertAlmostEqual(round(0.5e21, -21), 1e21)
- self.assertAlmostEqual(round(1.5e21, -21), 2e21)
- self.assertAlmostEqual(round(2.5e21, -21), 3e21)
- self.assertAlmostEqual(round(5.5e21, -21), 6e21)
- self.assertAlmostEqual(round(8.5e21, -21), 9e21)
-
- self.assertAlmostEqual(round(-1.5e22, -22), -2e22)
- self.assertAlmostEqual(round(-0.5e22, -22), -1e22)
- self.assertAlmostEqual(round(0.5e22, -22), 1e22)
- self.assertAlmostEqual(round(1.5e22, -22), 2e22)
+ @unittest.skipUnless(getattr(sys, 'float_repr_style', '') == 'short',
+ "applies only when using short float repr style")
+ def test_matches_float_format(self):
+ # round should give the same results as float formatting
+ for i in range(500):
+ x = i/1000.
+ self.assertEqual(float(format(x, '.0f')), round(x, 0))
+ self.assertEqual(float(format(x, '.1f')), round(x, 1))
+ self.assertEqual(float(format(x, '.2f')), round(x, 2))
+ self.assertEqual(float(format(x, '.3f')), round(x, 3))
+
+ for i in range(5, 5000, 10):
+ x = i/1000.
+ self.assertEqual(float(format(x, '.0f')), round(x, 0))
+ self.assertEqual(float(format(x, '.1f')), round(x, 1))
+ self.assertEqual(float(format(x, '.2f')), round(x, 2))
+ self.assertEqual(float(format(x, '.3f')), round(x, 3))
+
+ for i in range(500):
+ x = random.random()
+ self.assertEqual(float(format(x, '.0f')), round(x, 0))
+ self.assertEqual(float(format(x, '.1f')), round(x, 1))
+ self.assertEqual(float(format(x, '.2f')), round(x, 2))
+ self.assertEqual(float(format(x, '.3f')), round(x, 3))
- @requires_IEEE_754
def test_format_specials(self):
# Test formatting of nans and infs.
def test(fmt, value, expected):
# Test with both % and format().
self.assertEqual(fmt % value, expected, fmt)
- if not '#' in fmt:
- # Until issue 7094 is implemented, format() for floats doesn't
- # support '#' formatting
- fmt = fmt[1:] # strip off the %
- self.assertEqual(format(value, fmt), expected, fmt)
+ fmt = fmt[1:] # strip off the %
+ self.assertEqual(format(value, fmt), expected, fmt)
for fmt in ['%e', '%f', '%g', '%.0e', '%.6f', '%.20g',
'%#e', '%#f', '%#g', '%#.20e', '%#.15f', '%#.3g']:
@@ -907,6 +812,11 @@ class InfNanTest(unittest.TestCase):
self.assertRaises(ValueError, float, "-INFI")
self.assertRaises(ValueError, float, "infinitys")
+ self.assertRaises(ValueError, float, "++Inf")
+ self.assertRaises(ValueError, float, "-+inf")
+ self.assertRaises(ValueError, float, "+-infinity")
+ self.assertRaises(ValueError, float, "--Infinity")
+
def test_inf_as_str(self):
self.assertEqual(repr(1e300 * 1e300), "inf")
self.assertEqual(repr(-1e300 * 1e300), "-inf")
@@ -938,6 +848,11 @@ class InfNanTest(unittest.TestCase):
self.assertRaises(ValueError, float, "+na")
self.assertRaises(ValueError, float, "-na")
+ self.assertRaises(ValueError, float, "++nan")
+ self.assertRaises(ValueError, float, "-+NAN")
+ self.assertRaises(ValueError, float, "+-NaN")
+ self.assertRaises(ValueError, float, "--nAn")
+
def test_nan_as_str(self):
self.assertEqual(repr(1e300 * 1e300 * 0), "nan")
self.assertEqual(repr(-1e300 * 1e300 * 0), "nan")
@@ -955,15 +870,6 @@ class InfNanTest(unittest.TestCase):
self.assertFalse(NAN.is_inf())
self.assertFalse((0.).is_inf())
- def test_hash_inf(self):
- # the actual values here should be regarded as an
- # implementation detail, but they need to be
- # identical to those used in the Decimal module.
- self.assertEqual(hash(float('inf')), 314159)
- self.assertEqual(hash(float('-inf')), -271828)
- self.assertEqual(hash(float('nan')), 0)
-
-
fromHex = float.fromhex
toHex = float.hex
class HexFloatTestCase(unittest.TestCase):
@@ -1035,10 +941,10 @@ class HexFloatTestCase(unittest.TestCase):
'0x.p0', # no hex digits before or after point
'0x1,p0', # wrong decimal point character
'0x1pa',
- u'0x1p\uff10', # fullwidth Unicode digits
- u'\uff10x1p0',
- u'0x\uff11p0',
- u'0x1.\uff10p0',
+ '0x1p\uff10', # fullwidth Unicode digits
+ '\uff10x1p0',
+ '0x\uff11p0',
+ '0x1.\uff10p0',
'0x1p0 \n 0x2p0',
'0x1p0\0 0x1p0', # embedded null byte is not end of string
]
@@ -1126,7 +1032,6 @@ class HexFloatTestCase(unittest.TestCase):
self.identical(fromHex('+0x1p0'), 1.0)
self.identical(fromHex('0x01p0'), 1.0)
self.identical(fromHex('0x1p00'), 1.0)
- self.identical(fromHex(u'0x1p0'), 1.0)
self.identical(fromHex(' 0x1p0 '), 1.0)
self.identical(fromHex('\n 0x1p0'), 1.0)
self.identical(fromHex('0x1p0 \t'), 1.0)
@@ -1374,7 +1279,7 @@ class HexFloatTestCase(unittest.TestCase):
# fromHex(toHex(x)) should exactly recover x, for any non-NaN float x.
import random
- for i in xrange(10000):
+ for i in range(10000):
e = random.randrange(-1200, 1200)
m = random.random()
s = random.choice([1.0, -1.0])
@@ -1387,11 +1292,12 @@ class HexFloatTestCase(unittest.TestCase):
def test_main():
- test_support.run_unittest(
+ support.run_unittest(
GeneralFloatCases,
FormatFunctionsTestCase,
UnknownFormatTestCase,
IEEEFormatTestCase,
+ FormatTestCase,
ReprTestCase,
RoundTestCase,
InfNanTest,