| 1 |
# Python test set -- math module |
| 2 |
# XXXX Should not do tests around zero only |
| 3 |
|
| 4 |
from test.support import verbose, requires_IEEE_754 |
| 5 |
from test import support |
| 6 |
import unittest |
| 7 |
import fractions |
| 8 |
import itertools |
| 9 |
import decimal |
| 10 |
import math |
| 11 |
import os |
| 12 |
import platform |
| 13 |
import random |
| 14 |
import struct |
| 15 |
import sys |
| 16 |
|
| 17 |
|
| 18 |
eps = 1E-05 |
| 19 |
NAN = float('nan') |
| 20 |
INF = float('inf') |
| 21 |
NINF = float('-inf') |
| 22 |
FLOAT_MAX = sys.float_info.max |
| 23 |
FLOAT_MIN = sys.float_info.min |
| 24 |
|
| 25 |
# detect evidence of double-rounding: fsum is not always correctly |
| 26 |
# rounded on machines that suffer from double rounding. |
| 27 |
x, y = 1e16, 2.9999 # use temporary values to defeat peephole optimizer |
| 28 |
HAVE_DOUBLE_ROUNDING = (x + y == 1e16 + 4) |
| 29 |
|
| 30 |
# locate file with test values |
| 31 |
if __name__ == '__main__': |
| 32 |
file = sys.argv[0] |
| 33 |
else: |
| 34 |
file = __file__ |
| 35 |
test_dir = os.path.dirname(file) or os.curdir |
| 36 |
math_testcases = os.path.join(test_dir, 'mathdata', 'math_testcases.txt') |
| 37 |
test_file = os.path.join(test_dir, 'mathdata', 'cmath_testcases.txt') |
| 38 |
|
| 39 |
|
| 40 |
def to_ulps(x): |
| 41 |
"""Convert a non-NaN float x to an integer, in such a way that |
| 42 |
adjacent floats are converted to adjacent integers. Then |
| 43 |
abs(ulps(x) - ulps(y)) gives the difference in ulps between two |
| 44 |
floats. |
| 45 |
|
| 46 |
The results from this function will only make sense on platforms |
| 47 |
where native doubles are represented in IEEE 754 binary64 format. |
| 48 |
|
| 49 |
Note: 0.0 and -0.0 are converted to 0 and -1, respectively. |
| 50 |
""" |
| 51 |
n = struct.unpack('<q', struct.pack('<d', x))[0] |
| 52 |
if n < 0: |
| 53 |
n = ~(n+2**63) |
| 54 |
return n |
| 55 |
|
| 56 |
|
| 57 |
# Here's a pure Python version of the math.factorial algorithm, for |
| 58 |
# documentation and comparison purposes. |
| 59 |
# |
| 60 |
# Formula: |
| 61 |
# |
| 62 |
# factorial(n) = factorial_odd_part(n) << (n - count_set_bits(n)) |
| 63 |
# |
| 64 |
# where |
| 65 |
# |
| 66 |
# factorial_odd_part(n) = product_{i >= 0} product_{0 < j <= n >> i; j odd} j |
| 67 |
# |
| 68 |
# The outer product above is an infinite product, but once i >= n.bit_length, |
| 69 |
# (n >> i) < 1 and the corresponding term of the product is empty. So only the |
| 70 |
# finitely many terms for 0 <= i < n.bit_length() contribute anything. |
| 71 |
# |
| 72 |
# We iterate downwards from i == n.bit_length() - 1 to i == 0. The inner |
| 73 |
# product in the formula above starts at 1 for i == n.bit_length(); for each i |
| 74 |
# < n.bit_length() we get the inner product for i from that for i + 1 by |
| 75 |
# multiplying by all j in {n >> i+1 < j <= n >> i; j odd}. In Python terms, |
| 76 |
# this set is range((n >> i+1) + 1 | 1, (n >> i) + 1 | 1, 2). |
| 77 |
|
| 78 |
def count_set_bits(n): |
| 79 |
"""Number of '1' bits in binary expansion of a nonnnegative integer.""" |
| 80 |
return 1 + count_set_bits(n & n - 1) if n else 0 |
| 81 |
|
| 82 |
def partial_product(start, stop): |
| 83 |
"""Product of integers in range(start, stop, 2), computed recursively. |
| 84 |
start and stop should both be odd, with start <= stop. |
| 85 |
|
| 86 |
""" |
| 87 |
numfactors = (stop - start) >> 1 |
| 88 |
if not numfactors: |
| 89 |
return 1 |
| 90 |
elif numfactors == 1: |
| 91 |
return start |
| 92 |
else: |
| 93 |
mid = (start + numfactors) | 1 |
| 94 |
return partial_product(start, mid) * partial_product(mid, stop) |
| 95 |
|
| 96 |
def py_factorial(n): |
| 97 |
"""Factorial of nonnegative integer n, via "Binary Split Factorial Formula" |
| 98 |
described at http://www.luschny.de/math/factorial/binarysplitfact.html |
| 99 |
|
| 100 |
""" |
| 101 |
inner = outer = 1 |
| 102 |
for i in reversed(range(n.bit_length())): |
| 103 |
inner *= partial_product((n >> i + 1) + 1 | 1, (n >> i) + 1 | 1) |
| 104 |
outer *= inner |
| 105 |
return outer << (n - count_set_bits(n)) |
| 106 |
|
| 107 |
def ulp_abs_check(expected, got, ulp_tol, abs_tol): |
| 108 |
"""Given finite floats `expected` and `got`, check that they're |
| 109 |
approximately equal to within the given number of ulps or the |
| 110 |
given absolute tolerance, whichever is bigger. |
| 111 |
|
| 112 |
Returns None on success and an error message on failure. |
| 113 |
""" |
| 114 |
ulp_error = abs(to_ulps(expected) - to_ulps(got)) |
| 115 |
abs_error = abs(expected - got) |
| 116 |
|
| 117 |
# Succeed if either abs_error <= abs_tol or ulp_error <= ulp_tol. |
| 118 |
if abs_error <= abs_tol or ulp_error <= ulp_tol: |
| 119 |
return None |
| 120 |
else: |
| 121 |
fmt = ("error = {:.3g} ({:d} ulps); " |
| 122 |
"permitted error = {:.3g} or {:d} ulps") |
| 123 |
return fmt.format(abs_error, ulp_error, abs_tol, ulp_tol) |
| 124 |
|
| 125 |
def parse_mtestfile(fname): |
| 126 |
"""Parse a file with test values |
| 127 |
|
| 128 |
-- starts a comment |
| 129 |
blank lines, or lines containing only a comment, are ignored |
| 130 |
other lines are expected to have the form |
| 131 |
id fn arg -> expected [flag]* |
| 132 |
|
| 133 |
""" |
| 134 |
with open(fname, encoding="utf-8") as fp: |
| 135 |
for line in fp: |
| 136 |
# strip comments, and skip blank lines |
| 137 |
if '--' in line: |
| 138 |
line = line[:line.index('--')] |
| 139 |
if not line.strip(): |
| 140 |
continue |
| 141 |
|
| 142 |
lhs, rhs = line.split('->') |
| 143 |
id, fn, arg = lhs.split() |
| 144 |
rhs_pieces = rhs.split() |
| 145 |
exp = rhs_pieces[0] |
| 146 |
flags = rhs_pieces[1:] |
| 147 |
|
| 148 |
yield (id, fn, float(arg), float(exp), flags) |
| 149 |
|
| 150 |
|
| 151 |
def parse_testfile(fname): |
| 152 |
"""Parse a file with test values |
| 153 |
|
| 154 |
Empty lines or lines starting with -- are ignored |
| 155 |
yields id, fn, arg_real, arg_imag, exp_real, exp_imag |
| 156 |
""" |
| 157 |
with open(fname, encoding="utf-8") as fp: |
| 158 |
for line in fp: |
| 159 |
# skip comment lines and blank lines |
| 160 |
if line.startswith('--') or not line.strip(): |
| 161 |
continue |
| 162 |
|
| 163 |
lhs, rhs = line.split('->') |
| 164 |
id, fn, arg_real, arg_imag = lhs.split() |
| 165 |
rhs_pieces = rhs.split() |
| 166 |
exp_real, exp_imag = rhs_pieces[0], rhs_pieces[1] |
| 167 |
flags = rhs_pieces[2:] |
| 168 |
|
| 169 |
yield (id, fn, |
| 170 |
float(arg_real), float(arg_imag), |
| 171 |
float(exp_real), float(exp_imag), |
| 172 |
flags) |
| 173 |
|
| 174 |
|
| 175 |
def result_check(expected, got, ulp_tol=5, abs_tol=0.0): |
| 176 |
# Common logic of MathTests.(ftest, test_testcases, test_mtestcases) |
| 177 |
"""Compare arguments expected and got, as floats, if either |
| 178 |
is a float, using a tolerance expressed in multiples of |
| 179 |
ulp(expected) or absolutely (if given and greater). |
| 180 |
|
| 181 |
As a convenience, when neither argument is a float, and for |
| 182 |
non-finite floats, exact equality is demanded. Also, nan==nan |
| 183 |
as far as this function is concerned. |
| 184 |
|
| 185 |
Returns None on success and an error message on failure. |
| 186 |
""" |
| 187 |
|
| 188 |
# Check exactly equal (applies also to strings representing exceptions) |
| 189 |
if got == expected: |
| 190 |
if not got and not expected: |
| 191 |
if math.copysign(1, got) != math.copysign(1, expected): |
| 192 |
return f"expected {expected}, got {got} (zero has wrong sign)" |
| 193 |
return None |
| 194 |
|
| 195 |
failure = "not equal" |
| 196 |
|
| 197 |
# Turn mixed float and int comparison (e.g. floor()) to all-float |
| 198 |
if isinstance(expected, float) and isinstance(got, int): |
| 199 |
got = float(got) |
| 200 |
elif isinstance(got, float) and isinstance(expected, int): |
| 201 |
expected = float(expected) |
| 202 |
|
| 203 |
if isinstance(expected, float) and isinstance(got, float): |
| 204 |
if math.isnan(expected) and math.isnan(got): |
| 205 |
# Pass, since both nan |
| 206 |
failure = None |
| 207 |
elif math.isinf(expected) or math.isinf(got): |
| 208 |
# We already know they're not equal, drop through to failure |
| 209 |
pass |
| 210 |
else: |
| 211 |
# Both are finite floats (now). Are they close enough? |
| 212 |
failure = ulp_abs_check(expected, got, ulp_tol, abs_tol) |
| 213 |
|
| 214 |
# arguments are not equal, and if numeric, are too far apart |
| 215 |
if failure is not None: |
| 216 |
fail_fmt = "expected {!r}, got {!r}" |
| 217 |
fail_msg = fail_fmt.format(expected, got) |
| 218 |
fail_msg += ' ({})'.format(failure) |
| 219 |
return fail_msg |
| 220 |
else: |
| 221 |
return None |
| 222 |
|
| 223 |
class FloatLike: |
| 224 |
def __init__(self, value): |
| 225 |
self.value = value |
| 226 |
|
| 227 |
def __float__(self): |
| 228 |
return self.value |
| 229 |
|
| 230 |
class IntSubclass(int): |
| 231 |
pass |
| 232 |
|
| 233 |
# Class providing an __index__ method. |
| 234 |
class MyIndexable(object): |
| 235 |
def __init__(self, value): |
| 236 |
self.value = value |
| 237 |
|
| 238 |
def __index__(self): |
| 239 |
return self.value |
| 240 |
|
| 241 |
class BadDescr: |
| 242 |
def __get__(self, obj, objtype=None): |
| 243 |
raise ValueError |
| 244 |
|
| 245 |
class MathTests(unittest.TestCase): |
| 246 |
|
| 247 |
def ftest(self, name, got, expected, ulp_tol=5, abs_tol=0.0): |
| 248 |
"""Compare arguments expected and got, as floats, if either |
| 249 |
is a float, using a tolerance expressed in multiples of |
| 250 |
ulp(expected) or absolutely, whichever is greater. |
| 251 |
|
| 252 |
As a convenience, when neither argument is a float, and for |
| 253 |
non-finite floats, exact equality is demanded. Also, nan==nan |
| 254 |
in this function. |
| 255 |
""" |
| 256 |
failure = result_check(expected, got, ulp_tol, abs_tol) |
| 257 |
if failure is not None: |
| 258 |
self.fail("{}: {}".format(name, failure)) |
| 259 |
|
| 260 |
def testConstants(self): |
| 261 |
# Ref: Abramowitz & Stegun (Dover, 1965) |
| 262 |
self.ftest('pi', math.pi, 3.141592653589793238462643) |
| 263 |
self.ftest('e', math.e, 2.718281828459045235360287) |
| 264 |
self.assertEqual(math.tau, 2*math.pi) |
| 265 |
|
| 266 |
def testAcos(self): |
| 267 |
self.assertRaises(TypeError, math.acos) |
| 268 |
self.ftest('acos(-1)', math.acos(-1), math.pi) |
| 269 |
self.ftest('acos(0)', math.acos(0), math.pi/2) |
| 270 |
self.ftest('acos(1)', math.acos(1), 0) |
| 271 |
self.assertRaises(ValueError, math.acos, INF) |
| 272 |
self.assertRaises(ValueError, math.acos, NINF) |
| 273 |
self.assertRaises(ValueError, math.acos, 1 + eps) |
| 274 |
self.assertRaises(ValueError, math.acos, -1 - eps) |
| 275 |
self.assertTrue(math.isnan(math.acos(NAN))) |
| 276 |
|
| 277 |
def testAcosh(self): |
| 278 |
self.assertRaises(TypeError, math.acosh) |
| 279 |
self.ftest('acosh(1)', math.acosh(1), 0) |
| 280 |
self.ftest('acosh(2)', math.acosh(2), 1.3169578969248168) |
| 281 |
self.assertRaises(ValueError, math.acosh, 0) |
| 282 |
self.assertRaises(ValueError, math.acosh, -1) |
| 283 |
self.assertEqual(math.acosh(INF), INF) |
| 284 |
self.assertRaises(ValueError, math.acosh, NINF) |
| 285 |
self.assertTrue(math.isnan(math.acosh(NAN))) |
| 286 |
|
| 287 |
def testAsin(self): |
| 288 |
self.assertRaises(TypeError, math.asin) |
| 289 |
self.ftest('asin(-1)', math.asin(-1), -math.pi/2) |
| 290 |
self.ftest('asin(0)', math.asin(0), 0) |
| 291 |
self.ftest('asin(1)', math.asin(1), math.pi/2) |
| 292 |
self.assertRaises(ValueError, math.asin, INF) |
| 293 |
self.assertRaises(ValueError, math.asin, NINF) |
| 294 |
self.assertRaises(ValueError, math.asin, 1 + eps) |
| 295 |
self.assertRaises(ValueError, math.asin, -1 - eps) |
| 296 |
self.assertTrue(math.isnan(math.asin(NAN))) |
| 297 |
|
| 298 |
def testAsinh(self): |
| 299 |
self.assertRaises(TypeError, math.asinh) |
| 300 |
self.ftest('asinh(0)', math.asinh(0), 0) |
| 301 |
self.ftest('asinh(1)', math.asinh(1), 0.88137358701954305) |
| 302 |
self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305) |
| 303 |
self.assertEqual(math.asinh(INF), INF) |
| 304 |
self.assertEqual(math.asinh(NINF), NINF) |
| 305 |
self.assertTrue(math.isnan(math.asinh(NAN))) |
| 306 |
|
| 307 |
def testAtan(self): |
| 308 |
self.assertRaises(TypeError, math.atan) |
| 309 |
self.ftest('atan(-1)', math.atan(-1), -math.pi/4) |
| 310 |
self.ftest('atan(0)', math.atan(0), 0) |
| 311 |
self.ftest('atan(1)', math.atan(1), math.pi/4) |
| 312 |
self.ftest('atan(inf)', math.atan(INF), math.pi/2) |
| 313 |
self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2) |
| 314 |
self.assertTrue(math.isnan(math.atan(NAN))) |
| 315 |
|
| 316 |
def testAtanh(self): |
| 317 |
self.assertRaises(TypeError, math.atan) |
| 318 |
self.ftest('atanh(0)', math.atanh(0), 0) |
| 319 |
self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489) |
| 320 |
self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489) |
| 321 |
self.assertRaises(ValueError, math.atanh, 1) |
| 322 |
self.assertRaises(ValueError, math.atanh, -1) |
| 323 |
self.assertRaises(ValueError, math.atanh, INF) |
| 324 |
self.assertRaises(ValueError, math.atanh, NINF) |
| 325 |
self.assertTrue(math.isnan(math.atanh(NAN))) |
| 326 |
|
| 327 |
@unittest.skipIf(sys.platform.startswith("sunos"), |
| 328 |
"skipping, see gh-138573") |
| 329 |
def testAtan2(self): |
| 330 |
self.assertRaises(TypeError, math.atan2) |
| 331 |
self.ftest('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2) |
| 332 |
self.ftest('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4) |
| 333 |
self.ftest('atan2(0, 1)', math.atan2(0, 1), 0) |
| 334 |
self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4) |
| 335 |
self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2) |
| 336 |
self.ftest('atan2(1, -1)', math.atan2(1, -1), 3*math.pi/4) |
| 337 |
|
| 338 |
# math.atan2(0, x) |
| 339 |
self.ftest('atan2(0., -inf)', math.atan2(0., NINF), math.pi) |
| 340 |
self.ftest('atan2(0., -2.3)', math.atan2(0., -2.3), math.pi) |
| 341 |
self.ftest('atan2(0., -0.)', math.atan2(0., -0.), math.pi) |
| 342 |
self.assertEqual(math.atan2(0., 0.), 0.) |
| 343 |
self.assertEqual(math.atan2(0., 2.3), 0.) |
| 344 |
self.assertEqual(math.atan2(0., INF), 0.) |
| 345 |
self.assertTrue(math.isnan(math.atan2(0., NAN))) |
| 346 |
# math.atan2(-0, x) |
| 347 |
self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi) |
| 348 |
self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi) |
| 349 |
self.ftest('atan2(-0., -0.)', math.atan2(-0., -0.), -math.pi) |
| 350 |
self.assertEqual(math.atan2(-0., 0.), -0.) |
| 351 |
self.assertEqual(math.atan2(-0., 2.3), -0.) |
| 352 |
self.assertEqual(math.atan2(-0., INF), -0.) |
| 353 |
self.assertTrue(math.isnan(math.atan2(-0., NAN))) |
| 354 |
# math.atan2(INF, x) |
| 355 |
self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4) |
| 356 |
self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2) |
| 357 |
self.ftest('atan2(inf, -0.)', math.atan2(INF, -0.0), math.pi/2) |
| 358 |
self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2) |
| 359 |
self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2) |
| 360 |
self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4) |
| 361 |
self.assertTrue(math.isnan(math.atan2(INF, NAN))) |
| 362 |
# math.atan2(NINF, x) |
| 363 |
self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4) |
| 364 |
self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2) |
| 365 |
self.ftest('atan2(-inf, -0.)', math.atan2(NINF, -0.0), -math.pi/2) |
| 366 |
self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2) |
| 367 |
self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2) |
| 368 |
self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4) |
| 369 |
self.assertTrue(math.isnan(math.atan2(NINF, NAN))) |
| 370 |
# math.atan2(+finite, x) |
| 371 |
self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi) |
| 372 |
self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2) |
| 373 |
self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2) |
| 374 |
self.assertEqual(math.atan2(2.3, INF), 0.) |
| 375 |
self.assertTrue(math.isnan(math.atan2(2.3, NAN))) |
| 376 |
# math.atan2(-finite, x) |
| 377 |
self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi) |
| 378 |
self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2) |
| 379 |
self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2) |
| 380 |
self.assertEqual(math.atan2(-2.3, INF), -0.) |
| 381 |
self.assertTrue(math.isnan(math.atan2(-2.3, NAN))) |
| 382 |
# math.atan2(NAN, x) |
| 383 |
self.assertTrue(math.isnan(math.atan2(NAN, NINF))) |
| 384 |
self.assertTrue(math.isnan(math.atan2(NAN, -2.3))) |
| 385 |
self.assertTrue(math.isnan(math.atan2(NAN, -0.))) |
| 386 |
self.assertTrue(math.isnan(math.atan2(NAN, 0.))) |
| 387 |
self.assertTrue(math.isnan(math.atan2(NAN, 2.3))) |
| 388 |
self.assertTrue(math.isnan(math.atan2(NAN, INF))) |
| 389 |
self.assertTrue(math.isnan(math.atan2(NAN, NAN))) |
| 390 |
|
| 391 |
def testCbrt(self): |
| 392 |
self.assertRaises(TypeError, math.cbrt) |
| 393 |
self.ftest('cbrt(0)', math.cbrt(0), 0) |
| 394 |
self.ftest('cbrt(1)', math.cbrt(1), 1) |
| 395 |
self.ftest('cbrt(8)', math.cbrt(8), 2) |
| 396 |
self.ftest('cbrt(0.0)', math.cbrt(0.0), 0.0) |
| 397 |
self.ftest('cbrt(-0.0)', math.cbrt(-0.0), -0.0) |
| 398 |
self.ftest('cbrt(1.2)', math.cbrt(1.2), 1.062658569182611) |
| 399 |
self.ftest('cbrt(-2.6)', math.cbrt(-2.6), -1.375068867074141) |
| 400 |
self.ftest('cbrt(27)', math.cbrt(27), 3) |
| 401 |
self.ftest('cbrt(-1)', math.cbrt(-1), -1) |
| 402 |
self.ftest('cbrt(-27)', math.cbrt(-27), -3) |
| 403 |
self.assertEqual(math.cbrt(INF), INF) |
| 404 |
self.assertEqual(math.cbrt(NINF), NINF) |
| 405 |
self.assertTrue(math.isnan(math.cbrt(NAN))) |
| 406 |
|
| 407 |
def testCeil(self): |
| 408 |
self.assertRaises(TypeError, math.ceil) |
| 409 |
self.assertEqual(int, type(math.ceil(0.5))) |
| 410 |
self.assertEqual(math.ceil(0.5), 1) |
| 411 |
self.assertEqual(math.ceil(1.0), 1) |
| 412 |
self.assertEqual(math.ceil(1.5), 2) |
| 413 |
self.assertEqual(math.ceil(-0.5), 0) |
| 414 |
self.assertEqual(math.ceil(-1.0), -1) |
| 415 |
self.assertEqual(math.ceil(-1.5), -1) |
| 416 |
self.assertEqual(math.ceil(0.0), 0) |
| 417 |
self.assertEqual(math.ceil(-0.0), 0) |
| 418 |
#self.assertEqual(math.ceil(INF), INF) |
| 419 |
#self.assertEqual(math.ceil(NINF), NINF) |
| 420 |
#self.assertTrue(math.isnan(math.ceil(NAN))) |
| 421 |
|
| 422 |
class TestCeil: |
| 423 |
def __ceil__(self): |
| 424 |
return 42 |
| 425 |
class FloatCeil(float): |
| 426 |
def __ceil__(self): |
| 427 |
return 42 |
| 428 |
class TestNoCeil: |
| 429 |
pass |
| 430 |
class TestBadCeil: |
| 431 |
__ceil__ = BadDescr() |
| 432 |
self.assertEqual(math.ceil(TestCeil()), 42) |
| 433 |
self.assertEqual(math.ceil(FloatCeil()), 42) |
| 434 |
self.assertEqual(math.ceil(FloatLike(42.5)), 43) |
| 435 |
self.assertRaises(TypeError, math.ceil, TestNoCeil()) |
| 436 |
self.assertRaises(ValueError, math.ceil, TestBadCeil()) |
| 437 |
|
| 438 |
t = TestNoCeil() |
| 439 |
t.__ceil__ = lambda *args: args |
| 440 |
self.assertRaises(TypeError, math.ceil, t) |
| 441 |
self.assertRaises(TypeError, math.ceil, t, 0) |
| 442 |
|
| 443 |
self.assertEqual(math.ceil(FloatLike(+1.0)), +1.0) |
| 444 |
self.assertEqual(math.ceil(FloatLike(-1.0)), -1.0) |
| 445 |
|
| 446 |
@requires_IEEE_754 |
| 447 |
def testCopysign(self): |
| 448 |
self.assertEqual(math.copysign(1, 42), 1.0) |
| 449 |
self.assertEqual(math.copysign(0., 42), 0.0) |
| 450 |
self.assertEqual(math.copysign(1., -42), -1.0) |
| 451 |
self.assertEqual(math.copysign(3, 0.), 3.0) |
| 452 |
self.assertEqual(math.copysign(4., -0.), -4.0) |
| 453 |
|
| 454 |
self.assertRaises(TypeError, math.copysign) |
| 455 |
# copysign should let us distinguish signs of zeros |
| 456 |
self.assertEqual(math.copysign(1., 0.), 1.) |
| 457 |
self.assertEqual(math.copysign(1., -0.), -1.) |
| 458 |
self.assertEqual(math.copysign(INF, 0.), INF) |
| 459 |
self.assertEqual(math.copysign(INF, -0.), NINF) |
| 460 |
self.assertEqual(math.copysign(NINF, 0.), INF) |
| 461 |
self.assertEqual(math.copysign(NINF, -0.), NINF) |
| 462 |
# and of infinities |
| 463 |
self.assertEqual(math.copysign(1., INF), 1.) |
| 464 |
self.assertEqual(math.copysign(1., NINF), -1.) |
| 465 |
self.assertEqual(math.copysign(INF, INF), INF) |
| 466 |
self.assertEqual(math.copysign(INF, NINF), NINF) |
| 467 |
self.assertEqual(math.copysign(NINF, INF), INF) |
| 468 |
self.assertEqual(math.copysign(NINF, NINF), NINF) |
| 469 |
self.assertTrue(math.isnan(math.copysign(NAN, 1.))) |
| 470 |
self.assertTrue(math.isnan(math.copysign(NAN, INF))) |
| 471 |
self.assertTrue(math.isnan(math.copysign(NAN, NINF))) |
| 472 |
self.assertTrue(math.isnan(math.copysign(NAN, NAN))) |
| 473 |
# copysign(INF, NAN) may be INF or it may be NINF, since |
| 474 |
# we don't know whether the sign bit of NAN is set on any |
| 475 |
# given platform. |
| 476 |
self.assertTrue(math.isinf(math.copysign(INF, NAN))) |
| 477 |
# similarly, copysign(2., NAN) could be 2. or -2. |
| 478 |
self.assertEqual(abs(math.copysign(2., NAN)), 2.) |
| 479 |
|
| 480 |
def testCos(self): |
| 481 |
self.assertRaises(TypeError, math.cos) |
| 482 |
self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0, abs_tol=math.ulp(1)) |
| 483 |
self.ftest('cos(0)', math.cos(0), 1) |
| 484 |
self.ftest('cos(pi/2)', math.cos(math.pi/2), 0, abs_tol=math.ulp(1)) |
| 485 |
self.ftest('cos(pi)', math.cos(math.pi), -1) |
| 486 |
try: |
| 487 |
self.assertTrue(math.isnan(math.cos(INF))) |
| 488 |
self.assertTrue(math.isnan(math.cos(NINF))) |
| 489 |
except ValueError: |
| 490 |
self.assertRaises(ValueError, math.cos, INF) |
| 491 |
self.assertRaises(ValueError, math.cos, NINF) |
| 492 |
self.assertTrue(math.isnan(math.cos(NAN))) |
| 493 |
|
| 494 |
@unittest.skipIf(sys.platform == 'win32' and platform.machine() in ('ARM', 'ARM64'), |
| 495 |
"Windows UCRT is off by 2 ULP this test requires accuracy within 1 ULP") |
| 496 |
def testCosh(self): |
| 497 |
self.assertRaises(TypeError, math.cosh) |
| 498 |
self.ftest('cosh(0)', math.cosh(0), 1) |
| 499 |
self.ftest('cosh(2)-2*cosh(1)**2', math.cosh(2)-2*math.cosh(1)**2, -1) # Thanks to Lambert |
| 500 |
self.assertEqual(math.cosh(INF), INF) |
| 501 |
self.assertEqual(math.cosh(NINF), INF) |
| 502 |
self.assertTrue(math.isnan(math.cosh(NAN))) |
| 503 |
|
| 504 |
def testDegrees(self): |
| 505 |
self.assertRaises(TypeError, math.degrees) |
| 506 |
self.ftest('degrees(pi)', math.degrees(math.pi), 180.0) |
| 507 |
self.ftest('degrees(pi/2)', math.degrees(math.pi/2), 90.0) |
| 508 |
self.ftest('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0) |
| 509 |
self.ftest('degrees(0)', math.degrees(0), 0) |
| 510 |
|
| 511 |
def testExp(self): |
| 512 |
self.assertRaises(TypeError, math.exp) |
| 513 |
self.ftest('exp(-1)', math.exp(-1), 1/math.e) |
| 514 |
self.ftest('exp(0)', math.exp(0), 1) |
| 515 |
self.ftest('exp(1)', math.exp(1), math.e) |
| 516 |
self.assertEqual(math.exp(INF), INF) |
| 517 |
self.assertEqual(math.exp(NINF), 0.) |
| 518 |
self.assertTrue(math.isnan(math.exp(NAN))) |
| 519 |
self.assertRaises(OverflowError, math.exp, 1000000) |
| 520 |
|
| 521 |
def testExp2(self): |
| 522 |
self.assertRaises(TypeError, math.exp2) |
| 523 |
self.ftest('exp2(-1)', math.exp2(-1), 0.5) |
| 524 |
self.ftest('exp2(0)', math.exp2(0), 1) |
| 525 |
self.ftest('exp2(1)', math.exp2(1), 2) |
| 526 |
self.ftest('exp2(2.3)', math.exp2(2.3), 4.924577653379665) |
| 527 |
self.assertEqual(math.exp2(INF), INF) |
| 528 |
self.assertEqual(math.exp2(NINF), 0.) |
| 529 |
self.assertTrue(math.isnan(math.exp2(NAN))) |
| 530 |
self.assertRaises(OverflowError, math.exp2, 1000000) |
| 531 |
|
| 532 |
def testFabs(self): |
| 533 |
self.assertRaises(TypeError, math.fabs) |
| 534 |
self.ftest('fabs(-1)', math.fabs(-1), 1) |
| 535 |
self.ftest('fabs(0)', math.fabs(0), 0) |
| 536 |
self.ftest('fabs(1)', math.fabs(1), 1) |
| 537 |
|
| 538 |
def testFactorial(self): |
| 539 |
self.assertEqual(math.factorial(0), 1) |
| 540 |
total = 1 |
| 541 |
for i in range(1, 1000): |
| 542 |
total *= i |
| 543 |
self.assertEqual(math.factorial(i), total) |
| 544 |
self.assertEqual(math.factorial(i), py_factorial(i)) |
| 545 |
self.assertRaises(ValueError, math.factorial, -1) |
| 546 |
self.assertRaises(ValueError, math.factorial, -10**100) |
| 547 |
|
| 548 |
def testFactorialNonIntegers(self): |
| 549 |
self.assertRaises(TypeError, math.factorial, 5.0) |
| 550 |
self.assertRaises(TypeError, math.factorial, 5.2) |
| 551 |
self.assertRaises(TypeError, math.factorial, -1.0) |
| 552 |
self.assertRaises(TypeError, math.factorial, -1e100) |
| 553 |
self.assertRaises(TypeError, math.factorial, decimal.Decimal('5')) |
| 554 |
self.assertRaises(TypeError, math.factorial, decimal.Decimal('5.2')) |
| 555 |
self.assertRaises(TypeError, math.factorial, "5") |
| 556 |
|
| 557 |
# Other implementations may place different upper bounds. |
| 558 |
@support.cpython_only |
| 559 |
def testFactorialHugeInputs(self): |
| 560 |
# Currently raises OverflowError for inputs that are too large |
| 561 |
# to fit into a C long. |
| 562 |
self.assertRaises(OverflowError, math.factorial, 10**100) |
| 563 |
self.assertRaises(TypeError, math.factorial, 1e100) |
| 564 |
|
| 565 |
def testFloor(self): |
| 566 |
self.assertRaises(TypeError, math.floor) |
| 567 |
self.assertEqual(int, type(math.floor(0.5))) |
| 568 |
self.assertEqual(math.floor(0.5), 0) |
| 569 |
self.assertEqual(math.floor(1.0), 1) |
| 570 |
self.assertEqual(math.floor(1.5), 1) |
| 571 |
self.assertEqual(math.floor(-0.5), -1) |
| 572 |
self.assertEqual(math.floor(-1.0), -1) |
| 573 |
self.assertEqual(math.floor(-1.5), -2) |
| 574 |
#self.assertEqual(math.ceil(INF), INF) |
| 575 |
#self.assertEqual(math.ceil(NINF), NINF) |
| 576 |
#self.assertTrue(math.isnan(math.floor(NAN))) |
| 577 |
|
| 578 |
class TestFloorIsNone(float): |
| 579 |
__floor__ = None |
| 580 |
class TestFloor: |
| 581 |
def __floor__(self): |
| 582 |
return 42 |
| 583 |
class FloatFloor(float): |
| 584 |
def __floor__(self): |
| 585 |
return 42 |
| 586 |
class TestNoFloor: |
| 587 |
pass |
| 588 |
class TestBadFloor: |
| 589 |
__floor__ = BadDescr() |
| 590 |
self.assertEqual(math.floor(TestFloor()), 42) |
| 591 |
self.assertEqual(math.floor(FloatFloor()), 42) |
| 592 |
self.assertEqual(math.floor(FloatLike(41.9)), 41) |
| 593 |
self.assertRaises(TypeError, math.floor, TestNoFloor()) |
| 594 |
self.assertRaises(ValueError, math.floor, TestBadFloor()) |
| 595 |
self.assertRaises(TypeError, math.floor, TestFloorIsNone(3.5)) |
| 596 |
|
| 597 |
t = TestNoFloor() |
| 598 |
t.__floor__ = lambda *args: args |
| 599 |
self.assertRaises(TypeError, math.floor, t) |
| 600 |
self.assertRaises(TypeError, math.floor, t, 0) |
| 601 |
|
| 602 |
self.assertEqual(math.floor(FloatLike(+1.0)), +1.0) |
| 603 |
self.assertEqual(math.floor(FloatLike(-1.0)), -1.0) |
| 604 |
|
| 605 |
def testFmod(self): |
| 606 |
self.assertRaises(TypeError, math.fmod) |
| 607 |
self.ftest('fmod(10, 1)', math.fmod(10, 1), 0.0) |
| 608 |
self.ftest('fmod(10, 0.5)', math.fmod(10, 0.5), 0.0) |
| 609 |
self.ftest('fmod(10, 1.5)', math.fmod(10, 1.5), 1.0) |
| 610 |
self.ftest('fmod(-10, 1)', math.fmod(-10, 1), -0.0) |
| 611 |
self.ftest('fmod(-10, 0.5)', math.fmod(-10, 0.5), -0.0) |
| 612 |
self.ftest('fmod(-10, 1.5)', math.fmod(-10, 1.5), -1.0) |
| 613 |
self.assertTrue(math.isnan(math.fmod(NAN, 1.))) |
| 614 |
self.assertTrue(math.isnan(math.fmod(1., NAN))) |
| 615 |
self.assertTrue(math.isnan(math.fmod(NAN, NAN))) |
| 616 |
self.assertRaises(ValueError, math.fmod, 1., 0.) |
| 617 |
self.assertRaises(ValueError, math.fmod, INF, 1.) |
| 618 |
self.assertRaises(ValueError, math.fmod, NINF, 1.) |
| 619 |
self.assertRaises(ValueError, math.fmod, INF, 0.) |
| 620 |
self.assertEqual(math.fmod(3.0, INF), 3.0) |
| 621 |
self.assertEqual(math.fmod(-3.0, INF), -3.0) |
| 622 |
self.assertEqual(math.fmod(3.0, NINF), 3.0) |
| 623 |
self.assertEqual(math.fmod(-3.0, NINF), -3.0) |
| 624 |
self.assertEqual(math.fmod(0.0, 3.0), 0.0) |
| 625 |
self.assertEqual(math.fmod(0.0, NINF), 0.0) |
| 626 |
self.assertRaises(ValueError, math.fmod, INF, INF) |
| 627 |
|
| 628 |
def testFrexp(self): |
| 629 |
self.assertRaises(TypeError, math.frexp) |
| 630 |
|
| 631 |
def testfrexp(name, result, expected): |
| 632 |
(mant, exp), (emant, eexp) = result, expected |
| 633 |
if abs(mant-emant) > eps or exp != eexp: |
| 634 |
self.fail('%s returned %r, expected %r'%\ |
| 635 |
(name, result, expected)) |
| 636 |
|
| 637 |
testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1)) |
| 638 |
testfrexp('frexp(0)', math.frexp(0), (0, 0)) |
| 639 |
testfrexp('frexp(1)', math.frexp(1), (0.5, 1)) |
| 640 |
testfrexp('frexp(2)', math.frexp(2), (0.5, 2)) |
| 641 |
|
| 642 |
self.assertEqual(math.frexp(INF)[0], INF) |
| 643 |
self.assertEqual(math.frexp(NINF)[0], NINF) |
| 644 |
self.assertTrue(math.isnan(math.frexp(NAN)[0])) |
| 645 |
|
| 646 |
@requires_IEEE_754 |
| 647 |
@unittest.skipIf(HAVE_DOUBLE_ROUNDING, |
| 648 |
"fsum is not exact on machines with double rounding") |
| 649 |
def testFsum(self): |
| 650 |
# math.fsum relies on exact rounding for correct operation. |
| 651 |
# There's a known problem with IA32 floating-point that causes |
| 652 |
# inexact rounding in some situations, and will cause the |
| 653 |
# math.fsum tests below to fail; see issue #2937. On non IEEE |
| 654 |
# 754 platforms, and on IEEE 754 platforms that exhibit the |
| 655 |
# problem described in issue #2937, we simply skip the whole |
| 656 |
# test. |
| 657 |
|
| 658 |
# Python version of math.fsum, for comparison. Uses a |
| 659 |
# different algorithm based on frexp, ldexp and integer |
| 660 |
# arithmetic. |
| 661 |
from sys import float_info |
| 662 |
mant_dig = float_info.mant_dig |
| 663 |
etiny = float_info.min_exp - mant_dig |
| 664 |
|
| 665 |
def msum(iterable): |
| 666 |
"""Full precision summation. Compute sum(iterable) without any |
| 667 |
intermediate accumulation of error. Based on the 'lsum' function |
| 668 |
at https://code.activestate.com/recipes/393090-binary-floating-point-summation-accurate-to-full-p/ |
| 669 |
|
| 670 |
""" |
| 671 |
tmant, texp = 0, 0 |
| 672 |
for x in iterable: |
| 673 |
mant, exp = math.frexp(x) |
| 674 |
mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig |
| 675 |
if texp > exp: |
| 676 |
tmant <<= texp-exp |
| 677 |
texp = exp |
| 678 |
else: |
| 679 |
mant <<= exp-texp |
| 680 |
tmant += mant |
| 681 |
# Round tmant * 2**texp to a float. The original recipe |
| 682 |
# used float(str(tmant)) * 2.0**texp for this, but that's |
| 683 |
# a little unsafe because str -> float conversion can't be |
| 684 |
# relied upon to do correct rounding on all platforms. |
| 685 |
tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp) |
| 686 |
if tail > 0: |
| 687 |
h = 1 << (tail-1) |
| 688 |
tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1) |
| 689 |
texp += tail |
| 690 |
return math.ldexp(tmant, texp) |
| 691 |
|
| 692 |
test_values = [ |
| 693 |
([], 0.0), |
| 694 |
([0.0], 0.0), |
| 695 |
([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100), |
| 696 |
([1e100, 1.0, -1e100, 1e-100, 1e50, -1, -1e50], 1e-100), |
| 697 |
([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0), |
| 698 |
([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0), |
| 699 |
([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0), |
| 700 |
([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0), |
| 701 |
([1./n for n in range(1, 1001)], |
| 702 |
float.fromhex('0x1.df11f45f4e61ap+2')), |
| 703 |
([(-1.)**n/n for n in range(1, 1001)], |
| 704 |
float.fromhex('-0x1.62a2af1bd3624p-1')), |
| 705 |
([1e16, 1., 1e-16], 10000000000000002.0), |
| 706 |
([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0), |
| 707 |
# exercise code for resizing partials array |
| 708 |
([2.**n - 2.**(n+50) + 2.**(n+52) for n in range(-1074, 972, 2)] + |
| 709 |
[-2.**1022], |
| 710 |
float.fromhex('0x1.5555555555555p+970')), |
| 711 |
] |
| 712 |
|
| 713 |
# Telescoping sum, with exact differences (due to Sterbenz) |
| 714 |
terms = [1.7**i for i in range(1001)] |
| 715 |
test_values.append(( |
| 716 |
[terms[i+1] - terms[i] for i in range(1000)] + [-terms[1000]], |
| 717 |
-terms[0] |
| 718 |
)) |
| 719 |
|
| 720 |
for i, (vals, expected) in enumerate(test_values): |
| 721 |
try: |
| 722 |
actual = math.fsum(vals) |
| 723 |
except OverflowError: |
| 724 |
self.fail("test %d failed: got OverflowError, expected %r " |
| 725 |
"for math.fsum(%.100r)" % (i, expected, vals)) |
| 726 |
except ValueError: |
| 727 |
self.fail("test %d failed: got ValueError, expected %r " |
| 728 |
"for math.fsum(%.100r)" % (i, expected, vals)) |
| 729 |
self.assertEqual(actual, expected) |
| 730 |
|
| 731 |
from random import random, gauss, shuffle |
| 732 |
for j in range(1000): |
| 733 |
vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10 |
| 734 |
s = 0 |
| 735 |
for i in range(200): |
| 736 |
v = gauss(0, random()) ** 7 - s |
| 737 |
s += v |
| 738 |
vals.append(v) |
| 739 |
shuffle(vals) |
| 740 |
|
| 741 |
s = msum(vals) |
| 742 |
self.assertEqual(msum(vals), math.fsum(vals)) |
| 743 |
|
| 744 |
self.assertEqual(math.fsum([1.0, math.inf]), math.inf) |
| 745 |
self.assertTrue(math.isnan(math.fsum([math.nan, 1.0]))) |
| 746 |
self.assertEqual(math.fsum([1e100, FloatLike(1.0), -1e100, 1e-100, |
| 747 |
1e50, FloatLike(-1.0), -1e50]), 1e-100) |
| 748 |
self.assertRaises(OverflowError, math.fsum, [1e+308, 1e+308]) |
| 749 |
self.assertRaises(ValueError, math.fsum, [math.inf, -math.inf]) |
| 750 |
self.assertRaises(TypeError, math.fsum, ['spam']) |
| 751 |
self.assertRaises(TypeError, math.fsum, 1) |
| 752 |
self.assertRaises(OverflowError, math.fsum, [10**1000]) |
| 753 |
|
| 754 |
def bad_iter(): |
| 755 |
yield 1.0 |
| 756 |
raise ZeroDivisionError |
| 757 |
|
| 758 |
self.assertRaises(ZeroDivisionError, math.fsum, bad_iter()) |
| 759 |
|
| 760 |
def testGcd(self): |
| 761 |
gcd = math.gcd |
| 762 |
self.assertEqual(gcd(0, 0), 0) |
| 763 |
self.assertEqual(gcd(1, 0), 1) |
| 764 |
self.assertEqual(gcd(-1, 0), 1) |
| 765 |
self.assertEqual(gcd(0, 1), 1) |
| 766 |
self.assertEqual(gcd(0, -1), 1) |
| 767 |
self.assertEqual(gcd(7, 1), 1) |
| 768 |
self.assertEqual(gcd(7, -1), 1) |
| 769 |
self.assertEqual(gcd(-23, 15), 1) |
| 770 |
self.assertEqual(gcd(120, 84), 12) |
| 771 |
self.assertEqual(gcd(84, -120), 12) |
| 772 |
self.assertEqual(gcd(1216342683557601535506311712, |
| 773 |
436522681849110124616458784), 32) |
| 774 |
|
| 775 |
x = 434610456570399902378880679233098819019853229470286994367836600566 |
| 776 |
y = 1064502245825115327754847244914921553977 |
| 777 |
for c in (652560, |
| 778 |
576559230871654959816130551884856912003141446781646602790216406874): |
| 779 |
a = x * c |
| 780 |
b = y * c |
| 781 |
self.assertEqual(gcd(a, b), c) |
| 782 |
self.assertEqual(gcd(b, a), c) |
| 783 |
self.assertEqual(gcd(-a, b), c) |
| 784 |
self.assertEqual(gcd(b, -a), c) |
| 785 |
self.assertEqual(gcd(a, -b), c) |
| 786 |
self.assertEqual(gcd(-b, a), c) |
| 787 |
self.assertEqual(gcd(-a, -b), c) |
| 788 |
self.assertEqual(gcd(-b, -a), c) |
| 789 |
|
| 790 |
self.assertEqual(gcd(), 0) |
| 791 |
self.assertEqual(gcd(120), 120) |
| 792 |
self.assertEqual(gcd(-120), 120) |
| 793 |
self.assertEqual(gcd(120, 84, 102), 6) |
| 794 |
self.assertEqual(gcd(120, 1, 84), 1) |
| 795 |
|
| 796 |
self.assertRaises(TypeError, gcd, 120.0) |
| 797 |
self.assertRaises(TypeError, gcd, 120.0, 84) |
| 798 |
self.assertRaises(TypeError, gcd, 120, 84.0) |
| 799 |
self.assertRaises(TypeError, gcd, 120, 1, 84.0) |
| 800 |
self.assertEqual(gcd(MyIndexable(120), MyIndexable(84)), 12) |
| 801 |
|
| 802 |
def testHypot(self): |
| 803 |
from decimal import Decimal |
| 804 |
from fractions import Fraction |
| 805 |
|
| 806 |
hypot = math.hypot |
| 807 |
|
| 808 |
# Test different numbers of arguments (from zero to five) |
| 809 |
# against a straightforward pure python implementation |
| 810 |
args = math.e, math.pi, math.sqrt(2.0), math.gamma(3.5), math.sin(2.1) |
| 811 |
for i in range(len(args)+1): |
| 812 |
self.assertAlmostEqual( |
| 813 |
hypot(*args[:i]), |
| 814 |
math.sqrt(sum(s**2 for s in args[:i])) |
| 815 |
) |
| 816 |
|
| 817 |
# Test allowable types (those with __float__) |
| 818 |
self.assertEqual(hypot(12.0, 5.0), 13.0) |
| 819 |
self.assertEqual(hypot(12, 5), 13) |
| 820 |
self.assertEqual(hypot(0.75, -1), 1.25) |
| 821 |
self.assertEqual(hypot(-1, 0.75), 1.25) |
| 822 |
self.assertEqual(hypot(0.75, FloatLike(-1.)), 1.25) |
| 823 |
self.assertEqual(hypot(FloatLike(-1.), 0.75), 1.25) |
| 824 |
self.assertEqual(hypot(Decimal(12), Decimal(5)), 13) |
| 825 |
self.assertEqual(hypot(Fraction(12, 32), Fraction(5, 32)), Fraction(13, 32)) |
| 826 |
self.assertEqual(hypot(True, False, True, True, True), 2.0) |
| 827 |
|
| 828 |
# Test corner cases |
| 829 |
self.assertEqual(hypot(0.0, 0.0), 0.0) # Max input is zero |
| 830 |
self.assertEqual(hypot(-10.5), 10.5) # Negative input |
| 831 |
self.assertEqual(hypot(), 0.0) # Negative input |
| 832 |
self.assertEqual(1.0, |
| 833 |
math.copysign(1.0, hypot(-0.0)) # Convert negative zero to positive zero |
| 834 |
) |
| 835 |
self.assertEqual( # Handling of moving max to the end |
| 836 |
hypot(1.5, 1.5, 0.5), |
| 837 |
hypot(1.5, 0.5, 1.5), |
| 838 |
) |
| 839 |
|
| 840 |
# Test handling of bad arguments |
| 841 |
with self.assertRaises(TypeError): # Reject keyword args |
| 842 |
hypot(x=1) |
| 843 |
with self.assertRaises(TypeError): # Reject values without __float__ |
| 844 |
hypot(1.1, 'string', 2.2) |
| 845 |
int_too_big_for_float = 10 ** (sys.float_info.max_10_exp + 5) |
| 846 |
with self.assertRaises((ValueError, OverflowError)): |
| 847 |
hypot(1, int_too_big_for_float) |
| 848 |
|
| 849 |
# Any infinity gives positive infinity. |
| 850 |
self.assertEqual(hypot(INF), INF) |
| 851 |
self.assertEqual(hypot(0, INF), INF) |
| 852 |
self.assertEqual(hypot(10, INF), INF) |
| 853 |
self.assertEqual(hypot(-10, INF), INF) |
| 854 |
self.assertEqual(hypot(NAN, INF), INF) |
| 855 |
self.assertEqual(hypot(INF, NAN), INF) |
| 856 |
self.assertEqual(hypot(NINF, NAN), INF) |
| 857 |
self.assertEqual(hypot(NAN, NINF), INF) |
| 858 |
self.assertEqual(hypot(-INF, INF), INF) |
| 859 |
self.assertEqual(hypot(-INF, -INF), INF) |
| 860 |
self.assertEqual(hypot(10, -INF), INF) |
| 861 |
|
| 862 |
# If no infinity, any NaN gives a NaN. |
| 863 |
self.assertTrue(math.isnan(hypot(NAN))) |
| 864 |
self.assertTrue(math.isnan(hypot(0, NAN))) |
| 865 |
self.assertTrue(math.isnan(hypot(NAN, 10))) |
| 866 |
self.assertTrue(math.isnan(hypot(10, NAN))) |
| 867 |
self.assertTrue(math.isnan(hypot(NAN, NAN))) |
| 868 |
self.assertTrue(math.isnan(hypot(NAN))) |
| 869 |
|
| 870 |
# Verify scaling for extremely large values |
| 871 |
fourthmax = FLOAT_MAX / 4.0 |
| 872 |
for n in range(32): |
| 873 |
self.assertTrue(math.isclose(hypot(*([fourthmax]*n)), |
| 874 |
fourthmax * math.sqrt(n))) |
| 875 |
|
| 876 |
# Verify scaling for extremely small values |
| 877 |
for exp in range(32): |
| 878 |
scale = FLOAT_MIN / 2.0 ** exp |
| 879 |
self.assertEqual(math.hypot(4*scale, 3*scale), 5*scale) |
| 880 |
|
| 881 |
self.assertRaises(TypeError, math.hypot, *([1.0]*18), 'spam') |
| 882 |
|
| 883 |
@requires_IEEE_754 |
| 884 |
@unittest.skipIf(HAVE_DOUBLE_ROUNDING, |
| 885 |
"hypot() loses accuracy on machines with double rounding") |
| 886 |
def testHypotAccuracy(self): |
| 887 |
# Verify improved accuracy in cases that were known to be inaccurate. |
| 888 |
# |
| 889 |
# The new algorithm's accuracy depends on IEEE 754 arithmetic |
| 890 |
# guarantees, on having the usual ROUND HALF EVEN rounding mode, on |
| 891 |
# the system not having double rounding due to extended precision, |
| 892 |
# and on the compiler maintaining the specified order of operations. |
| 893 |
# |
| 894 |
# This test is known to succeed on most of our builds. If it fails |
| 895 |
# some build, we either need to add another skipIf if the cause is |
| 896 |
# identifiable; otherwise, we can remove this test entirely. |
| 897 |
|
| 898 |
hypot = math.hypot |
| 899 |
Decimal = decimal.Decimal |
| 900 |
high_precision = decimal.Context(prec=500) |
| 901 |
|
| 902 |
for hx, hy in [ |
| 903 |
# Cases with a 1 ulp error in Python 3.7 compiled with Clang |
| 904 |
('0x1.10e89518dca48p+29', '0x1.1970f7565b7efp+30'), |
| 905 |
('0x1.10106eb4b44a2p+29', '0x1.ef0596cdc97f8p+29'), |
| 906 |
('0x1.459c058e20bb7p+30', '0x1.993ca009b9178p+29'), |
| 907 |
('0x1.378371ae67c0cp+30', '0x1.fbe6619854b4cp+29'), |
| 908 |
('0x1.f4cd0574fb97ap+29', '0x1.50fe31669340ep+30'), |
| 909 |
('0x1.494b2cdd3d446p+29', '0x1.212a5367b4c7cp+29'), |
| 910 |
('0x1.f84e649f1e46dp+29', '0x1.1fa56bef8eec4p+30'), |
| 911 |
('0x1.2e817edd3d6fap+30', '0x1.eb0814f1e9602p+29'), |
| 912 |
('0x1.0d3a6e3d04245p+29', '0x1.32a62fea52352p+30'), |
| 913 |
('0x1.888e19611bfc5p+29', '0x1.52b8e70b24353p+29'), |
| 914 |
|
| 915 |
# Cases with 2 ulp error in Python 3.8 |
| 916 |
('0x1.538816d48a13fp+29', '0x1.7967c5ca43e16p+29'), |
| 917 |
('0x1.57b47b7234530p+29', '0x1.74e2c7040e772p+29'), |
| 918 |
('0x1.821b685e9b168p+30', '0x1.677dc1c1e3dc6p+29'), |
| 919 |
('0x1.9e8247f67097bp+29', '0x1.24bd2dc4f4baep+29'), |
| 920 |
('0x1.b73b59e0cb5f9p+29', '0x1.da899ab784a97p+28'), |
| 921 |
('0x1.94a8d2842a7cfp+30', '0x1.326a51d4d8d8ap+30'), |
| 922 |
('0x1.e930b9cd99035p+29', '0x1.5a1030e18dff9p+30'), |
| 923 |
('0x1.1592bbb0e4690p+29', '0x1.a9c337b33fb9ap+29'), |
| 924 |
('0x1.1243a50751fd4p+29', '0x1.a5a10175622d9p+29'), |
| 925 |
('0x1.57a8596e74722p+30', '0x1.42d1af9d04da9p+30'), |
| 926 |
|
| 927 |
# Cases with 1 ulp error in version fff3c28052e6b0 |
| 928 |
('0x1.ee7dbd9565899p+29', '0x1.7ab4d6fc6e4b4p+29'), |
| 929 |
('0x1.5c6bfbec5c4dcp+30', '0x1.02511184b4970p+30'), |
| 930 |
('0x1.59dcebba995cap+30', '0x1.50ca7e7c38854p+29'), |
| 931 |
('0x1.768cdd94cf5aap+29', '0x1.9cfdc5571d38ep+29'), |
| 932 |
('0x1.dcf137d60262ep+29', '0x1.1101621990b3ep+30'), |
| 933 |
('0x1.3a2d006e288b0p+30', '0x1.e9a240914326cp+29'), |
| 934 |
('0x1.62a32f7f53c61p+29', '0x1.47eb6cd72684fp+29'), |
| 935 |
('0x1.d3bcb60748ef2p+29', '0x1.3f13c4056312cp+30'), |
| 936 |
('0x1.282bdb82f17f3p+30', '0x1.640ba4c4eed3ap+30'), |
| 937 |
('0x1.89d8c423ea0c6p+29', '0x1.d35dcfe902bc3p+29'), |
| 938 |
]: |
| 939 |
x = float.fromhex(hx) |
| 940 |
y = float.fromhex(hy) |
| 941 |
with self.subTest(hx=hx, hy=hy, x=x, y=y): |
| 942 |
with decimal.localcontext(high_precision): |
| 943 |
z = float((Decimal(x)**2 + Decimal(y)**2).sqrt()) |
| 944 |
self.assertEqual(hypot(x, y), z) |
| 945 |
|
| 946 |
def testDist(self): |
| 947 |
from decimal import Decimal as D |
| 948 |
from fractions import Fraction as F |
| 949 |
|
| 950 |
dist = math.dist |
| 951 |
sqrt = math.sqrt |
| 952 |
|
| 953 |
# Simple exact cases |
| 954 |
self.assertEqual(dist((1.0, 2.0, 3.0), (4.0, 2.0, -1.0)), 5.0) |
| 955 |
self.assertEqual(dist((1, 2, 3), (4, 2, -1)), 5.0) |
| 956 |
|
| 957 |
# Test different numbers of arguments (from zero to nine) |
| 958 |
# against a straightforward pure python implementation |
| 959 |
for i in range(9): |
| 960 |
for j in range(5): |
| 961 |
p = tuple(random.uniform(-5, 5) for k in range(i)) |
| 962 |
q = tuple(random.uniform(-5, 5) for k in range(i)) |
| 963 |
self.assertAlmostEqual( |
| 964 |
dist(p, q), |
| 965 |
sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q))) |
| 966 |
) |
| 967 |
|
| 968 |
# Test non-tuple inputs |
| 969 |
self.assertEqual(dist([1.0, 2.0, 3.0], [4.0, 2.0, -1.0]), 5.0) |
| 970 |
self.assertEqual(dist(iter([1.0, 2.0, 3.0]), iter([4.0, 2.0, -1.0])), 5.0) |
| 971 |
|
| 972 |
# Test allowable types (those with __float__) |
| 973 |
self.assertEqual(dist((14.0, 1.0), (2.0, -4.0)), 13.0) |
| 974 |
self.assertEqual(dist((14, 1), (2, -4)), 13) |
| 975 |
self.assertEqual(dist((FloatLike(14.), 1), (2, -4)), 13) |
| 976 |
self.assertEqual(dist((11, 1), (FloatLike(-1.), -4)), 13) |
| 977 |
self.assertEqual(dist((14, FloatLike(-1.)), (2, -6)), 13) |
| 978 |
self.assertEqual(dist((14, -1), (2, -6)), 13) |
| 979 |
self.assertEqual(dist((D(14), D(1)), (D(2), D(-4))), D(13)) |
| 980 |
self.assertEqual(dist((F(14, 32), F(1, 32)), (F(2, 32), F(-4, 32))), |
| 981 |
F(13, 32)) |
| 982 |
self.assertEqual(dist((True, True, False, False, True, True), |
| 983 |
(True, False, True, False, False, False)), |
| 984 |
2.0) |
| 985 |
|
| 986 |
# Test corner cases |
| 987 |
self.assertEqual(dist((13.25, 12.5, -3.25), |
| 988 |
(13.25, 12.5, -3.25)), |
| 989 |
0.0) # Distance with self is zero |
| 990 |
self.assertEqual(dist((), ()), 0.0) # Zero-dimensional case |
| 991 |
self.assertEqual(1.0, # Convert negative zero to positive zero |
| 992 |
math.copysign(1.0, dist((-0.0,), (0.0,))) |
| 993 |
) |
| 994 |
self.assertEqual(1.0, # Convert negative zero to positive zero |
| 995 |
math.copysign(1.0, dist((0.0,), (-0.0,))) |
| 996 |
) |
| 997 |
self.assertEqual( # Handling of moving max to the end |
| 998 |
dist((1.5, 1.5, 0.5), (0, 0, 0)), |
| 999 |
dist((1.5, 0.5, 1.5), (0, 0, 0)) |
| 1000 |
) |
| 1001 |
|
| 1002 |
# Verify tuple subclasses are allowed |
| 1003 |
class T(tuple): |
| 1004 |
pass |
| 1005 |
self.assertEqual(dist(T((1, 2, 3)), ((4, 2, -1))), 5.0) |
| 1006 |
|
| 1007 |
# Test handling of bad arguments |
| 1008 |
with self.assertRaises(TypeError): # Reject keyword args |
| 1009 |
dist(p=(1, 2, 3), q=(4, 5, 6)) |
| 1010 |
with self.assertRaises(TypeError): # Too few args |
| 1011 |
dist((1, 2, 3)) |
| 1012 |
with self.assertRaises(TypeError): # Too many args |
| 1013 |
dist((1, 2, 3), (4, 5, 6), (7, 8, 9)) |
| 1014 |
with self.assertRaises(TypeError): # Scalars not allowed |
| 1015 |
dist(1, 2) |
| 1016 |
with self.assertRaises(TypeError): # Reject values without __float__ |
| 1017 |
dist((1.1, 'string', 2.2), (1, 2, 3)) |
| 1018 |
with self.assertRaises(ValueError): # Check dimension agree |
| 1019 |
dist((1, 2, 3, 4), (5, 6, 7)) |
| 1020 |
with self.assertRaises(ValueError): # Check dimension agree |
| 1021 |
dist((1, 2, 3), (4, 5, 6, 7)) |
| 1022 |
with self.assertRaises(TypeError): |
| 1023 |
dist((1,)*17 + ("spam",), (1,)*18) |
| 1024 |
with self.assertRaises(TypeError): # Rejects invalid types |
| 1025 |
dist("abc", "xyz") |
| 1026 |
int_too_big_for_float = 10 ** (sys.float_info.max_10_exp + 5) |
| 1027 |
with self.assertRaises((ValueError, OverflowError)): |
| 1028 |
dist((1, int_too_big_for_float), (2, 3)) |
| 1029 |
with self.assertRaises((ValueError, OverflowError)): |
| 1030 |
dist((2, 3), (1, int_too_big_for_float)) |
| 1031 |
with self.assertRaises(TypeError): |
| 1032 |
dist((1,), 2) |
| 1033 |
with self.assertRaises(TypeError): |
| 1034 |
dist([1], 2) |
| 1035 |
|
| 1036 |
class BadFloat: |
| 1037 |
__float__ = BadDescr() |
| 1038 |
|
| 1039 |
with self.assertRaises(ValueError): |
| 1040 |
dist([1], [BadFloat()]) |
| 1041 |
|
| 1042 |
# Verify that the one dimensional case is equivalent to abs() |
| 1043 |
for i in range(20): |
| 1044 |
p, q = random.random(), random.random() |
| 1045 |
self.assertEqual(dist((p,), (q,)), abs(p - q)) |
| 1046 |
|
| 1047 |
# Test special values |
| 1048 |
values = [NINF, -10.5, -0.0, 0.0, 10.5, INF, NAN] |
| 1049 |
for p in itertools.product(values, repeat=3): |
| 1050 |
for q in itertools.product(values, repeat=3): |
| 1051 |
diffs = [px - qx for px, qx in zip(p, q)] |
| 1052 |
if any(map(math.isinf, diffs)): |
| 1053 |
# Any infinite difference gives positive infinity. |
| 1054 |
self.assertEqual(dist(p, q), INF) |
| 1055 |
elif any(map(math.isnan, diffs)): |
| 1056 |
# If no infinity, any NaN gives a NaN. |
| 1057 |
self.assertTrue(math.isnan(dist(p, q))) |
| 1058 |
|
| 1059 |
# Verify scaling for extremely large values |
| 1060 |
fourthmax = FLOAT_MAX / 4.0 |
| 1061 |
for n in range(32): |
| 1062 |
p = (fourthmax,) * n |
| 1063 |
q = (0.0,) * n |
| 1064 |
self.assertTrue(math.isclose(dist(p, q), fourthmax * math.sqrt(n))) |
| 1065 |
self.assertTrue(math.isclose(dist(q, p), fourthmax * math.sqrt(n))) |
| 1066 |
|
| 1067 |
# Verify scaling for extremely small values |
| 1068 |
for exp in range(32): |
| 1069 |
scale = FLOAT_MIN / 2.0 ** exp |
| 1070 |
p = (4*scale, 3*scale) |
| 1071 |
q = (0.0, 0.0) |
| 1072 |
self.assertEqual(math.dist(p, q), 5*scale) |
| 1073 |
self.assertEqual(math.dist(q, p), 5*scale) |
| 1074 |
|
| 1075 |
def test_math_dist_leak(self): |
| 1076 |
# gh-98897: Check for error handling does not leak memory |
| 1077 |
with self.assertRaises(ValueError): |
| 1078 |
math.dist([1, 2], [3, 4, 5]) |
| 1079 |
|
| 1080 |
def testIsqrt(self): |
| 1081 |
# Test a variety of inputs, large and small. |
| 1082 |
test_values = ( |
| 1083 |
list(range(1000)) |
| 1084 |
+ list(range(10**6 - 1000, 10**6 + 1000)) |
| 1085 |
+ [2**e + i for e in range(60, 200) for i in range(-40, 40)] |
| 1086 |
+ [3**9999, 10**5001] |
| 1087 |
) |
| 1088 |
|
| 1089 |
for value in test_values: |
| 1090 |
with self.subTest(value=value): |
| 1091 |
s = math.isqrt(value) |
| 1092 |
self.assertIs(type(s), int) |
| 1093 |
self.assertLessEqual(s*s, value) |
| 1094 |
self.assertLess(value, (s+1)*(s+1)) |
| 1095 |
|
| 1096 |
# Negative values |
| 1097 |
with self.assertRaises(ValueError): |
| 1098 |
math.isqrt(-1) |
| 1099 |
|
| 1100 |
# Integer-like things |
| 1101 |
s = math.isqrt(True) |
| 1102 |
self.assertIs(type(s), int) |
| 1103 |
self.assertEqual(s, 1) |
| 1104 |
|
| 1105 |
s = math.isqrt(False) |
| 1106 |
self.assertIs(type(s), int) |
| 1107 |
self.assertEqual(s, 0) |
| 1108 |
|
| 1109 |
class IntegerLike(object): |
| 1110 |
def __init__(self, value): |
| 1111 |
self.value = value |
| 1112 |
|
| 1113 |
def __index__(self): |
| 1114 |
return self.value |
| 1115 |
|
| 1116 |
s = math.isqrt(IntegerLike(1729)) |
| 1117 |
self.assertIs(type(s), int) |
| 1118 |
self.assertEqual(s, 41) |
| 1119 |
|
| 1120 |
with self.assertRaises(ValueError): |
| 1121 |
math.isqrt(IntegerLike(-3)) |
| 1122 |
|
| 1123 |
# Non-integer-like things |
| 1124 |
bad_values = [ |
| 1125 |
3.5, "a string", decimal.Decimal("3.5"), 3.5j, |
| 1126 |
100.0, -4.0, |
| 1127 |
] |
| 1128 |
for value in bad_values: |
| 1129 |
with self.subTest(value=value): |
| 1130 |
with self.assertRaises(TypeError): |
| 1131 |
math.isqrt(value) |
| 1132 |
|
| 1133 |
@support.bigmemtest(2**32, memuse=0.85) |
| 1134 |
def test_isqrt_huge(self, size): |
| 1135 |
if size & 1: |
| 1136 |
size += 1 |
| 1137 |
v = 1 << size |
| 1138 |
w = math.isqrt(v) |
| 1139 |
self.assertEqual(w.bit_length(), size // 2 + 1) |
| 1140 |
self.assertEqual(w.bit_count(), 1) |
| 1141 |
|
| 1142 |
def test_lcm(self): |
| 1143 |
lcm = math.lcm |
| 1144 |
self.assertEqual(lcm(0, 0), 0) |
| 1145 |
self.assertEqual(lcm(1, 0), 0) |
| 1146 |
self.assertEqual(lcm(-1, 0), 0) |
| 1147 |
self.assertEqual(lcm(0, 1), 0) |
| 1148 |
self.assertEqual(lcm(0, -1), 0) |
| 1149 |
self.assertEqual(lcm(7, 1), 7) |
| 1150 |
self.assertEqual(lcm(7, -1), 7) |
| 1151 |
self.assertEqual(lcm(-23, 15), 345) |
| 1152 |
self.assertEqual(lcm(120, 84), 840) |
| 1153 |
self.assertEqual(lcm(84, -120), 840) |
| 1154 |
self.assertEqual(lcm(1216342683557601535506311712, |
| 1155 |
436522681849110124616458784), |
| 1156 |
16592536571065866494401400422922201534178938447014944) |
| 1157 |
|
| 1158 |
x = 43461045657039990237 |
| 1159 |
y = 10645022458251153277 |
| 1160 |
for c in (652560, |
| 1161 |
57655923087165495981): |
| 1162 |
a = x * c |
| 1163 |
b = y * c |
| 1164 |
d = x * y * c |
| 1165 |
self.assertEqual(lcm(a, b), d) |
| 1166 |
self.assertEqual(lcm(b, a), d) |
| 1167 |
self.assertEqual(lcm(-a, b), d) |
| 1168 |
self.assertEqual(lcm(b, -a), d) |
| 1169 |
self.assertEqual(lcm(a, -b), d) |
| 1170 |
self.assertEqual(lcm(-b, a), d) |
| 1171 |
self.assertEqual(lcm(-a, -b), d) |
| 1172 |
self.assertEqual(lcm(-b, -a), d) |
| 1173 |
|
| 1174 |
self.assertEqual(lcm(), 1) |
| 1175 |
self.assertEqual(lcm(120), 120) |
| 1176 |
self.assertEqual(lcm(-120), 120) |
| 1177 |
self.assertEqual(lcm(120, 84, 102), 14280) |
| 1178 |
self.assertEqual(lcm(120, 0, 84), 0) |
| 1179 |
|
| 1180 |
self.assertRaises(TypeError, lcm, 120.0) |
| 1181 |
self.assertRaises(TypeError, lcm, 120.0, 84) |
| 1182 |
self.assertRaises(TypeError, lcm, 120, 84.0) |
| 1183 |
self.assertRaises(TypeError, lcm, 120, 0, 84.0) |
| 1184 |
self.assertEqual(lcm(MyIndexable(120), MyIndexable(84)), 840) |
| 1185 |
|
| 1186 |
def testLdexp(self): |
| 1187 |
self.assertRaises(TypeError, math.ldexp) |
| 1188 |
self.assertRaises(TypeError, math.ldexp, 2.0, 1.1) |
| 1189 |
self.ftest('ldexp(0,1)', math.ldexp(0,1), 0) |
| 1190 |
self.ftest('ldexp(1,1)', math.ldexp(1,1), 2) |
| 1191 |
self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5) |
| 1192 |
self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2) |
| 1193 |
self.assertRaises(OverflowError, math.ldexp, 1., 1000000) |
| 1194 |
self.assertRaises(OverflowError, math.ldexp, -1., 1000000) |
| 1195 |
self.assertEqual(math.ldexp(1., -1000000), 0.) |
| 1196 |
self.assertEqual(math.ldexp(-1., -1000000), -0.) |
| 1197 |
self.assertEqual(math.ldexp(INF, 30), INF) |
| 1198 |
self.assertEqual(math.ldexp(NINF, -213), NINF) |
| 1199 |
self.assertTrue(math.isnan(math.ldexp(NAN, 0))) |
| 1200 |
|
| 1201 |
# large second argument |
| 1202 |
for n in [10**5, 10**10, 10**20, 10**40]: |
| 1203 |
self.assertEqual(math.ldexp(INF, -n), INF) |
| 1204 |
self.assertEqual(math.ldexp(NINF, -n), NINF) |
| 1205 |
self.assertEqual(math.ldexp(1., -n), 0.) |
| 1206 |
self.assertEqual(math.ldexp(-1., -n), -0.) |
| 1207 |
self.assertEqual(math.ldexp(0., -n), 0.) |
| 1208 |
self.assertEqual(math.ldexp(-0., -n), -0.) |
| 1209 |
self.assertTrue(math.isnan(math.ldexp(NAN, -n))) |
| 1210 |
|
| 1211 |
self.assertRaises(OverflowError, math.ldexp, 1., n) |
| 1212 |
self.assertRaises(OverflowError, math.ldexp, -1., n) |
| 1213 |
self.assertEqual(math.ldexp(0., n), 0.) |
| 1214 |
self.assertEqual(math.ldexp(-0., n), -0.) |
| 1215 |
self.assertEqual(math.ldexp(INF, n), INF) |
| 1216 |
self.assertEqual(math.ldexp(NINF, n), NINF) |
| 1217 |
self.assertTrue(math.isnan(math.ldexp(NAN, n))) |
| 1218 |
|
| 1219 |
@requires_IEEE_754 |
| 1220 |
def testLdexp_denormal(self): |
| 1221 |
# Denormal output incorrectly rounded (truncated) |
| 1222 |
# on some Windows. |
| 1223 |
self.assertEqual(math.ldexp(6993274598585239, -1126), 1e-323) |
| 1224 |
|
| 1225 |
def testLog(self): |
| 1226 |
self.assertRaises(TypeError, math.log) |
| 1227 |
self.assertRaises(TypeError, math.log, 1, 2, 3) |
| 1228 |
self.ftest('log(1/e)', math.log(1/math.e), -1) |
| 1229 |
self.ftest('log(1)', math.log(1), 0) |
| 1230 |
self.ftest('log(e)', math.log(math.e), 1) |
| 1231 |
self.ftest('log(32,2)', math.log(32,2), 5) |
| 1232 |
self.ftest('log(10**40, 10)', math.log(10**40, 10), 40) |
| 1233 |
self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2) |
| 1234 |
self.ftest('log(10**1000)', math.log(10**1000), |
| 1235 |
2302.5850929940457) |
| 1236 |
self.assertRaises(ValueError, math.log, -1.5) |
| 1237 |
self.assertRaises(ValueError, math.log, -10**1000) |
| 1238 |
self.assertRaises(ValueError, math.log, 10, -10) |
| 1239 |
self.assertRaises(ValueError, math.log, NINF) |
| 1240 |
self.assertEqual(math.log(INF), INF) |
| 1241 |
self.assertTrue(math.isnan(math.log(NAN))) |
| 1242 |
|
| 1243 |
def testLog1p(self): |
| 1244 |
self.assertRaises(TypeError, math.log1p) |
| 1245 |
for n in [2, 2**90, 2**300]: |
| 1246 |
self.assertAlmostEqual(math.log1p(n), math.log1p(float(n))) |
| 1247 |
self.assertRaises(ValueError, math.log1p, -1) |
| 1248 |
self.assertEqual(math.log1p(INF), INF) |
| 1249 |
|
| 1250 |
@requires_IEEE_754 |
| 1251 |
def testLog2(self): |
| 1252 |
self.assertRaises(TypeError, math.log2) |
| 1253 |
|
| 1254 |
# Check some integer values |
| 1255 |
self.assertEqual(math.log2(1), 0.0) |
| 1256 |
self.assertEqual(math.log2(2), 1.0) |
| 1257 |
self.assertEqual(math.log2(4), 2.0) |
| 1258 |
|
| 1259 |
# Large integer values |
| 1260 |
self.assertEqual(math.log2(2**1023), 1023.0) |
| 1261 |
self.assertEqual(math.log2(2**1024), 1024.0) |
| 1262 |
self.assertEqual(math.log2(2**2000), 2000.0) |
| 1263 |
|
| 1264 |
self.assertRaises(ValueError, math.log2, -1.5) |
| 1265 |
self.assertRaises(ValueError, math.log2, NINF) |
| 1266 |
self.assertTrue(math.isnan(math.log2(NAN))) |
| 1267 |
|
| 1268 |
@requires_IEEE_754 |
| 1269 |
# log2() is not accurate enough on Mac OS X Tiger (10.4) |
| 1270 |
@support.requires_mac_ver(10, 5) |
| 1271 |
def testLog2Exact(self): |
| 1272 |
# Check that we get exact equality for log2 of powers of 2. |
| 1273 |
actual = [math.log2(math.ldexp(1.0, n)) for n in range(-1074, 1024)] |
| 1274 |
expected = [float(n) for n in range(-1074, 1024)] |
| 1275 |
self.assertEqual(actual, expected) |
| 1276 |
|
| 1277 |
def testLog10(self): |
| 1278 |
self.assertRaises(TypeError, math.log10) |
| 1279 |
self.ftest('log10(0.1)', math.log10(0.1), -1) |
| 1280 |
self.ftest('log10(1)', math.log10(1), 0) |
| 1281 |
self.ftest('log10(10)', math.log10(10), 1) |
| 1282 |
self.ftest('log10(10**1000)', math.log10(10**1000), 1000.0) |
| 1283 |
self.assertRaises(ValueError, math.log10, -1.5) |
| 1284 |
self.assertRaises(ValueError, math.log10, -10**1000) |
| 1285 |
self.assertRaises(ValueError, math.log10, NINF) |
| 1286 |
self.assertEqual(math.log(INF), INF) |
| 1287 |
self.assertTrue(math.isnan(math.log10(NAN))) |
| 1288 |
|
| 1289 |
@support.bigmemtest(2**32, memuse=0.2) |
| 1290 |
def test_log_huge_integer(self, size): |
| 1291 |
v = 1 << size |
| 1292 |
self.assertAlmostEqual(math.log2(v), size) |
| 1293 |
self.assertAlmostEqual(math.log(v), size * 0.6931471805599453) |
| 1294 |
self.assertAlmostEqual(math.log10(v), size * 0.3010299956639812) |
| 1295 |
|
| 1296 |
def testSumProd(self): |
| 1297 |
sumprod = math.sumprod |
| 1298 |
Decimal = decimal.Decimal |
| 1299 |
Fraction = fractions.Fraction |
| 1300 |
|
| 1301 |
# Core functionality |
| 1302 |
self.assertEqual(sumprod(iter([10, 20, 30]), (1, 2, 3)), 140) |
| 1303 |
self.assertEqual(sumprod([1.5, 2.5], [3.5, 4.5]), 16.5) |
| 1304 |
self.assertEqual(sumprod([], []), 0) |
| 1305 |
self.assertEqual(sumprod([-1], [1.]), -1) |
| 1306 |
self.assertEqual(sumprod([1.], [-1]), -1) |
| 1307 |
|
| 1308 |
# Type preservation and coercion |
| 1309 |
for v in [ |
| 1310 |
(10, 20, 30), |
| 1311 |
(1.5, -2.5), |
| 1312 |
(Fraction(3, 5), Fraction(4, 5)), |
| 1313 |
(Decimal(3.5), Decimal(4.5)), |
| 1314 |
(2.5, 10), # float/int |
| 1315 |
(2.5, Fraction(3, 5)), # float/fraction |
| 1316 |
(25, Fraction(3, 5)), # int/fraction |
| 1317 |
(25, Decimal(4.5)), # int/decimal |
| 1318 |
]: |
| 1319 |
for p, q in [(v, v), (v, v[::-1])]: |
| 1320 |
with self.subTest(p=p, q=q): |
| 1321 |
expected = sum(p_i * q_i for p_i, q_i in zip(p, q, strict=True)) |
| 1322 |
actual = sumprod(p, q) |
| 1323 |
self.assertEqual(expected, actual) |
| 1324 |
self.assertEqual(type(expected), type(actual)) |
| 1325 |
|
| 1326 |
# Bad arguments |
| 1327 |
self.assertRaises(TypeError, sumprod) # No args |
| 1328 |
self.assertRaises(TypeError, sumprod, []) # One arg |
| 1329 |
self.assertRaises(TypeError, sumprod, [], [], []) # Three args |
| 1330 |
self.assertRaises(TypeError, sumprod, None, [10]) # Non-iterable |
| 1331 |
self.assertRaises(TypeError, sumprod, [10], None) # Non-iterable |
| 1332 |
self.assertRaises(TypeError, sumprod, ['x'], [1.0]) |
| 1333 |
|
| 1334 |
# Uneven lengths |
| 1335 |
self.assertRaises(ValueError, sumprod, [10, 20], [30]) |
| 1336 |
self.assertRaises(ValueError, sumprod, [10], [20, 30]) |
| 1337 |
|
| 1338 |
# Overflows |
| 1339 |
self.assertEqual(sumprod([10**20], [1]), 10**20) |
| 1340 |
self.assertEqual(sumprod([1], [10**20]), 10**20) |
| 1341 |
self.assertEqual(sumprod([10**10], [10**10]), 10**20) |
| 1342 |
self.assertEqual(sumprod([10**7]*10**5, [10**7]*10**5), 10**19) |
| 1343 |
self.assertRaises(OverflowError, sumprod, [10**1000], [1.0]) |
| 1344 |
self.assertRaises(OverflowError, sumprod, [1.0], [10**1000]) |
| 1345 |
|
| 1346 |
# Error in iterator |
| 1347 |
def raise_after(n): |
| 1348 |
for i in range(n): |
| 1349 |
yield i |
| 1350 |
raise RuntimeError |
| 1351 |
with self.assertRaises(RuntimeError): |
| 1352 |
sumprod(range(10), raise_after(5)) |
| 1353 |
with self.assertRaises(RuntimeError): |
| 1354 |
sumprod(raise_after(5), range(10)) |
| 1355 |
|
| 1356 |
from test.test_iter import BasicIterClass |
| 1357 |
|
| 1358 |
self.assertEqual(sumprod(BasicIterClass(1), [1]), 0) |
| 1359 |
self.assertEqual(sumprod([1], BasicIterClass(1)), 0) |
| 1360 |
|
| 1361 |
# Error in multiplication |
| 1362 |
class BadMultiply: |
| 1363 |
def __mul__(self, other): |
| 1364 |
raise RuntimeError |
| 1365 |
def __rmul__(self, other): |
| 1366 |
raise RuntimeError |
| 1367 |
with self.assertRaises(RuntimeError): |
| 1368 |
sumprod([10, BadMultiply(), 30], [1, 2, 3]) |
| 1369 |
with self.assertRaises(RuntimeError): |
| 1370 |
sumprod([1, 2, 3], [10, BadMultiply(), 30]) |
| 1371 |
|
| 1372 |
# Error in addition |
| 1373 |
with self.assertRaises(TypeError): |
| 1374 |
sumprod(['abc', 3], [5, 10]) |
| 1375 |
with self.assertRaises(TypeError): |
| 1376 |
sumprod([5, 10], ['abc', 3]) |
| 1377 |
|
| 1378 |
# Special values should give the same as the pure python recipe |
| 1379 |
self.assertEqual(sumprod([10.1, math.inf], [20.2, 30.3]), math.inf) |
| 1380 |
self.assertEqual(sumprod([10.1, math.inf], [math.inf, 30.3]), math.inf) |
| 1381 |
self.assertEqual(sumprod([10.1, math.inf], [math.inf, math.inf]), math.inf) |
| 1382 |
self.assertEqual(sumprod([10.1, -math.inf], [20.2, 30.3]), -math.inf) |
| 1383 |
self.assertTrue(math.isnan(sumprod([10.1, math.inf], [-math.inf, math.inf]))) |
| 1384 |
self.assertTrue(math.isnan(sumprod([10.1, math.nan], [20.2, 30.3]))) |
| 1385 |
self.assertTrue(math.isnan(sumprod([10.1, math.inf], [math.nan, 30.3]))) |
| 1386 |
self.assertTrue(math.isnan(sumprod([10.1, math.inf], [20.3, math.nan]))) |
| 1387 |
|
| 1388 |
# Error cases that arose during development |
| 1389 |
args = ((-5, -5, 10), (1.5, 4611686018427387904, 2305843009213693952)) |
| 1390 |
self.assertEqual(sumprod(*args), 0.0) |
| 1391 |
|
| 1392 |
|
| 1393 |
@requires_IEEE_754 |
| 1394 |
@unittest.skipIf(HAVE_DOUBLE_ROUNDING, |
| 1395 |
"sumprod() accuracy not guaranteed on machines with double rounding") |
| 1396 |
@support.cpython_only # Other implementations may choose a different algorithm |
| 1397 |
def test_sumprod_accuracy(self): |
| 1398 |
sumprod = math.sumprod |
| 1399 |
self.assertEqual(sumprod([0.1] * 10, [1]*10), 1.0) |
| 1400 |
self.assertEqual(sumprod([0.1] * 20, [True, False] * 10), 1.0) |
| 1401 |
self.assertEqual(sumprod([True, False] * 10, [0.1] * 20), 1.0) |
| 1402 |
self.assertEqual(sumprod([1.0, 10E100, 1.0, -10E100], [1.0]*4), 2.0) |
| 1403 |
|
| 1404 |
@support.requires_resource('cpu') |
| 1405 |
def test_sumprod_stress(self): |
| 1406 |
sumprod = math.sumprod |
| 1407 |
product = itertools.product |
| 1408 |
Decimal = decimal.Decimal |
| 1409 |
Fraction = fractions.Fraction |
| 1410 |
|
| 1411 |
class Int(int): |
| 1412 |
def __add__(self, other): |
| 1413 |
return Int(int(self) + int(other)) |
| 1414 |
def __mul__(self, other): |
| 1415 |
return Int(int(self) * int(other)) |
| 1416 |
__radd__ = __add__ |
| 1417 |
__rmul__ = __mul__ |
| 1418 |
def __repr__(self): |
| 1419 |
return f'Int({int(self)})' |
| 1420 |
|
| 1421 |
class Flt(float): |
| 1422 |
def __add__(self, other): |
| 1423 |
return Int(int(self) + int(other)) |
| 1424 |
def __mul__(self, other): |
| 1425 |
return Int(int(self) * int(other)) |
| 1426 |
__radd__ = __add__ |
| 1427 |
__rmul__ = __mul__ |
| 1428 |
def __repr__(self): |
| 1429 |
return f'Flt({int(self)})' |
| 1430 |
|
| 1431 |
def baseline_sumprod(p, q): |
| 1432 |
"""This defines the target behavior including exceptions and special values. |
| 1433 |
However, it is subject to rounding errors, so float inputs should be exactly |
| 1434 |
representable with only a few bits. |
| 1435 |
""" |
| 1436 |
total = 0 |
| 1437 |
for p_i, q_i in zip(p, q, strict=True): |
| 1438 |
total += p_i * q_i |
| 1439 |
return total |
| 1440 |
|
| 1441 |
def run(func, *args): |
| 1442 |
"Make comparing functions easier. Returns error status, type, and result." |
| 1443 |
try: |
| 1444 |
result = func(*args) |
| 1445 |
except (AssertionError, NameError): |
| 1446 |
raise |
| 1447 |
except Exception as e: |
| 1448 |
return type(e), None, 'None' |
| 1449 |
return None, type(result), repr(result) |
| 1450 |
|
| 1451 |
pools = [ |
| 1452 |
(-5, 10, -2**20, 2**31, 2**40, 2**61, 2**62, 2**80, 1.5, Int(7)), |
| 1453 |
(5.25, -3.5, 4.75, 11.25, 400.5, 0.046875, 0.25, -1.0, -0.078125), |
| 1454 |
(-19.0*2**500, 11*2**1000, -3*2**1500, 17*2*333, |
| 1455 |
5.25, -3.25, -3.0*2**(-333), 3, 2**513), |
| 1456 |
(3.75, 2.5, -1.5, float('inf'), -float('inf'), float('NaN'), 14, |
| 1457 |
9, 3+4j, Flt(13), 0.0), |
| 1458 |
(13.25, -4.25, Decimal('10.5'), Decimal('-2.25'), Fraction(13, 8), |
| 1459 |
Fraction(-11, 16), 4.75 + 0.125j, 97, -41, Int(3)), |
| 1460 |
(Decimal('6.125'), Decimal('12.375'), Decimal('-2.75'), Decimal(0), |
| 1461 |
Decimal('Inf'), -Decimal('Inf'), Decimal('NaN'), 12, 13.5), |
| 1462 |
(-2.0 ** -1000, 11*2**1000, 3, 7, -37*2**32, -2*2**-537, -2*2**-538, |
| 1463 |
2*2**-513), |
| 1464 |
(-7 * 2.0 ** -510, 5 * 2.0 ** -520, 17, -19.0, -6.25), |
| 1465 |
(11.25, -3.75, -0.625, 23.375, True, False, 7, Int(5)), |
| 1466 |
] |
| 1467 |
|
| 1468 |
for pool in pools: |
| 1469 |
for size in range(4): |
| 1470 |
for args1 in product(pool, repeat=size): |
| 1471 |
for args2 in product(pool, repeat=size): |
| 1472 |
args = (args1, args2) |
| 1473 |
self.assertEqual( |
| 1474 |
run(baseline_sumprod, *args), |
| 1475 |
run(sumprod, *args), |
| 1476 |
args, |
| 1477 |
) |
| 1478 |
|
| 1479 |
@requires_IEEE_754 |
| 1480 |
@unittest.skipIf(HAVE_DOUBLE_ROUNDING, |
| 1481 |
"sumprod() accuracy not guaranteed on machines with double rounding") |
| 1482 |
@support.cpython_only # Other implementations may choose a different algorithm |
| 1483 |
@support.requires_resource('cpu') |
| 1484 |
def test_sumprod_extended_precision_accuracy(self): |
| 1485 |
import operator |
| 1486 |
from fractions import Fraction |
| 1487 |
from itertools import starmap |
| 1488 |
from collections import namedtuple |
| 1489 |
from math import log2, exp2, fabs |
| 1490 |
from random import choices, uniform, shuffle |
| 1491 |
from statistics import median |
| 1492 |
|
| 1493 |
DotExample = namedtuple('DotExample', ('x', 'y', 'target_sumprod', 'condition')) |
| 1494 |
|
| 1495 |
def DotExact(x, y): |
| 1496 |
vec1 = map(Fraction, x) |
| 1497 |
vec2 = map(Fraction, y) |
| 1498 |
return sum(starmap(operator.mul, zip(vec1, vec2, strict=True))) |
| 1499 |
|
| 1500 |
def Condition(x, y): |
| 1501 |
return 2.0 * DotExact(map(abs, x), map(abs, y)) / abs(DotExact(x, y)) |
| 1502 |
|
| 1503 |
def linspace(lo, hi, n): |
| 1504 |
width = (hi - lo) / (n - 1) |
| 1505 |
return [lo + width * i for i in range(n)] |
| 1506 |
|
| 1507 |
def GenDot(n, c): |
| 1508 |
""" Algorithm 6.1 (GenDot) works as follows. The condition number (5.7) of |
| 1509 |
the dot product xT y is proportional to the degree of cancellation. In |
| 1510 |
order to achieve a prescribed cancellation, we generate the first half of |
| 1511 |
the vectors x and y randomly within a large exponent range. This range is |
| 1512 |
chosen according to the anticipated condition number. The second half of x |
| 1513 |
and y is then constructed choosing xi randomly with decreasing exponent, |
| 1514 |
and calculating yi such that some cancellation occurs. Finally, we permute |
| 1515 |
the vectors x, y randomly and calculate the achieved condition number. |
| 1516 |
""" |
| 1517 |
|
| 1518 |
assert n >= 6 |
| 1519 |
n2 = n // 2 |
| 1520 |
x = [0.0] * n |
| 1521 |
y = [0.0] * n |
| 1522 |
b = log2(c) |
| 1523 |
|
| 1524 |
# First half with exponents from 0 to |_b/2_| and random ints in between |
| 1525 |
e = choices(range(int(b/2)), k=n2) |
| 1526 |
e[0] = int(b / 2) + 1 |
| 1527 |
e[-1] = 0.0 |
| 1528 |
|
| 1529 |
x[:n2] = [uniform(-1.0, 1.0) * exp2(p) for p in e] |
| 1530 |
y[:n2] = [uniform(-1.0, 1.0) * exp2(p) for p in e] |
| 1531 |
|
| 1532 |
# Second half |
| 1533 |
e = list(map(round, linspace(b/2, 0.0 , n-n2))) |
| 1534 |
for i in range(n2, n): |
| 1535 |
x[i] = uniform(-1.0, 1.0) * exp2(e[i - n2]) |
| 1536 |
y[i] = (uniform(-1.0, 1.0) * exp2(e[i - n2]) - DotExact(x, y)) / x[i] |
| 1537 |
|
| 1538 |
# Shuffle |
| 1539 |
pairs = list(zip(x, y)) |
| 1540 |
shuffle(pairs) |
| 1541 |
x, y = zip(*pairs) |
| 1542 |
|
| 1543 |
return DotExample(x, y, DotExact(x, y), Condition(x, y)) |
| 1544 |
|
| 1545 |
def RelativeError(res, ex): |
| 1546 |
x, y, target_sumprod, condition = ex |
| 1547 |
n = DotExact(list(x) + [-res], list(y) + [1]) |
| 1548 |
return fabs(n / target_sumprod) |
| 1549 |
|
| 1550 |
def Trial(dotfunc, c, n): |
| 1551 |
ex = GenDot(10, c) |
| 1552 |
res = dotfunc(ex.x, ex.y) |
| 1553 |
return RelativeError(res, ex) |
| 1554 |
|
| 1555 |
times = 1000 # Number of trials |
| 1556 |
n = 20 # Length of vectors |
| 1557 |
c = 1e30 # Target condition number |
| 1558 |
|
| 1559 |
# If the following test fails, it means that the C math library |
| 1560 |
# implementation of fma() is not compliant with the C99 standard |
| 1561 |
# and is inaccurate. To solve this problem, make a new build |
| 1562 |
# with the symbol UNRELIABLE_FMA defined. That will enable a |
| 1563 |
# slower but accurate code path that avoids the fma() call. |
| 1564 |
relative_err = median(Trial(math.sumprod, c, n) for i in range(times)) |
| 1565 |
self.assertLess(relative_err, 1e-16) |
| 1566 |
|
| 1567 |
def testModf(self): |
| 1568 |
self.assertRaises(TypeError, math.modf) |
| 1569 |
|
| 1570 |
def testmodf(name, result, expected): |
| 1571 |
(v1, v2), (e1, e2) = result, expected |
| 1572 |
if abs(v1-e1) > eps or abs(v2-e2): |
| 1573 |
self.fail('%s returned %r, expected %r'%\ |
| 1574 |
(name, result, expected)) |
| 1575 |
|
| 1576 |
testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0)) |
| 1577 |
testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0)) |
| 1578 |
|
| 1579 |
self.assertEqual(math.modf(INF), (0.0, INF)) |
| 1580 |
self.assertEqual(math.modf(NINF), (-0.0, NINF)) |
| 1581 |
|
| 1582 |
modf_nan = math.modf(NAN) |
| 1583 |
self.assertTrue(math.isnan(modf_nan[0])) |
| 1584 |
self.assertTrue(math.isnan(modf_nan[1])) |
| 1585 |
|
| 1586 |
def testPow(self): |
| 1587 |
self.assertRaises(TypeError, math.pow) |
| 1588 |
self.ftest('pow(0,1)', math.pow(0,1), 0) |
| 1589 |
self.ftest('pow(1,0)', math.pow(1,0), 1) |
| 1590 |
self.ftest('pow(2,1)', math.pow(2,1), 2) |
| 1591 |
self.ftest('pow(2,-1)', math.pow(2,-1), 0.5) |
| 1592 |
self.assertEqual(math.pow(INF, 1), INF) |
| 1593 |
self.assertEqual(math.pow(NINF, 1), NINF) |
| 1594 |
self.assertEqual((math.pow(1, INF)), 1.) |
| 1595 |
self.assertEqual((math.pow(1, NINF)), 1.) |
| 1596 |
self.assertTrue(math.isnan(math.pow(NAN, 1))) |
| 1597 |
self.assertTrue(math.isnan(math.pow(2, NAN))) |
| 1598 |
self.assertTrue(math.isnan(math.pow(0, NAN))) |
| 1599 |
self.assertEqual(math.pow(1, NAN), 1) |
| 1600 |
self.assertRaises(OverflowError, math.pow, 1e+100, 1e+100) |
| 1601 |
|
| 1602 |
# pow(0., x) |
| 1603 |
self.assertEqual(math.pow(0., INF), 0.) |
| 1604 |
self.assertEqual(math.pow(0., 3.), 0.) |
| 1605 |
self.assertEqual(math.pow(0., 2.3), 0.) |
| 1606 |
self.assertEqual(math.pow(0., 2.), 0.) |
| 1607 |
self.assertEqual(math.pow(0., 0.), 1.) |
| 1608 |
self.assertEqual(math.pow(0., -0.), 1.) |
| 1609 |
self.assertRaises(ValueError, math.pow, 0., -2.) |
| 1610 |
self.assertRaises(ValueError, math.pow, 0., -2.3) |
| 1611 |
self.assertRaises(ValueError, math.pow, 0., -3.) |
| 1612 |
self.assertEqual(math.pow(0., NINF), INF) |
| 1613 |
self.assertTrue(math.isnan(math.pow(0., NAN))) |
| 1614 |
|
| 1615 |
# pow(INF, x) |
| 1616 |
self.assertEqual(math.pow(INF, INF), INF) |
| 1617 |
self.assertEqual(math.pow(INF, 3.), INF) |
| 1618 |
self.assertEqual(math.pow(INF, 2.3), INF) |
| 1619 |
self.assertEqual(math.pow(INF, 2.), INF) |
| 1620 |
self.assertEqual(math.pow(INF, 0.), 1.) |
| 1621 |
self.assertEqual(math.pow(INF, -0.), 1.) |
| 1622 |
self.assertEqual(math.pow(INF, -2.), 0.) |
| 1623 |
self.assertEqual(math.pow(INF, -2.3), 0.) |
| 1624 |
self.assertEqual(math.pow(INF, -3.), 0.) |
| 1625 |
self.assertEqual(math.pow(INF, NINF), 0.) |
| 1626 |
self.assertTrue(math.isnan(math.pow(INF, NAN))) |
| 1627 |
|
| 1628 |
# pow(-0., x) |
| 1629 |
self.assertEqual(math.pow(-0., INF), 0.) |
| 1630 |
self.assertEqual(math.pow(-0., 3.), -0.) |
| 1631 |
self.assertEqual(math.pow(-0., 2.3), 0.) |
| 1632 |
self.assertEqual(math.pow(-0., 2.), 0.) |
| 1633 |
self.assertEqual(math.pow(-0., 0.), 1.) |
| 1634 |
self.assertEqual(math.pow(-0., -0.), 1.) |
| 1635 |
self.assertRaises(ValueError, math.pow, -0., -2.) |
| 1636 |
self.assertRaises(ValueError, math.pow, -0., -2.3) |
| 1637 |
self.assertRaises(ValueError, math.pow, -0., -3.) |
| 1638 |
self.assertEqual(math.pow(-0., NINF), INF) |
| 1639 |
self.assertTrue(math.isnan(math.pow(-0., NAN))) |
| 1640 |
|
| 1641 |
# pow(NINF, x) |
| 1642 |
self.assertEqual(math.pow(NINF, INF), INF) |
| 1643 |
self.assertEqual(math.pow(NINF, 3.), NINF) |
| 1644 |
self.assertEqual(math.pow(NINF, 2.3), INF) |
| 1645 |
self.assertEqual(math.pow(NINF, 2.), INF) |
| 1646 |
self.assertEqual(math.pow(NINF, 0.), 1.) |
| 1647 |
self.assertEqual(math.pow(NINF, -0.), 1.) |
| 1648 |
self.assertEqual(math.pow(NINF, -2.), 0.) |
| 1649 |
self.assertEqual(math.pow(NINF, -2.3), 0.) |
| 1650 |
self.assertEqual(math.pow(NINF, -3.), -0.) |
| 1651 |
self.assertEqual(math.pow(NINF, NINF), 0.) |
| 1652 |
self.assertTrue(math.isnan(math.pow(NINF, NAN))) |
| 1653 |
|
| 1654 |
# pow(-1, x) |
| 1655 |
self.assertEqual(math.pow(-1., INF), 1.) |
| 1656 |
self.assertEqual(math.pow(-1., 3.), -1.) |
| 1657 |
self.assertRaises(ValueError, math.pow, -1., 2.3) |
| 1658 |
self.assertEqual(math.pow(-1., 2.), 1.) |
| 1659 |
self.assertEqual(math.pow(-1., 0.), 1.) |
| 1660 |
self.assertEqual(math.pow(-1., -0.), 1.) |
| 1661 |
self.assertEqual(math.pow(-1., -2.), 1.) |
| 1662 |
self.assertRaises(ValueError, math.pow, -1., -2.3) |
| 1663 |
self.assertEqual(math.pow(-1., -3.), -1.) |
| 1664 |
self.assertEqual(math.pow(-1., NINF), 1.) |
| 1665 |
self.assertTrue(math.isnan(math.pow(-1., NAN))) |
| 1666 |
|
| 1667 |
# pow(1, x) |
| 1668 |
self.assertEqual(math.pow(1., INF), 1.) |
| 1669 |
self.assertEqual(math.pow(1., 3.), 1.) |
| 1670 |
self.assertEqual(math.pow(1., 2.3), 1.) |
| 1671 |
self.assertEqual(math.pow(1., 2.), 1.) |
| 1672 |
self.assertEqual(math.pow(1., 0.), 1.) |
| 1673 |
self.assertEqual(math.pow(1., -0.), 1.) |
| 1674 |
self.assertEqual(math.pow(1., -2.), 1.) |
| 1675 |
self.assertEqual(math.pow(1., -2.3), 1.) |
| 1676 |
self.assertEqual(math.pow(1., -3.), 1.) |
| 1677 |
self.assertEqual(math.pow(1., NINF), 1.) |
| 1678 |
self.assertEqual(math.pow(1., NAN), 1.) |
| 1679 |
|
| 1680 |
# pow(x, 0) should be 1 for any x |
| 1681 |
self.assertEqual(math.pow(2.3, 0.), 1.) |
| 1682 |
self.assertEqual(math.pow(-2.3, 0.), 1.) |
| 1683 |
self.assertEqual(math.pow(NAN, 0.), 1.) |
| 1684 |
self.assertEqual(math.pow(2.3, -0.), 1.) |
| 1685 |
self.assertEqual(math.pow(-2.3, -0.), 1.) |
| 1686 |
self.assertEqual(math.pow(NAN, -0.), 1.) |
| 1687 |
|
| 1688 |
# pow(x, y) is invalid if x is negative and y is not integral |
| 1689 |
self.assertRaises(ValueError, math.pow, -1., 2.3) |
| 1690 |
self.assertRaises(ValueError, math.pow, -15., -3.1) |
| 1691 |
|
| 1692 |
# pow(x, NINF) |
| 1693 |
self.assertEqual(math.pow(1.9, NINF), 0.) |
| 1694 |
self.assertEqual(math.pow(1.1, NINF), 0.) |
| 1695 |
self.assertEqual(math.pow(0.9, NINF), INF) |
| 1696 |
self.assertEqual(math.pow(0.1, NINF), INF) |
| 1697 |
self.assertEqual(math.pow(-0.1, NINF), INF) |
| 1698 |
self.assertEqual(math.pow(-0.9, NINF), INF) |
| 1699 |
self.assertEqual(math.pow(-1.1, NINF), 0.) |
| 1700 |
self.assertEqual(math.pow(-1.9, NINF), 0.) |
| 1701 |
|
| 1702 |
# pow(x, INF) |
| 1703 |
self.assertEqual(math.pow(1.9, INF), INF) |
| 1704 |
self.assertEqual(math.pow(1.1, INF), INF) |
| 1705 |
self.assertEqual(math.pow(0.9, INF), 0.) |
| 1706 |
self.assertEqual(math.pow(0.1, INF), 0.) |
| 1707 |
self.assertEqual(math.pow(-0.1, INF), 0.) |
| 1708 |
self.assertEqual(math.pow(-0.9, INF), 0.) |
| 1709 |
self.assertEqual(math.pow(-1.1, INF), INF) |
| 1710 |
self.assertEqual(math.pow(-1.9, INF), INF) |
| 1711 |
|
| 1712 |
# pow(x, y) should work for x negative, y an integer |
| 1713 |
self.ftest('(-2.)**3.', math.pow(-2.0, 3.0), -8.0) |
| 1714 |
self.ftest('(-2.)**2.', math.pow(-2.0, 2.0), 4.0) |
| 1715 |
self.ftest('(-2.)**1.', math.pow(-2.0, 1.0), -2.0) |
| 1716 |
self.ftest('(-2.)**0.', math.pow(-2.0, 0.0), 1.0) |
| 1717 |
self.ftest('(-2.)**-0.', math.pow(-2.0, -0.0), 1.0) |
| 1718 |
self.ftest('(-2.)**-1.', math.pow(-2.0, -1.0), -0.5) |
| 1719 |
self.ftest('(-2.)**-2.', math.pow(-2.0, -2.0), 0.25) |
| 1720 |
self.ftest('(-2.)**-3.', math.pow(-2.0, -3.0), -0.125) |
| 1721 |
self.assertRaises(ValueError, math.pow, -2.0, -0.5) |
| 1722 |
self.assertRaises(ValueError, math.pow, -2.0, 0.5) |
| 1723 |
|
| 1724 |
# the following tests have been commented out since they don't |
| 1725 |
# really belong here: the implementation of ** for floats is |
| 1726 |
# independent of the implementation of math.pow |
| 1727 |
#self.assertEqual(1**NAN, 1) |
| 1728 |
#self.assertEqual(1**INF, 1) |
| 1729 |
#self.assertEqual(1**NINF, 1) |
| 1730 |
#self.assertEqual(1**0, 1) |
| 1731 |
#self.assertEqual(1.**NAN, 1) |
| 1732 |
#self.assertEqual(1.**INF, 1) |
| 1733 |
#self.assertEqual(1.**NINF, 1) |
| 1734 |
#self.assertEqual(1.**0, 1) |
| 1735 |
|
| 1736 |
def testRadians(self): |
| 1737 |
self.assertRaises(TypeError, math.radians) |
| 1738 |
self.ftest('radians(180)', math.radians(180), math.pi) |
| 1739 |
self.ftest('radians(90)', math.radians(90), math.pi/2) |
| 1740 |
self.ftest('radians(-45)', math.radians(-45), -math.pi/4) |
| 1741 |
self.ftest('radians(0)', math.radians(0), 0) |
| 1742 |
|
| 1743 |
@requires_IEEE_754 |
| 1744 |
def testRemainder(self): |
| 1745 |
from fractions import Fraction |
| 1746 |
|
| 1747 |
def validate_spec(x, y, r): |
| 1748 |
""" |
| 1749 |
Check that r matches remainder(x, y) according to the IEEE 754 |
| 1750 |
specification. Assumes that x, y and r are finite and y is nonzero. |
| 1751 |
""" |
| 1752 |
fx, fy, fr = Fraction(x), Fraction(y), Fraction(r) |
| 1753 |
# r should not exceed y/2 in absolute value |
| 1754 |
self.assertLessEqual(abs(fr), abs(fy/2)) |
| 1755 |
# x - r should be an exact integer multiple of y |
| 1756 |
n = (fx - fr) / fy |
| 1757 |
self.assertEqual(n, int(n)) |
| 1758 |
if abs(fr) == abs(fy/2): |
| 1759 |
# If |r| == |y/2|, n should be even. |
| 1760 |
self.assertEqual(n/2, int(n/2)) |
| 1761 |
|
| 1762 |
# triples (x, y, remainder(x, y)) in hexadecimal form. |
| 1763 |
testcases = [ |
| 1764 |
# Remainders modulo 1, showing the ties-to-even behaviour. |
| 1765 |
'-4.0 1 -0.0', |
| 1766 |
'-3.8 1 0.8', |
| 1767 |
'-3.0 1 -0.0', |
| 1768 |
'-2.8 1 -0.8', |
| 1769 |
'-2.0 1 -0.0', |
| 1770 |
'-1.8 1 0.8', |
| 1771 |
'-1.0 1 -0.0', |
| 1772 |
'-0.8 1 -0.8', |
| 1773 |
'-0.0 1 -0.0', |
| 1774 |
' 0.0 1 0.0', |
| 1775 |
' 0.8 1 0.8', |
| 1776 |
' 1.0 1 0.0', |
| 1777 |
' 1.8 1 -0.8', |
| 1778 |
' 2.0 1 0.0', |
| 1779 |
' 2.8 1 0.8', |
| 1780 |
' 3.0 1 0.0', |
| 1781 |
' 3.8 1 -0.8', |
| 1782 |
' 4.0 1 0.0', |
| 1783 |
|
| 1784 |
# Reductions modulo 2*pi |
| 1785 |
'0x0.0p+0 0x1.921fb54442d18p+2 0x0.0p+0', |
| 1786 |
'0x1.921fb54442d18p+0 0x1.921fb54442d18p+2 0x1.921fb54442d18p+0', |
| 1787 |
'0x1.921fb54442d17p+1 0x1.921fb54442d18p+2 0x1.921fb54442d17p+1', |
| 1788 |
'0x1.921fb54442d18p+1 0x1.921fb54442d18p+2 0x1.921fb54442d18p+1', |
| 1789 |
'0x1.921fb54442d19p+1 0x1.921fb54442d18p+2 -0x1.921fb54442d17p+1', |
| 1790 |
'0x1.921fb54442d17p+2 0x1.921fb54442d18p+2 -0x0.0000000000001p+2', |
| 1791 |
'0x1.921fb54442d18p+2 0x1.921fb54442d18p+2 0x0p0', |
| 1792 |
'0x1.921fb54442d19p+2 0x1.921fb54442d18p+2 0x0.0000000000001p+2', |
| 1793 |
'0x1.2d97c7f3321d1p+3 0x1.921fb54442d18p+2 0x1.921fb54442d14p+1', |
| 1794 |
'0x1.2d97c7f3321d2p+3 0x1.921fb54442d18p+2 -0x1.921fb54442d18p+1', |
| 1795 |
'0x1.2d97c7f3321d3p+3 0x1.921fb54442d18p+2 -0x1.921fb54442d14p+1', |
| 1796 |
'0x1.921fb54442d17p+3 0x1.921fb54442d18p+2 -0x0.0000000000001p+3', |
| 1797 |
'0x1.921fb54442d18p+3 0x1.921fb54442d18p+2 0x0p0', |
| 1798 |
'0x1.921fb54442d19p+3 0x1.921fb54442d18p+2 0x0.0000000000001p+3', |
| 1799 |
'0x1.f6a7a2955385dp+3 0x1.921fb54442d18p+2 0x1.921fb54442d14p+1', |
| 1800 |
'0x1.f6a7a2955385ep+3 0x1.921fb54442d18p+2 0x1.921fb54442d18p+1', |
| 1801 |
'0x1.f6a7a2955385fp+3 0x1.921fb54442d18p+2 -0x1.921fb54442d14p+1', |
| 1802 |
'0x1.1475cc9eedf00p+5 0x1.921fb54442d18p+2 0x1.921fb54442d10p+1', |
| 1803 |
'0x1.1475cc9eedf01p+5 0x1.921fb54442d18p+2 -0x1.921fb54442d10p+1', |
| 1804 |
|
| 1805 |
# Symmetry with respect to signs. |
| 1806 |
' 1 0.c 0.4', |
| 1807 |
'-1 0.c -0.4', |
| 1808 |
' 1 -0.c 0.4', |
| 1809 |
'-1 -0.c -0.4', |
| 1810 |
' 1.4 0.c -0.4', |
| 1811 |
'-1.4 0.c 0.4', |
| 1812 |
' 1.4 -0.c -0.4', |
| 1813 |
'-1.4 -0.c 0.4', |
| 1814 |
|
| 1815 |
# Huge modulus, to check that the underlying algorithm doesn't |
| 1816 |
# rely on 2.0 * modulus being representable. |
| 1817 |
'0x1.dp+1023 0x1.4p+1023 0x0.9p+1023', |
| 1818 |
'0x1.ep+1023 0x1.4p+1023 -0x0.ap+1023', |
| 1819 |
'0x1.fp+1023 0x1.4p+1023 -0x0.9p+1023', |
| 1820 |
] |
| 1821 |
|
| 1822 |
for case in testcases: |
| 1823 |
with self.subTest(case=case): |
| 1824 |
x_hex, y_hex, expected_hex = case.split() |
| 1825 |
x = float.fromhex(x_hex) |
| 1826 |
y = float.fromhex(y_hex) |
| 1827 |
expected = float.fromhex(expected_hex) |
| 1828 |
validate_spec(x, y, expected) |
| 1829 |
actual = math.remainder(x, y) |
| 1830 |
# Cheap way of checking that the floats are |
| 1831 |
# as identical as we need them to be. |
| 1832 |
self.assertEqual(actual.hex(), expected.hex()) |
| 1833 |
|
| 1834 |
# Test tiny subnormal modulus: there's potential for |
| 1835 |
# getting the implementation wrong here (for example, |
| 1836 |
# by assuming that modulus/2 is exactly representable). |
| 1837 |
tiny = float.fromhex('1p-1074') # min +ve subnormal |
| 1838 |
for n in range(-25, 25): |
| 1839 |
if n == 0: |
| 1840 |
continue |
| 1841 |
y = n * tiny |
| 1842 |
for m in range(100): |
| 1843 |
x = m * tiny |
| 1844 |
actual = math.remainder(x, y) |
| 1845 |
validate_spec(x, y, actual) |
| 1846 |
actual = math.remainder(-x, y) |
| 1847 |
validate_spec(-x, y, actual) |
| 1848 |
|
| 1849 |
# Special values. |
| 1850 |
# NaNs should propagate as usual. |
| 1851 |
for value in [NAN, 0.0, -0.0, 2.0, -2.3, NINF, INF]: |
| 1852 |
self.assertIsNaN(math.remainder(NAN, value)) |
| 1853 |
self.assertIsNaN(math.remainder(value, NAN)) |
| 1854 |
|
| 1855 |
# remainder(x, inf) is x, for non-nan non-infinite x. |
| 1856 |
for value in [-2.3, -0.0, 0.0, 2.3]: |
| 1857 |
self.assertEqual(math.remainder(value, INF), value) |
| 1858 |
self.assertEqual(math.remainder(value, NINF), value) |
| 1859 |
|
| 1860 |
# remainder(x, 0) and remainder(infinity, x) for non-NaN x are invalid |
| 1861 |
# operations according to IEEE 754-2008 7.2(f), and should raise. |
| 1862 |
for value in [NINF, -2.3, -0.0, 0.0, 2.3, INF]: |
| 1863 |
with self.assertRaises(ValueError): |
| 1864 |
math.remainder(INF, value) |
| 1865 |
with self.assertRaises(ValueError): |
| 1866 |
math.remainder(NINF, value) |
| 1867 |
with self.assertRaises(ValueError): |
| 1868 |
math.remainder(value, 0.0) |
| 1869 |
with self.assertRaises(ValueError): |
| 1870 |
math.remainder(value, -0.0) |
| 1871 |
|
| 1872 |
def testSin(self): |
| 1873 |
self.assertRaises(TypeError, math.sin) |
| 1874 |
self.ftest('sin(0)', math.sin(0), 0) |
| 1875 |
self.ftest('sin(pi/2)', math.sin(math.pi/2), 1) |
| 1876 |
self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1) |
| 1877 |
try: |
| 1878 |
self.assertTrue(math.isnan(math.sin(INF))) |
| 1879 |
self.assertTrue(math.isnan(math.sin(NINF))) |
| 1880 |
except ValueError: |
| 1881 |
self.assertRaises(ValueError, math.sin, INF) |
| 1882 |
self.assertRaises(ValueError, math.sin, NINF) |
| 1883 |
self.assertTrue(math.isnan(math.sin(NAN))) |
| 1884 |
|
| 1885 |
def testSinh(self): |
| 1886 |
self.assertRaises(TypeError, math.sinh) |
| 1887 |
self.ftest('sinh(0)', math.sinh(0), 0) |
| 1888 |
self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1) |
| 1889 |
self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0) |
| 1890 |
self.assertEqual(math.sinh(INF), INF) |
| 1891 |
self.assertEqual(math.sinh(NINF), NINF) |
| 1892 |
self.assertTrue(math.isnan(math.sinh(NAN))) |
| 1893 |
|
| 1894 |
def testSqrt(self): |
| 1895 |
self.assertRaises(TypeError, math.sqrt) |
| 1896 |
self.ftest('sqrt(0)', math.sqrt(0), 0) |
| 1897 |
self.ftest('sqrt(0)', math.sqrt(0.0), 0.0) |
| 1898 |
self.ftest('sqrt(2.5)', math.sqrt(2.5), 1.5811388300841898) |
| 1899 |
self.ftest('sqrt(0.25)', math.sqrt(0.25), 0.5) |
| 1900 |
self.ftest('sqrt(25.25)', math.sqrt(25.25), 5.024937810560445) |
| 1901 |
self.ftest('sqrt(1)', math.sqrt(1), 1) |
| 1902 |
self.ftest('sqrt(4)', math.sqrt(4), 2) |
| 1903 |
self.assertEqual(math.sqrt(INF), INF) |
| 1904 |
self.assertRaises(ValueError, math.sqrt, -1) |
| 1905 |
self.assertRaises(ValueError, math.sqrt, NINF) |
| 1906 |
self.assertTrue(math.isnan(math.sqrt(NAN))) |
| 1907 |
|
| 1908 |
def testTan(self): |
| 1909 |
self.assertRaises(TypeError, math.tan) |
| 1910 |
self.ftest('tan(0)', math.tan(0), 0) |
| 1911 |
self.ftest('tan(pi/4)', math.tan(math.pi/4), 1) |
| 1912 |
self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1) |
| 1913 |
try: |
| 1914 |
self.assertTrue(math.isnan(math.tan(INF))) |
| 1915 |
self.assertTrue(math.isnan(math.tan(NINF))) |
| 1916 |
except ValueError: |
| 1917 |
self.assertRaises(ValueError, math.tan, INF) |
| 1918 |
self.assertRaises(ValueError, math.tan, NINF) |
| 1919 |
self.assertTrue(math.isnan(math.tan(NAN))) |
| 1920 |
|
| 1921 |
def testTanh(self): |
| 1922 |
self.assertRaises(TypeError, math.tanh) |
| 1923 |
self.ftest('tanh(0)', math.tanh(0), 0) |
| 1924 |
self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0, |
| 1925 |
abs_tol=math.ulp(1)) |
| 1926 |
self.ftest('tanh(inf)', math.tanh(INF), 1) |
| 1927 |
self.ftest('tanh(-inf)', math.tanh(NINF), -1) |
| 1928 |
self.assertTrue(math.isnan(math.tanh(NAN))) |
| 1929 |
|
| 1930 |
@requires_IEEE_754 |
| 1931 |
def testTanhSign(self): |
| 1932 |
# check that tanh(-0.) == -0. on IEEE 754 systems |
| 1933 |
self.assertEqual(math.tanh(-0.), -0.) |
| 1934 |
self.assertEqual(math.copysign(1., math.tanh(-0.)), |
| 1935 |
math.copysign(1., -0.)) |
| 1936 |
|
| 1937 |
def test_trunc(self): |
| 1938 |
self.assertEqual(math.trunc(1), 1) |
| 1939 |
self.assertEqual(math.trunc(-1), -1) |
| 1940 |
self.assertEqual(type(math.trunc(1)), int) |
| 1941 |
self.assertEqual(type(math.trunc(1.5)), int) |
| 1942 |
self.assertEqual(math.trunc(1.5), 1) |
| 1943 |
self.assertEqual(math.trunc(-1.5), -1) |
| 1944 |
self.assertEqual(math.trunc(1.999999), 1) |
| 1945 |
self.assertEqual(math.trunc(-1.999999), -1) |
| 1946 |
self.assertEqual(math.trunc(-0.999999), -0) |
| 1947 |
self.assertEqual(math.trunc(-100.999), -100) |
| 1948 |
|
| 1949 |
class TestTrunc: |
| 1950 |
def __trunc__(self): |
| 1951 |
return 23 |
| 1952 |
class FloatTrunc(float): |
| 1953 |
def __trunc__(self): |
| 1954 |
return 23 |
| 1955 |
class TestNoTrunc: |
| 1956 |
pass |
| 1957 |
class TestBadTrunc: |
| 1958 |
__trunc__ = BadDescr() |
| 1959 |
|
| 1960 |
self.assertEqual(math.trunc(TestTrunc()), 23) |
| 1961 |
self.assertEqual(math.trunc(FloatTrunc()), 23) |
| 1962 |
|
| 1963 |
self.assertRaises(TypeError, math.trunc) |
| 1964 |
self.assertRaises(TypeError, math.trunc, 1, 2) |
| 1965 |
self.assertRaises(TypeError, math.trunc, FloatLike(23.5)) |
| 1966 |
self.assertRaises(TypeError, math.trunc, TestNoTrunc()) |
| 1967 |
self.assertRaises(ValueError, math.trunc, TestBadTrunc()) |
| 1968 |
|
| 1969 |
def testIsfinite(self): |
| 1970 |
self.assertTrue(math.isfinite(0.0)) |
| 1971 |
self.assertTrue(math.isfinite(-0.0)) |
| 1972 |
self.assertTrue(math.isfinite(1.0)) |
| 1973 |
self.assertTrue(math.isfinite(-1.0)) |
| 1974 |
self.assertFalse(math.isfinite(float("nan"))) |
| 1975 |
self.assertFalse(math.isfinite(float("inf"))) |
| 1976 |
self.assertFalse(math.isfinite(float("-inf"))) |
| 1977 |
|
| 1978 |
def testIsnan(self): |
| 1979 |
self.assertTrue(math.isnan(float("nan"))) |
| 1980 |
self.assertTrue(math.isnan(float("-nan"))) |
| 1981 |
self.assertTrue(math.isnan(float("inf") * 0.)) |
| 1982 |
self.assertFalse(math.isnan(float("inf"))) |
| 1983 |
self.assertFalse(math.isnan(0.)) |
| 1984 |
self.assertFalse(math.isnan(1.)) |
| 1985 |
|
| 1986 |
def testIsinf(self): |
| 1987 |
self.assertTrue(math.isinf(float("inf"))) |
| 1988 |
self.assertTrue(math.isinf(float("-inf"))) |
| 1989 |
self.assertTrue(math.isinf(1E400)) |
| 1990 |
self.assertTrue(math.isinf(-1E400)) |
| 1991 |
self.assertFalse(math.isinf(float("nan"))) |
| 1992 |
self.assertFalse(math.isinf(0.)) |
| 1993 |
self.assertFalse(math.isinf(1.)) |
| 1994 |
|
| 1995 |
def test_nan_constant(self): |
| 1996 |
# `math.nan` must be a quiet NaN with positive sign bit |
| 1997 |
self.assertTrue(math.isnan(math.nan)) |
| 1998 |
self.assertEqual(math.copysign(1., math.nan), 1.) |
| 1999 |
|
| 2000 |
def test_inf_constant(self): |
| 2001 |
self.assertTrue(math.isinf(math.inf)) |
| 2002 |
self.assertGreater(math.inf, 0.0) |
| 2003 |
self.assertEqual(math.inf, float("inf")) |
| 2004 |
self.assertEqual(-math.inf, float("-inf")) |
| 2005 |
|
| 2006 |
# RED_FLAG 16-Oct-2000 Tim |
| 2007 |
# While 2.0 is more consistent about exceptions than previous releases, it |
| 2008 |
# still fails this part of the test on some platforms. For now, we only |
| 2009 |
# *run* test_exceptions() in verbose mode, so that this isn't normally |
| 2010 |
# tested. |
| 2011 |
@unittest.skipUnless(verbose, 'requires verbose mode') |
| 2012 |
def test_exceptions(self): |
| 2013 |
try: |
| 2014 |
x = math.exp(-1000000000) |
| 2015 |
except: |
| 2016 |
# mathmodule.c is failing to weed out underflows from libm, or |
| 2017 |
# we've got an fp format with huge dynamic range |
| 2018 |
self.fail("underflowing exp() should not have raised " |
| 2019 |
"an exception") |
| 2020 |
if x != 0: |
| 2021 |
self.fail("underflowing exp() should have returned 0") |
| 2022 |
|
| 2023 |
# If this fails, probably using a strict IEEE-754 conforming libm, and x |
| 2024 |
# is +Inf afterwards. But Python wants overflows detected by default. |
| 2025 |
try: |
| 2026 |
x = math.exp(1000000000) |
| 2027 |
except OverflowError: |
| 2028 |
pass |
| 2029 |
else: |
| 2030 |
self.fail("overflowing exp() didn't trigger OverflowError") |
| 2031 |
|
| 2032 |
# If this fails, it could be a puzzle. One odd possibility is that |
| 2033 |
# mathmodule.c's macros are getting confused while comparing |
| 2034 |
# Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE |
| 2035 |
# as a result (and so raising OverflowError instead). |
| 2036 |
try: |
| 2037 |
x = math.sqrt(-1.0) |
| 2038 |
except ValueError: |
| 2039 |
pass |
| 2040 |
else: |
| 2041 |
self.fail("sqrt(-1) didn't raise ValueError") |
| 2042 |
|
| 2043 |
@requires_IEEE_754 |
| 2044 |
def test_testfile(self): |
| 2045 |
# Some tests need to be skipped on ancient OS X versions. |
| 2046 |
# See issue #27953. |
| 2047 |
SKIP_ON_TIGER = {'tan0064'} |
| 2048 |
|
| 2049 |
osx_version = None |
| 2050 |
if sys.platform == 'darwin': |
| 2051 |
version_txt = platform.mac_ver()[0] |
| 2052 |
try: |
| 2053 |
osx_version = tuple(map(int, version_txt.split('.'))) |
| 2054 |
except ValueError: |
| 2055 |
pass |
| 2056 |
|
| 2057 |
fail_fmt = "{}: {}({!r}): {}" |
| 2058 |
|
| 2059 |
failures = [] |
| 2060 |
for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file): |
| 2061 |
# Skip if either the input or result is complex |
| 2062 |
if ai != 0.0 or ei != 0.0: |
| 2063 |
continue |
| 2064 |
if fn in ['rect', 'polar']: |
| 2065 |
# no real versions of rect, polar |
| 2066 |
continue |
| 2067 |
# Skip certain tests on OS X 10.4. |
| 2068 |
if osx_version is not None and osx_version < (10, 5): |
| 2069 |
if id in SKIP_ON_TIGER: |
| 2070 |
continue |
| 2071 |
|
| 2072 |
func = getattr(math, fn) |
| 2073 |
|
| 2074 |
if 'invalid' in flags or 'divide-by-zero' in flags: |
| 2075 |
er = 'ValueError' |
| 2076 |
elif 'overflow' in flags: |
| 2077 |
er = 'OverflowError' |
| 2078 |
|
| 2079 |
try: |
| 2080 |
result = func(ar) |
| 2081 |
except ValueError: |
| 2082 |
result = 'ValueError' |
| 2083 |
except OverflowError: |
| 2084 |
result = 'OverflowError' |
| 2085 |
|
| 2086 |
# C99+ says for math.h's sqrt: If the argument is +∞ or ±0, it is |
| 2087 |
# returned, unmodified. On another hand, for csqrt: If z is ±0+0i, |
| 2088 |
# the result is +0+0i. Lets correct zero sign of er to follow |
| 2089 |
# first convention. |
| 2090 |
if id in ['sqrt0002', 'sqrt0003', 'sqrt1001', 'sqrt1023']: |
| 2091 |
er = math.copysign(er, ar) |
| 2092 |
|
| 2093 |
# Default tolerances |
| 2094 |
ulp_tol, abs_tol = 5, 0.0 |
| 2095 |
|
| 2096 |
failure = result_check(er, result, ulp_tol, abs_tol) |
| 2097 |
if failure is None: |
| 2098 |
continue |
| 2099 |
|
| 2100 |
msg = fail_fmt.format(id, fn, ar, failure) |
| 2101 |
failures.append(msg) |
| 2102 |
|
| 2103 |
if failures: |
| 2104 |
self.fail('Failures in test_testfile:\n ' + |
| 2105 |
'\n '.join(failures)) |
| 2106 |
|
| 2107 |
@requires_IEEE_754 |
| 2108 |
def test_mtestfile(self): |
| 2109 |
fail_fmt = "{}: {}({!r}): {}" |
| 2110 |
|
| 2111 |
failures = [] |
| 2112 |
for id, fn, arg, expected, flags in parse_mtestfile(math_testcases): |
| 2113 |
func = getattr(math, fn) |
| 2114 |
|
| 2115 |
if 'invalid' in flags or 'divide-by-zero' in flags: |
| 2116 |
expected = 'ValueError' |
| 2117 |
elif 'overflow' in flags: |
| 2118 |
expected = 'OverflowError' |
| 2119 |
|
| 2120 |
try: |
| 2121 |
got = func(arg) |
| 2122 |
except ValueError: |
| 2123 |
got = 'ValueError' |
| 2124 |
except OverflowError: |
| 2125 |
got = 'OverflowError' |
| 2126 |
|
| 2127 |
# Default tolerances |
| 2128 |
ulp_tol, abs_tol = 5, 0.0 |
| 2129 |
|
| 2130 |
# Exceptions to the defaults |
| 2131 |
if fn == 'gamma': |
| 2132 |
# Experimental results on one platform gave |
| 2133 |
# an accuracy of <= 10 ulps across the entire float |
| 2134 |
# domain. We weaken that to require 20 ulp accuracy. |
| 2135 |
ulp_tol = 20 |
| 2136 |
|
| 2137 |
elif fn == 'lgamma': |
| 2138 |
# we use a weaker accuracy test for lgamma; |
| 2139 |
# lgamma only achieves an absolute error of |
| 2140 |
# a few multiples of the machine accuracy, in |
| 2141 |
# general. |
| 2142 |
abs_tol = 1e-15 |
| 2143 |
|
| 2144 |
elif fn == 'erfc' and arg >= 0.0: |
| 2145 |
# erfc has less-than-ideal accuracy for large |
| 2146 |
# arguments (x ~ 25 or so), mainly due to the |
| 2147 |
# error involved in computing exp(-x*x). |
| 2148 |
# |
| 2149 |
# Observed between CPython and mpmath at 25 dp: |
| 2150 |
# x < 0 : err <= 2 ulp |
| 2151 |
# 0 <= x < 1 : err <= 10 ulp |
| 2152 |
# 1 <= x < 10 : err <= 100 ulp |
| 2153 |
# 10 <= x < 20 : err <= 300 ulp |
| 2154 |
# 20 <= x : < 600 ulp |
| 2155 |
# |
| 2156 |
if arg < 1.0: |
| 2157 |
ulp_tol = 10 |
| 2158 |
elif arg < 10.0: |
| 2159 |
ulp_tol = 100 |
| 2160 |
else: |
| 2161 |
ulp_tol = 1000 |
| 2162 |
|
| 2163 |
failure = result_check(expected, got, ulp_tol, abs_tol) |
| 2164 |
if failure is None: |
| 2165 |
continue |
| 2166 |
|
| 2167 |
msg = fail_fmt.format(id, fn, arg, failure) |
| 2168 |
failures.append(msg) |
| 2169 |
|
| 2170 |
if failures: |
| 2171 |
self.fail('Failures in test_mtestfile:\n ' + |
| 2172 |
'\n '.join(failures)) |
| 2173 |
|
| 2174 |
def test_prod(self): |
| 2175 |
from fractions import Fraction as F |
| 2176 |
|
| 2177 |
prod = math.prod |
| 2178 |
self.assertEqual(prod([]), 1) |
| 2179 |
self.assertEqual(prod([], start=5), 5) |
| 2180 |
self.assertEqual(prod(list(range(2,8))), 5040) |
| 2181 |
self.assertEqual(prod(iter(list(range(2,8)))), 5040) |
| 2182 |
self.assertEqual(prod(range(1, 10), start=10), 3628800) |
| 2183 |
|
| 2184 |
self.assertEqual(prod([1, 2, 3, 4, 5]), 120) |
| 2185 |
self.assertEqual(prod([1.0, 2.0, 3.0, 4.0, 5.0]), 120.0) |
| 2186 |
self.assertEqual(prod([1, 2, 3, 4.0, 5.0]), 120.0) |
| 2187 |
self.assertEqual(prod([1.0, 2.0, 3.0, 4, 5]), 120.0) |
| 2188 |
self.assertEqual(prod([1., F(3, 2)]), 1.5) |
| 2189 |
|
| 2190 |
# Error in multiplication |
| 2191 |
class BadMultiply: |
| 2192 |
def __rmul__(self, other): |
| 2193 |
raise RuntimeError |
| 2194 |
with self.assertRaises(RuntimeError): |
| 2195 |
prod([10., BadMultiply()]) |
| 2196 |
|
| 2197 |
# Test overflow in fast-path for integers |
| 2198 |
self.assertEqual(prod([1, 1, 2**32, 1, 1]), 2**32) |
| 2199 |
# Test overflow in fast-path for floats |
| 2200 |
self.assertEqual(prod([1.0, 1.0, 2**32, 1, 1]), float(2**32)) |
| 2201 |
|
| 2202 |
self.assertRaises(TypeError, prod) |
| 2203 |
self.assertRaises(TypeError, prod, 42) |
| 2204 |
self.assertRaises(TypeError, prod, ['a', 'b', 'c']) |
| 2205 |
self.assertRaises(TypeError, prod, ['a', 'b', 'c'], start='') |
| 2206 |
self.assertRaises(TypeError, prod, [b'a', b'c'], start=b'') |
| 2207 |
values = [bytearray(b'a'), bytearray(b'b')] |
| 2208 |
self.assertRaises(TypeError, prod, values, start=bytearray(b'')) |
| 2209 |
self.assertRaises(TypeError, prod, [[1], [2], [3]]) |
| 2210 |
self.assertRaises(TypeError, prod, [{2:3}]) |
| 2211 |
self.assertRaises(TypeError, prod, [{2:3}]*2, start={2:3}) |
| 2212 |
self.assertRaises(TypeError, prod, [[1], [2], [3]], start=[]) |
| 2213 |
|
| 2214 |
# Some odd cases |
| 2215 |
self.assertEqual(prod([2, 3], start='ab'), 'abababababab') |
| 2216 |
self.assertEqual(prod([2, 3], start=[1, 2]), [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]) |
| 2217 |
self.assertEqual(prod([], start={2: 3}), {2:3}) |
| 2218 |
|
| 2219 |
with self.assertRaises(TypeError): |
| 2220 |
prod([10, 20], 1) # start is a keyword-only argument |
| 2221 |
|
| 2222 |
self.assertEqual(prod([0, 1, 2, 3]), 0) |
| 2223 |
self.assertEqual(prod([1, 0, 2, 3]), 0) |
| 2224 |
self.assertEqual(prod([1, 2, 3, 0]), 0) |
| 2225 |
|
| 2226 |
def _naive_prod(iterable, start=1): |
| 2227 |
for elem in iterable: |
| 2228 |
start *= elem |
| 2229 |
return start |
| 2230 |
|
| 2231 |
# Big integers |
| 2232 |
|
| 2233 |
iterable = range(1, 10000) |
| 2234 |
self.assertEqual(prod(iterable), _naive_prod(iterable)) |
| 2235 |
iterable = range(-10000, -1) |
| 2236 |
self.assertEqual(prod(iterable), _naive_prod(iterable)) |
| 2237 |
iterable = range(-1000, 1000) |
| 2238 |
self.assertEqual(prod(iterable), 0) |
| 2239 |
|
| 2240 |
# Big floats |
| 2241 |
|
| 2242 |
iterable = [float(x) for x in range(1, 1000)] |
| 2243 |
self.assertEqual(prod(iterable), _naive_prod(iterable)) |
| 2244 |
iterable = [float(x) for x in range(-1000, -1)] |
| 2245 |
self.assertEqual(prod(iterable), _naive_prod(iterable)) |
| 2246 |
iterable = [float(x) for x in range(-1000, 1000)] |
| 2247 |
self.assertIsNaN(prod(iterable)) |
| 2248 |
|
| 2249 |
# Float tests |
| 2250 |
|
| 2251 |
self.assertIsNaN(prod([1, 2, 3, float("nan"), 2, 3])) |
| 2252 |
self.assertIsNaN(prod([1, 0, float("nan"), 2, 3])) |
| 2253 |
self.assertIsNaN(prod([1, float("nan"), 0, 3])) |
| 2254 |
self.assertIsNaN(prod([1, float("inf"), float("nan"),3])) |
| 2255 |
self.assertIsNaN(prod([1, float("-inf"), float("nan"),3])) |
| 2256 |
self.assertIsNaN(prod([1, float("nan"), float("inf"),3])) |
| 2257 |
self.assertIsNaN(prod([1, float("nan"), float("-inf"),3])) |
| 2258 |
|
| 2259 |
self.assertEqual(prod([1, 2, 3, float('inf'),-3,4]), float('-inf')) |
| 2260 |
self.assertEqual(prod([1, 2, 3, float('-inf'),-3,4]), float('inf')) |
| 2261 |
|
| 2262 |
self.assertIsNaN(prod([1,2,0,float('inf'), -3, 4])) |
| 2263 |
self.assertIsNaN(prod([1,2,0,float('-inf'), -3, 4])) |
| 2264 |
self.assertIsNaN(prod([1, 2, 3, float('inf'), -3, 0, 3])) |
| 2265 |
self.assertIsNaN(prod([1, 2, 3, float('-inf'), -3, 0, 2])) |
| 2266 |
|
| 2267 |
# Type preservation |
| 2268 |
|
| 2269 |
self.assertEqual(type(prod([1, 2, 3, 4, 5, 6])), int) |
| 2270 |
self.assertEqual(type(prod([1, 2.0, 3, 4, 5, 6])), float) |
| 2271 |
self.assertEqual(type(prod(range(1, 10000))), int) |
| 2272 |
self.assertEqual(type(prod(range(1, 10000), start=1.0)), float) |
| 2273 |
self.assertEqual(type(prod([1, decimal.Decimal(2.0), 3, 4, 5, 6])), |
| 2274 |
decimal.Decimal) |
| 2275 |
|
| 2276 |
def testPerm(self): |
| 2277 |
perm = math.perm |
| 2278 |
factorial = math.factorial |
| 2279 |
# Test if factorial definition is satisfied |
| 2280 |
for n in range(500): |
| 2281 |
for k in (range(n + 1) if n < 100 else range(30) if n < 200 else range(10)): |
| 2282 |
self.assertEqual(perm(n, k), |
| 2283 |
factorial(n) // factorial(n - k)) |
| 2284 |
|
| 2285 |
# Test for Pascal's identity |
| 2286 |
for n in range(1, 100): |
| 2287 |
for k in range(1, n): |
| 2288 |
self.assertEqual(perm(n, k), perm(n - 1, k - 1) * k + perm(n - 1, k)) |
| 2289 |
|
| 2290 |
# Test corner cases |
| 2291 |
for n in range(1, 100): |
| 2292 |
self.assertEqual(perm(n, 0), 1) |
| 2293 |
self.assertEqual(perm(n, 1), n) |
| 2294 |
self.assertEqual(perm(n, n), factorial(n)) |
| 2295 |
|
| 2296 |
# Test one argument form |
| 2297 |
for n in range(20): |
| 2298 |
self.assertEqual(perm(n), factorial(n)) |
| 2299 |
self.assertEqual(perm(n, None), factorial(n)) |
| 2300 |
|
| 2301 |
# Raises TypeError if any argument is non-integer or argument count is |
| 2302 |
# not 1 or 2 |
| 2303 |
self.assertRaises(TypeError, perm, 10, 1.0) |
| 2304 |
self.assertRaises(TypeError, perm, 10, decimal.Decimal(1.0)) |
| 2305 |
self.assertRaises(TypeError, perm, 10, "1") |
| 2306 |
self.assertRaises(TypeError, perm, 10.0, 1) |
| 2307 |
self.assertRaises(TypeError, perm, decimal.Decimal(10.0), 1) |
| 2308 |
self.assertRaises(TypeError, perm, "10", 1) |
| 2309 |
|
| 2310 |
self.assertRaises(TypeError, perm) |
| 2311 |
self.assertRaises(TypeError, perm, 10, 1, 3) |
| 2312 |
self.assertRaises(TypeError, perm) |
| 2313 |
|
| 2314 |
# Raises Value error if not k or n are negative numbers |
| 2315 |
self.assertRaises(ValueError, perm, -1, 1) |
| 2316 |
self.assertRaises(ValueError, perm, -2**1000, 1) |
| 2317 |
self.assertRaises(ValueError, perm, 1, -1) |
| 2318 |
self.assertRaises(ValueError, perm, 1, -2**1000) |
| 2319 |
|
| 2320 |
# Returns zero if k is greater than n |
| 2321 |
self.assertEqual(perm(1, 2), 0) |
| 2322 |
self.assertEqual(perm(1, 2**1000), 0) |
| 2323 |
|
| 2324 |
n = 2**1000 |
| 2325 |
self.assertEqual(perm(n, 0), 1) |
| 2326 |
self.assertEqual(perm(n, 1), n) |
| 2327 |
self.assertEqual(perm(n, 2), n * (n-1)) |
| 2328 |
if support.check_impl_detail(cpython=True): |
| 2329 |
self.assertRaises(OverflowError, perm, n, n) |
| 2330 |
|
| 2331 |
for n, k in (True, True), (True, False), (False, False): |
| 2332 |
self.assertEqual(perm(n, k), 1) |
| 2333 |
self.assertIs(type(perm(n, k)), int) |
| 2334 |
self.assertEqual(perm(IntSubclass(5), IntSubclass(2)), 20) |
| 2335 |
self.assertEqual(perm(MyIndexable(5), MyIndexable(2)), 20) |
| 2336 |
for k in range(3): |
| 2337 |
self.assertIs(type(perm(IntSubclass(5), IntSubclass(k))), int) |
| 2338 |
self.assertIs(type(perm(MyIndexable(5), MyIndexable(k))), int) |
| 2339 |
|
| 2340 |
def testComb(self): |
| 2341 |
comb = math.comb |
| 2342 |
factorial = math.factorial |
| 2343 |
# Test if factorial definition is satisfied |
| 2344 |
for n in range(500): |
| 2345 |
for k in (range(n + 1) if n < 100 else range(30) if n < 200 else range(10)): |
| 2346 |
self.assertEqual(comb(n, k), factorial(n) |
| 2347 |
// (factorial(k) * factorial(n - k))) |
| 2348 |
|
| 2349 |
# Test for Pascal's identity |
| 2350 |
for n in range(1, 100): |
| 2351 |
for k in range(1, n): |
| 2352 |
self.assertEqual(comb(n, k), comb(n - 1, k - 1) + comb(n - 1, k)) |
| 2353 |
|
| 2354 |
# Test corner cases |
| 2355 |
for n in range(100): |
| 2356 |
self.assertEqual(comb(n, 0), 1) |
| 2357 |
self.assertEqual(comb(n, n), 1) |
| 2358 |
|
| 2359 |
for n in range(1, 100): |
| 2360 |
self.assertEqual(comb(n, 1), n) |
| 2361 |
self.assertEqual(comb(n, n - 1), n) |
| 2362 |
|
| 2363 |
# Test Symmetry |
| 2364 |
for n in range(100): |
| 2365 |
for k in range(n // 2): |
| 2366 |
self.assertEqual(comb(n, k), comb(n, n - k)) |
| 2367 |
|
| 2368 |
# Raises TypeError if any argument is non-integer or argument count is |
| 2369 |
# not 2 |
| 2370 |
self.assertRaises(TypeError, comb, 10, 1.0) |
| 2371 |
self.assertRaises(TypeError, comb, 10, decimal.Decimal(1.0)) |
| 2372 |
self.assertRaises(TypeError, comb, 10, "1") |
| 2373 |
self.assertRaises(TypeError, comb, 10.0, 1) |
| 2374 |
self.assertRaises(TypeError, comb, decimal.Decimal(10.0), 1) |
| 2375 |
self.assertRaises(TypeError, comb, "10", 1) |
| 2376 |
|
| 2377 |
self.assertRaises(TypeError, comb, 10) |
| 2378 |
self.assertRaises(TypeError, comb, 10, 1, 3) |
| 2379 |
self.assertRaises(TypeError, comb) |
| 2380 |
|
| 2381 |
# Raises Value error if not k or n are negative numbers |
| 2382 |
self.assertRaises(ValueError, comb, -1, 1) |
| 2383 |
self.assertRaises(ValueError, comb, -2**1000, 1) |
| 2384 |
self.assertRaises(ValueError, comb, 1, -1) |
| 2385 |
self.assertRaises(ValueError, comb, 1, -2**1000) |
| 2386 |
|
| 2387 |
# Returns zero if k is greater than n |
| 2388 |
self.assertEqual(comb(1, 2), 0) |
| 2389 |
self.assertEqual(comb(1, 2**1000), 0) |
| 2390 |
|
| 2391 |
n = 2**1000 |
| 2392 |
self.assertEqual(comb(n, 0), 1) |
| 2393 |
self.assertEqual(comb(n, 1), n) |
| 2394 |
self.assertEqual(comb(n, 2), n * (n-1) // 2) |
| 2395 |
self.assertEqual(comb(n, n), 1) |
| 2396 |
self.assertEqual(comb(n, n-1), n) |
| 2397 |
self.assertEqual(comb(n, n-2), n * (n-1) // 2) |
| 2398 |
if support.check_impl_detail(cpython=True): |
| 2399 |
self.assertRaises(OverflowError, comb, n, n//2) |
| 2400 |
|
| 2401 |
for n, k in (True, True), (True, False), (False, False): |
| 2402 |
self.assertEqual(comb(n, k), 1) |
| 2403 |
self.assertIs(type(comb(n, k)), int) |
| 2404 |
self.assertEqual(comb(IntSubclass(5), IntSubclass(2)), 10) |
| 2405 |
self.assertEqual(comb(MyIndexable(5), MyIndexable(2)), 10) |
| 2406 |
for k in range(3): |
| 2407 |
self.assertIs(type(comb(IntSubclass(5), IntSubclass(k))), int) |
| 2408 |
self.assertIs(type(comb(MyIndexable(5), MyIndexable(k))), int) |
| 2409 |
|
| 2410 |
@requires_IEEE_754 |
| 2411 |
def test_nextafter(self): |
| 2412 |
# around 2^52 and 2^63 |
| 2413 |
self.assertEqual(math.nextafter(4503599627370496.0, -INF), |
| 2414 |
4503599627370495.5) |
| 2415 |
self.assertEqual(math.nextafter(4503599627370496.0, INF), |
| 2416 |
4503599627370497.0) |
| 2417 |
self.assertEqual(math.nextafter(9223372036854775808.0, 0.0), |
| 2418 |
9223372036854774784.0) |
| 2419 |
self.assertEqual(math.nextafter(-9223372036854775808.0, 0.0), |
| 2420 |
-9223372036854774784.0) |
| 2421 |
|
| 2422 |
# around 1.0 |
| 2423 |
self.assertEqual(math.nextafter(1.0, -INF), |
| 2424 |
float.fromhex('0x1.fffffffffffffp-1')) |
| 2425 |
self.assertEqual(math.nextafter(1.0, INF), |
| 2426 |
float.fromhex('0x1.0000000000001p+0')) |
| 2427 |
self.assertEqual(math.nextafter(1.0, -INF, steps=1), |
| 2428 |
float.fromhex('0x1.fffffffffffffp-1')) |
| 2429 |
self.assertEqual(math.nextafter(1.0, INF, steps=1), |
| 2430 |
float.fromhex('0x1.0000000000001p+0')) |
| 2431 |
self.assertEqual(math.nextafter(1.0, -INF, steps=3), |
| 2432 |
float.fromhex('0x1.ffffffffffffdp-1')) |
| 2433 |
self.assertEqual(math.nextafter(1.0, INF, steps=3), |
| 2434 |
float.fromhex('0x1.0000000000003p+0')) |
| 2435 |
|
| 2436 |
# x == y: y is returned |
| 2437 |
for steps in range(1, 5): |
| 2438 |
self.assertEqual(math.nextafter(2.0, 2.0, steps=steps), 2.0) |
| 2439 |
self.assertEqualSign(math.nextafter(-0.0, +0.0, steps=steps), +0.0) |
| 2440 |
self.assertEqualSign(math.nextafter(+0.0, -0.0, steps=steps), -0.0) |
| 2441 |
|
| 2442 |
# around 0.0 |
| 2443 |
smallest_subnormal = sys.float_info.min * sys.float_info.epsilon |
| 2444 |
self.assertEqual(math.nextafter(+0.0, INF), smallest_subnormal) |
| 2445 |
self.assertEqual(math.nextafter(-0.0, INF), smallest_subnormal) |
| 2446 |
self.assertEqual(math.nextafter(+0.0, -INF), -smallest_subnormal) |
| 2447 |
self.assertEqual(math.nextafter(-0.0, -INF), -smallest_subnormal) |
| 2448 |
self.assertEqualSign(math.nextafter(smallest_subnormal, +0.0), +0.0) |
| 2449 |
self.assertEqualSign(math.nextafter(-smallest_subnormal, +0.0), -0.0) |
| 2450 |
self.assertEqualSign(math.nextafter(smallest_subnormal, -0.0), +0.0) |
| 2451 |
self.assertEqualSign(math.nextafter(-smallest_subnormal, -0.0), -0.0) |
| 2452 |
|
| 2453 |
# around infinity |
| 2454 |
largest_normal = sys.float_info.max |
| 2455 |
self.assertEqual(math.nextafter(INF, 0.0), largest_normal) |
| 2456 |
self.assertEqual(math.nextafter(-INF, 0.0), -largest_normal) |
| 2457 |
self.assertEqual(math.nextafter(largest_normal, INF), INF) |
| 2458 |
self.assertEqual(math.nextafter(-largest_normal, -INF), -INF) |
| 2459 |
|
| 2460 |
# NaN |
| 2461 |
self.assertIsNaN(math.nextafter(NAN, 1.0)) |
| 2462 |
self.assertIsNaN(math.nextafter(1.0, NAN)) |
| 2463 |
self.assertIsNaN(math.nextafter(NAN, NAN)) |
| 2464 |
|
| 2465 |
self.assertEqual(1.0, math.nextafter(1.0, INF, steps=0)) |
| 2466 |
with self.assertRaises(ValueError): |
| 2467 |
math.nextafter(1.0, INF, steps=-1) |
| 2468 |
|
| 2469 |
|
| 2470 |
@requires_IEEE_754 |
| 2471 |
def test_ulp(self): |
| 2472 |
self.assertEqual(math.ulp(1.0), sys.float_info.epsilon) |
| 2473 |
# use int ** int rather than float ** int to not rely on pow() accuracy |
| 2474 |
self.assertEqual(math.ulp(2 ** 52), 1.0) |
| 2475 |
self.assertEqual(math.ulp(2 ** 53), 2.0) |
| 2476 |
self.assertEqual(math.ulp(2 ** 64), 4096.0) |
| 2477 |
|
| 2478 |
# min and max |
| 2479 |
self.assertEqual(math.ulp(0.0), |
| 2480 |
sys.float_info.min * sys.float_info.epsilon) |
| 2481 |
self.assertEqual(math.ulp(FLOAT_MAX), |
| 2482 |
FLOAT_MAX - math.nextafter(FLOAT_MAX, -INF)) |
| 2483 |
|
| 2484 |
# special cases |
| 2485 |
self.assertEqual(math.ulp(INF), INF) |
| 2486 |
self.assertIsNaN(math.ulp(math.nan)) |
| 2487 |
|
| 2488 |
# negative number: ulp(-x) == ulp(x) |
| 2489 |
for x in (0.0, 1.0, 2 ** 52, 2 ** 64, INF): |
| 2490 |
with self.subTest(x=x): |
| 2491 |
self.assertEqual(math.ulp(-x), math.ulp(x)) |
| 2492 |
|
| 2493 |
def test_issue39871(self): |
| 2494 |
# A SystemError should not be raised if the first arg to atan2(), |
| 2495 |
# copysign(), or remainder() cannot be converted to a float. |
| 2496 |
class F: |
| 2497 |
def __float__(self): |
| 2498 |
self.converted = True |
| 2499 |
1/0 |
| 2500 |
for func in math.atan2, math.copysign, math.remainder: |
| 2501 |
y = F() |
| 2502 |
with self.assertRaises(TypeError): |
| 2503 |
func("not a number", y) |
| 2504 |
|
| 2505 |
# There should not have been any attempt to convert the second |
| 2506 |
# argument to a float. |
| 2507 |
self.assertFalse(getattr(y, "converted", False)) |
| 2508 |
|
| 2509 |
def test_input_exceptions(self): |
| 2510 |
self.assertRaises(TypeError, math.exp, "spam") |
| 2511 |
self.assertRaises(TypeError, math.erf, "spam") |
| 2512 |
self.assertRaises(TypeError, math.atan2, "spam", 1.0) |
| 2513 |
self.assertRaises(TypeError, math.atan2, 1.0, "spam") |
| 2514 |
self.assertRaises(TypeError, math.atan2, 1.0) |
| 2515 |
self.assertRaises(TypeError, math.atan2, 1.0, 2.0, 3.0) |
| 2516 |
|
| 2517 |
def test_exception_messages(self): |
| 2518 |
x = -1.1 |
| 2519 |
with self.assertRaisesRegex(ValueError, |
| 2520 |
f"expected a nonnegative input, got {x}"): |
| 2521 |
math.sqrt(x) |
| 2522 |
with self.assertRaisesRegex(ValueError, |
| 2523 |
f"expected a positive input, got {x}"): |
| 2524 |
math.log(x) |
| 2525 |
with self.assertRaisesRegex(ValueError, |
| 2526 |
f"expected a positive input, got {x}"): |
| 2527 |
math.log(123, x) |
| 2528 |
with self.assertRaisesRegex(ValueError, |
| 2529 |
f"expected a positive input, got {x}"): |
| 2530 |
math.log(x, 123) |
| 2531 |
with self.assertRaisesRegex(ValueError, |
| 2532 |
f"expected a positive input, got {x}"): |
| 2533 |
math.log2(x) |
| 2534 |
with self.assertRaisesRegex(ValueError, |
| 2535 |
f"expected a positive input, got {x}"): |
| 2536 |
math.log10(x) |
| 2537 |
x = decimal.Decimal('-1.1') |
| 2538 |
with self.assertRaisesRegex(ValueError, |
| 2539 |
f"expected a positive input, got {x}"): |
| 2540 |
math.log(x) |
| 2541 |
x = fractions.Fraction(1, 10**400) |
| 2542 |
with self.assertRaisesRegex(ValueError, |
| 2543 |
f"expected a positive input, got {float(x)}"): |
| 2544 |
math.log(x) |
| 2545 |
x = -123 |
| 2546 |
with self.assertRaisesRegex(ValueError, |
| 2547 |
"expected a positive input$"): |
| 2548 |
math.log(x) |
| 2549 |
with self.assertRaisesRegex(ValueError, |
| 2550 |
f"expected a noninteger or positive integer, got {x}"): |
| 2551 |
math.gamma(x) |
| 2552 |
x = 1.0 |
| 2553 |
with self.assertRaisesRegex(ValueError, |
| 2554 |
f"expected a number between -1 and 1, got {x}"): |
| 2555 |
math.atanh(x) |
| 2556 |
|
| 2557 |
# Custom assertions. |
| 2558 |
|
| 2559 |
def assertIsNaN(self, value): |
| 2560 |
if not math.isnan(value): |
| 2561 |
self.fail("Expected a NaN, got {!r}.".format(value)) |
| 2562 |
|
| 2563 |
def assertEqualSign(self, x, y): |
| 2564 |
"""Similar to assertEqual(), but compare also the sign with copysign(). |
| 2565 |
|
| 2566 |
Function useful to compare signed zeros. |
| 2567 |
""" |
| 2568 |
self.assertEqual(x, y) |
| 2569 |
self.assertEqual(math.copysign(1.0, x), math.copysign(1.0, y)) |
| 2570 |
|
| 2571 |
|
| 2572 |
class IsCloseTests(unittest.TestCase): |
| 2573 |
isclose = math.isclose # subclasses should override this |
| 2574 |
|
| 2575 |
def assertIsClose(self, a, b, *args, **kwargs): |
| 2576 |
self.assertTrue(self.isclose(a, b, *args, **kwargs), |
| 2577 |
msg="%s and %s should be close!" % (a, b)) |
| 2578 |
|
| 2579 |
def assertIsNotClose(self, a, b, *args, **kwargs): |
| 2580 |
self.assertFalse(self.isclose(a, b, *args, **kwargs), |
| 2581 |
msg="%s and %s should not be close!" % (a, b)) |
| 2582 |
|
| 2583 |
def assertAllClose(self, examples, *args, **kwargs): |
| 2584 |
for a, b in examples: |
| 2585 |
self.assertIsClose(a, b, *args, **kwargs) |
| 2586 |
|
| 2587 |
def assertAllNotClose(self, examples, *args, **kwargs): |
| 2588 |
for a, b in examples: |
| 2589 |
self.assertIsNotClose(a, b, *args, **kwargs) |
| 2590 |
|
| 2591 |
def test_negative_tolerances(self): |
| 2592 |
# ValueError should be raised if either tolerance is less than zero |
| 2593 |
with self.assertRaises(ValueError): |
| 2594 |
self.assertIsClose(1, 1, rel_tol=-1e-100) |
| 2595 |
with self.assertRaises(ValueError): |
| 2596 |
self.assertIsClose(1, 1, rel_tol=1e-100, abs_tol=-1e10) |
| 2597 |
|
| 2598 |
def test_identical(self): |
| 2599 |
# identical values must test as close |
| 2600 |
identical_examples = [(2.0, 2.0), |
| 2601 |
(0.1e200, 0.1e200), |
| 2602 |
(1.123e-300, 1.123e-300), |
| 2603 |
(12345, 12345.0), |
| 2604 |
(0.0, -0.0), |
| 2605 |
(345678, 345678)] |
| 2606 |
self.assertAllClose(identical_examples, rel_tol=0.0, abs_tol=0.0) |
| 2607 |
|
| 2608 |
def test_eight_decimal_places(self): |
| 2609 |
# examples that are close to 1e-8, but not 1e-9 |
| 2610 |
eight_decimal_places_examples = [(1e8, 1e8 + 1), |
| 2611 |
(-1e-8, -1.000000009e-8), |
| 2612 |
(1.12345678, 1.12345679)] |
| 2613 |
self.assertAllClose(eight_decimal_places_examples, rel_tol=1e-8) |
| 2614 |
self.assertAllNotClose(eight_decimal_places_examples, rel_tol=1e-9) |
| 2615 |
|
| 2616 |
def test_near_zero(self): |
| 2617 |
# values close to zero |
| 2618 |
near_zero_examples = [(1e-9, 0.0), |
| 2619 |
(-1e-9, 0.0), |
| 2620 |
(-1e-150, 0.0)] |
| 2621 |
# these should not be close to any rel_tol |
| 2622 |
self.assertAllNotClose(near_zero_examples, rel_tol=0.9) |
| 2623 |
# these should be close to abs_tol=1e-8 |
| 2624 |
self.assertAllClose(near_zero_examples, abs_tol=1e-8) |
| 2625 |
|
| 2626 |
def test_identical_infinite(self): |
| 2627 |
# these are close regardless of tolerance -- i.e. they are equal |
| 2628 |
self.assertIsClose(INF, INF) |
| 2629 |
self.assertIsClose(INF, INF, abs_tol=0.0) |
| 2630 |
self.assertIsClose(NINF, NINF) |
| 2631 |
self.assertIsClose(NINF, NINF, abs_tol=0.0) |
| 2632 |
|
| 2633 |
def test_inf_ninf_nan(self): |
| 2634 |
# these should never be close (following IEEE 754 rules for equality) |
| 2635 |
not_close_examples = [(NAN, NAN), |
| 2636 |
(NAN, 1e-100), |
| 2637 |
(1e-100, NAN), |
| 2638 |
(INF, NAN), |
| 2639 |
(NAN, INF), |
| 2640 |
(INF, NINF), |
| 2641 |
(INF, 1.0), |
| 2642 |
(1.0, INF), |
| 2643 |
(INF, 1e308), |
| 2644 |
(1e308, INF)] |
| 2645 |
# use largest reasonable tolerance |
| 2646 |
self.assertAllNotClose(not_close_examples, abs_tol=0.999999999999999) |
| 2647 |
|
| 2648 |
def test_zero_tolerance(self): |
| 2649 |
# test with zero tolerance |
| 2650 |
zero_tolerance_close_examples = [(1.0, 1.0), |
| 2651 |
(-3.4, -3.4), |
| 2652 |
(-1e-300, -1e-300)] |
| 2653 |
self.assertAllClose(zero_tolerance_close_examples, rel_tol=0.0) |
| 2654 |
|
| 2655 |
zero_tolerance_not_close_examples = [(1.0, 1.000000000000001), |
| 2656 |
(0.99999999999999, 1.0), |
| 2657 |
(1.0e200, .999999999999999e200)] |
| 2658 |
self.assertAllNotClose(zero_tolerance_not_close_examples, rel_tol=0.0) |
| 2659 |
|
| 2660 |
def test_asymmetry(self): |
| 2661 |
# test the asymmetry example from PEP 485 |
| 2662 |
self.assertAllClose([(9, 10), (10, 9)], rel_tol=0.1) |
| 2663 |
|
| 2664 |
def test_integers(self): |
| 2665 |
# test with integer values |
| 2666 |
integer_examples = [(100000001, 100000000), |
| 2667 |
(123456789, 123456788)] |
| 2668 |
|
| 2669 |
self.assertAllClose(integer_examples, rel_tol=1e-8) |
| 2670 |
self.assertAllNotClose(integer_examples, rel_tol=1e-9) |
| 2671 |
|
| 2672 |
def test_decimals(self): |
| 2673 |
# test with Decimal values |
| 2674 |
from decimal import Decimal |
| 2675 |
|
| 2676 |
decimal_examples = [(Decimal('1.00000001'), Decimal('1.0')), |
| 2677 |
(Decimal('1.00000001e-20'), Decimal('1.0e-20')), |
| 2678 |
(Decimal('1.00000001e-100'), Decimal('1.0e-100')), |
| 2679 |
(Decimal('1.00000001e20'), Decimal('1.0e20'))] |
| 2680 |
self.assertAllClose(decimal_examples, rel_tol=1e-8) |
| 2681 |
self.assertAllNotClose(decimal_examples, rel_tol=1e-9) |
| 2682 |
|
| 2683 |
def test_fractions(self): |
| 2684 |
# test with Fraction values |
| 2685 |
from fractions import Fraction |
| 2686 |
|
| 2687 |
fraction_examples = [ |
| 2688 |
(Fraction(1, 100000000) + 1, Fraction(1)), |
| 2689 |
(Fraction(100000001), Fraction(100000000)), |
| 2690 |
(Fraction(10**8 + 1, 10**28), Fraction(1, 10**20))] |
| 2691 |
self.assertAllClose(fraction_examples, rel_tol=1e-8) |
| 2692 |
self.assertAllNotClose(fraction_examples, rel_tol=1e-9) |
| 2693 |
|
| 2694 |
|
| 2695 |
class FMATests(unittest.TestCase): |
| 2696 |
""" Tests for math.fma. """ |
| 2697 |
|
| 2698 |
def test_fma_nan_results(self): |
| 2699 |
# Selected representative values. |
| 2700 |
values = [ |
| 2701 |
-math.inf, -1e300, -2.3, -1e-300, -0.0, |
| 2702 |
0.0, 1e-300, 2.3, 1e300, math.inf, math.nan |
| 2703 |
] |
| 2704 |
|
| 2705 |
# If any input is a NaN, the result should be a NaN, too. |
| 2706 |
for a, b in itertools.product(values, repeat=2): |
| 2707 |
with self.subTest(a=a, b=b): |
| 2708 |
self.assertIsNaN(math.fma(math.nan, a, b)) |
| 2709 |
self.assertIsNaN(math.fma(a, math.nan, b)) |
| 2710 |
self.assertIsNaN(math.fma(a, b, math.nan)) |
| 2711 |
|
| 2712 |
def test_fma_infinities(self): |
| 2713 |
# Cases involving infinite inputs or results. |
| 2714 |
positives = [1e-300, 2.3, 1e300, math.inf] |
| 2715 |
finites = [-1e300, -2.3, -1e-300, -0.0, 0.0, 1e-300, 2.3, 1e300] |
| 2716 |
non_nans = [-math.inf, -2.3, -0.0, 0.0, 2.3, math.inf] |
| 2717 |
|
| 2718 |
# ValueError due to inf * 0 computation. |
| 2719 |
for c in non_nans: |
| 2720 |
for infinity in [math.inf, -math.inf]: |
| 2721 |
for zero in [0.0, -0.0]: |
| 2722 |
with self.subTest(c=c, infinity=infinity, zero=zero): |
| 2723 |
with self.assertRaises(ValueError): |
| 2724 |
math.fma(infinity, zero, c) |
| 2725 |
with self.assertRaises(ValueError): |
| 2726 |
math.fma(zero, infinity, c) |
| 2727 |
|
| 2728 |
# ValueError when a*b and c both infinite of opposite signs. |
| 2729 |
for b in positives: |
| 2730 |
with self.subTest(b=b): |
| 2731 |
with self.assertRaises(ValueError): |
| 2732 |
math.fma(math.inf, b, -math.inf) |
| 2733 |
with self.assertRaises(ValueError): |
| 2734 |
math.fma(math.inf, -b, math.inf) |
| 2735 |
with self.assertRaises(ValueError): |
| 2736 |
math.fma(-math.inf, -b, -math.inf) |
| 2737 |
with self.assertRaises(ValueError): |
| 2738 |
math.fma(-math.inf, b, math.inf) |
| 2739 |
with self.assertRaises(ValueError): |
| 2740 |
math.fma(b, math.inf, -math.inf) |
| 2741 |
with self.assertRaises(ValueError): |
| 2742 |
math.fma(-b, math.inf, math.inf) |
| 2743 |
with self.assertRaises(ValueError): |
| 2744 |
math.fma(-b, -math.inf, -math.inf) |
| 2745 |
with self.assertRaises(ValueError): |
| 2746 |
math.fma(b, -math.inf, math.inf) |
| 2747 |
|
| 2748 |
# Infinite result when a*b and c both infinite of the same sign. |
| 2749 |
for b in positives: |
| 2750 |
with self.subTest(b=b): |
| 2751 |
self.assertEqual(math.fma(math.inf, b, math.inf), math.inf) |
| 2752 |
self.assertEqual(math.fma(math.inf, -b, -math.inf), -math.inf) |
| 2753 |
self.assertEqual(math.fma(-math.inf, -b, math.inf), math.inf) |
| 2754 |
self.assertEqual(math.fma(-math.inf, b, -math.inf), -math.inf) |
| 2755 |
self.assertEqual(math.fma(b, math.inf, math.inf), math.inf) |
| 2756 |
self.assertEqual(math.fma(-b, math.inf, -math.inf), -math.inf) |
| 2757 |
self.assertEqual(math.fma(-b, -math.inf, math.inf), math.inf) |
| 2758 |
self.assertEqual(math.fma(b, -math.inf, -math.inf), -math.inf) |
| 2759 |
|
| 2760 |
# Infinite result when a*b finite, c infinite. |
| 2761 |
for a, b in itertools.product(finites, finites): |
| 2762 |
with self.subTest(b=b): |
| 2763 |
self.assertEqual(math.fma(a, b, math.inf), math.inf) |
| 2764 |
self.assertEqual(math.fma(a, b, -math.inf), -math.inf) |
| 2765 |
|
| 2766 |
# Infinite result when a*b infinite, c finite. |
| 2767 |
for b, c in itertools.product(positives, finites): |
| 2768 |
with self.subTest(b=b, c=c): |
| 2769 |
self.assertEqual(math.fma(math.inf, b, c), math.inf) |
| 2770 |
self.assertEqual(math.fma(-math.inf, b, c), -math.inf) |
| 2771 |
self.assertEqual(math.fma(-math.inf, -b, c), math.inf) |
| 2772 |
self.assertEqual(math.fma(math.inf, -b, c), -math.inf) |
| 2773 |
|
| 2774 |
self.assertEqual(math.fma(b, math.inf, c), math.inf) |
| 2775 |
self.assertEqual(math.fma(b, -math.inf, c), -math.inf) |
| 2776 |
self.assertEqual(math.fma(-b, -math.inf, c), math.inf) |
| 2777 |
self.assertEqual(math.fma(-b, math.inf, c), -math.inf) |
| 2778 |
|
| 2779 |
# gh-73468: On some platforms, libc fma() doesn't implement IEE 754-2008 |
| 2780 |
# properly: it doesn't use the right sign when the result is zero. |
| 2781 |
@unittest.skipIf( |
| 2782 |
sys.platform.startswith(("freebsd", "wasi", "netbsd", "emscripten")) |
| 2783 |
or (sys.platform == "android" and platform.machine() == "x86_64") |
| 2784 |
or support.linked_to_musl(), # gh-131032 |
| 2785 |
f"this platform doesn't implement IEE 754-2008 properly") |
| 2786 |
# gh-131032: musl is fixed but the fix is not yet released; when the fixed |
| 2787 |
# version is known change this to: |
| 2788 |
# or support.linked_to_musl() < (1, <m>, <p>) |
| 2789 |
def test_fma_zero_result(self): |
| 2790 |
nonnegative_finites = [0.0, 1e-300, 2.3, 1e300] |
| 2791 |
|
| 2792 |
# Zero results from exact zero inputs. |
| 2793 |
for b in nonnegative_finites: |
| 2794 |
with self.subTest(b=b): |
| 2795 |
self.assertIsPositiveZero(math.fma(0.0, b, 0.0)) |
| 2796 |
self.assertIsPositiveZero(math.fma(0.0, b, -0.0)) |
| 2797 |
self.assertIsNegativeZero(math.fma(0.0, -b, -0.0)) |
| 2798 |
self.assertIsPositiveZero(math.fma(0.0, -b, 0.0)) |
| 2799 |
self.assertIsPositiveZero(math.fma(-0.0, -b, 0.0)) |
| 2800 |
self.assertIsPositiveZero(math.fma(-0.0, -b, -0.0)) |
| 2801 |
self.assertIsNegativeZero(math.fma(-0.0, b, -0.0)) |
| 2802 |
self.assertIsPositiveZero(math.fma(-0.0, b, 0.0)) |
| 2803 |
|
| 2804 |
self.assertIsPositiveZero(math.fma(b, 0.0, 0.0)) |
| 2805 |
self.assertIsPositiveZero(math.fma(b, 0.0, -0.0)) |
| 2806 |
self.assertIsNegativeZero(math.fma(-b, 0.0, -0.0)) |
| 2807 |
self.assertIsPositiveZero(math.fma(-b, 0.0, 0.0)) |
| 2808 |
self.assertIsPositiveZero(math.fma(-b, -0.0, 0.0)) |
| 2809 |
self.assertIsPositiveZero(math.fma(-b, -0.0, -0.0)) |
| 2810 |
self.assertIsNegativeZero(math.fma(b, -0.0, -0.0)) |
| 2811 |
self.assertIsPositiveZero(math.fma(b, -0.0, 0.0)) |
| 2812 |
|
| 2813 |
# Exact zero result from nonzero inputs. |
| 2814 |
self.assertIsPositiveZero(math.fma(2.0, 2.0, -4.0)) |
| 2815 |
self.assertIsPositiveZero(math.fma(2.0, -2.0, 4.0)) |
| 2816 |
self.assertIsPositiveZero(math.fma(-2.0, -2.0, -4.0)) |
| 2817 |
self.assertIsPositiveZero(math.fma(-2.0, 2.0, 4.0)) |
| 2818 |
|
| 2819 |
# Underflow to zero. |
| 2820 |
tiny = 1e-300 |
| 2821 |
self.assertIsPositiveZero(math.fma(tiny, tiny, 0.0)) |
| 2822 |
self.assertIsNegativeZero(math.fma(tiny, -tiny, 0.0)) |
| 2823 |
self.assertIsPositiveZero(math.fma(-tiny, -tiny, 0.0)) |
| 2824 |
self.assertIsNegativeZero(math.fma(-tiny, tiny, 0.0)) |
| 2825 |
self.assertIsPositiveZero(math.fma(tiny, tiny, -0.0)) |
| 2826 |
self.assertIsNegativeZero(math.fma(tiny, -tiny, -0.0)) |
| 2827 |
self.assertIsPositiveZero(math.fma(-tiny, -tiny, -0.0)) |
| 2828 |
self.assertIsNegativeZero(math.fma(-tiny, tiny, -0.0)) |
| 2829 |
|
| 2830 |
# Corner case where rounding the multiplication would |
| 2831 |
# give the wrong result. |
| 2832 |
x = float.fromhex('0x1p-500') |
| 2833 |
y = float.fromhex('0x1p-550') |
| 2834 |
z = float.fromhex('0x1p-1000') |
| 2835 |
self.assertIsNegativeZero(math.fma(x-y, x+y, -z)) |
| 2836 |
self.assertIsPositiveZero(math.fma(y-x, x+y, z)) |
| 2837 |
self.assertIsNegativeZero(math.fma(y-x, -(x+y), -z)) |
| 2838 |
self.assertIsPositiveZero(math.fma(x-y, -(x+y), z)) |
| 2839 |
|
| 2840 |
def test_fma_overflow(self): |
| 2841 |
a = b = float.fromhex('0x1p512') |
| 2842 |
c = float.fromhex('0x1p1023') |
| 2843 |
# Overflow from multiplication. |
| 2844 |
with self.assertRaises(OverflowError): |
| 2845 |
math.fma(a, b, 0.0) |
| 2846 |
self.assertEqual(math.fma(a, b/2.0, 0.0), c) |
| 2847 |
# Overflow from the addition. |
| 2848 |
with self.assertRaises(OverflowError): |
| 2849 |
math.fma(a, b/2.0, c) |
| 2850 |
# No overflow, even though a*b overflows a float. |
| 2851 |
self.assertEqual(math.fma(a, b, -c), c) |
| 2852 |
|
| 2853 |
# Extreme case: a * b is exactly at the overflow boundary, so the |
| 2854 |
# tiniest offset makes a difference between overflow and a finite |
| 2855 |
# result. |
| 2856 |
a = float.fromhex('0x1.ffffffc000000p+511') |
| 2857 |
b = float.fromhex('0x1.0000002000000p+512') |
| 2858 |
c = float.fromhex('0x0.0000000000001p-1022') |
| 2859 |
with self.assertRaises(OverflowError): |
| 2860 |
math.fma(a, b, 0.0) |
| 2861 |
with self.assertRaises(OverflowError): |
| 2862 |
math.fma(a, b, c) |
| 2863 |
self.assertEqual(math.fma(a, b, -c), |
| 2864 |
float.fromhex('0x1.fffffffffffffp+1023')) |
| 2865 |
|
| 2866 |
# Another extreme case: here a*b is about as large as possible subject |
| 2867 |
# to math.fma(a, b, c) being finite. |
| 2868 |
a = float.fromhex('0x1.ae565943785f9p+512') |
| 2869 |
b = float.fromhex('0x1.3094665de9db8p+512') |
| 2870 |
c = float.fromhex('0x1.fffffffffffffp+1023') |
| 2871 |
self.assertEqual(math.fma(a, b, -c), c) |
| 2872 |
|
| 2873 |
def test_fma_single_round(self): |
| 2874 |
a = float.fromhex('0x1p-50') |
| 2875 |
self.assertEqual(math.fma(a - 1.0, a + 1.0, 1.0), a*a) |
| 2876 |
|
| 2877 |
def test_random(self): |
| 2878 |
# A collection of randomly generated inputs for which the naive FMA |
| 2879 |
# (with two rounds) gives a different result from a singly-rounded FMA. |
| 2880 |
|
| 2881 |
# tuples (a, b, c, expected) |
| 2882 |
test_values = [ |
| 2883 |
('0x1.694adde428b44p-1', '0x1.371b0d64caed7p-1', |
| 2884 |
'0x1.f347e7b8deab8p-4', '0x1.19f10da56c8adp-1'), |
| 2885 |
('0x1.605401ccc6ad6p-2', '0x1.ce3a40bf56640p-2', |
| 2886 |
'0x1.96e3bf7bf2e20p-2', '0x1.1af6d8aa83101p-1'), |
| 2887 |
('0x1.e5abd653a67d4p-2', '0x1.a2e400209b3e6p-1', |
| 2888 |
'0x1.a90051422ce13p-1', '0x1.37d68cc8c0fbbp+0'), |
| 2889 |
('0x1.f94e8efd54700p-2', '0x1.123065c812cebp-1', |
| 2890 |
'0x1.458f86fb6ccd0p-1', '0x1.ccdcee26a3ff3p-1'), |
| 2891 |
('0x1.bd926f1eedc96p-1', '0x1.eee9ca68c5740p-1', |
| 2892 |
'0x1.960c703eb3298p-2', '0x1.3cdcfb4fdb007p+0'), |
| 2893 |
('0x1.27348350fbccdp-1', '0x1.3b073914a53f1p-1', |
| 2894 |
'0x1.e300da5c2b4cbp-1', '0x1.4c51e9a3c4e29p+0'), |
| 2895 |
('0x1.2774f00b3497bp-1', '0x1.7038ec336bff0p-2', |
| 2896 |
'0x1.2f6f2ccc3576bp-1', '0x1.99ad9f9c2688bp-1'), |
| 2897 |
('0x1.51d5a99300e5cp-1', '0x1.5cd74abd445a1p-1', |
| 2898 |
'0x1.8880ab0bbe530p-1', '0x1.3756f96b91129p+0'), |
| 2899 |
('0x1.73cb965b821b8p-2', '0x1.218fd3d8d5371p-1', |
| 2900 |
'0x1.d1ea966a1f758p-2', '0x1.5217b8fd90119p-1'), |
| 2901 |
('0x1.4aa98e890b046p-1', '0x1.954d85dff1041p-1', |
| 2902 |
'0x1.122b59317ebdfp-1', '0x1.0bf644b340cc5p+0'), |
| 2903 |
('0x1.e28f29e44750fp-1', '0x1.4bcc4fdcd18fep-1', |
| 2904 |
'0x1.fd47f81298259p-1', '0x1.9b000afbc9995p+0'), |
| 2905 |
('0x1.d2e850717fe78p-3', '0x1.1dd7531c303afp-1', |
| 2906 |
'0x1.e0869746a2fc2p-2', '0x1.316df6eb26439p-1'), |
| 2907 |
('0x1.cf89c75ee6fbap-2', '0x1.b23decdc66825p-1', |
| 2908 |
'0x1.3d1fe76ac6168p-1', '0x1.00d8ea4c12abbp+0'), |
| 2909 |
('0x1.3265ae6f05572p-2', '0x1.16d7ec285f7a2p-1', |
| 2910 |
'0x1.0b8405b3827fbp-1', '0x1.5ef33c118a001p-1'), |
| 2911 |
('0x1.c4d1bf55ec1a5p-1', '0x1.bc59618459e12p-2', |
| 2912 |
'0x1.ce5b73dc1773dp-1', '0x1.496cf6164f99bp+0'), |
| 2913 |
('0x1.d350026ac3946p-1', '0x1.9a234e149a68cp-2', |
| 2914 |
'0x1.f5467b1911fd6p-2', '0x1.b5cee3225caa5p-1'), |
| 2915 |
] |
| 2916 |
for a_hex, b_hex, c_hex, expected_hex in test_values: |
| 2917 |
with self.subTest(a_hex=a_hex, b_hex=b_hex, c_hex=c_hex, |
| 2918 |
expected_hex=expected_hex): |
| 2919 |
a = float.fromhex(a_hex) |
| 2920 |
b = float.fromhex(b_hex) |
| 2921 |
c = float.fromhex(c_hex) |
| 2922 |
expected = float.fromhex(expected_hex) |
| 2923 |
self.assertEqual(math.fma(a, b, c), expected) |
| 2924 |
self.assertEqual(math.fma(b, a, c), expected) |
| 2925 |
|
| 2926 |
# Custom assertions. |
| 2927 |
def assertIsNaN(self, value): |
| 2928 |
self.assertTrue( |
| 2929 |
math.isnan(value), |
| 2930 |
msg="Expected a NaN, got {!r}".format(value) |
| 2931 |
) |
| 2932 |
|
| 2933 |
def assertIsPositiveZero(self, value): |
| 2934 |
self.assertTrue( |
| 2935 |
value == 0 and math.copysign(1, value) > 0, |
| 2936 |
msg="Expected a positive zero, got {!r}".format(value) |
| 2937 |
) |
| 2938 |
|
| 2939 |
def assertIsNegativeZero(self, value): |
| 2940 |
self.assertTrue( |
| 2941 |
value == 0 and math.copysign(1, value) < 0, |
| 2942 |
msg="Expected a negative zero, got {!r}".format(value) |
| 2943 |
) |
| 2944 |
|
| 2945 |
|
| 2946 |
def load_tests(loader, tests, pattern): |
| 2947 |
from doctest import DocFileSuite |
| 2948 |
tests.addTest(DocFileSuite(os.path.join("mathdata", "ieee754.txt"))) |
| 2949 |
return tests |
| 2950 |
|
| 2951 |
if __name__ == '__main__': |
| 2952 |
unittest.main() |