blob: f5283c5e0dcb63519e600b0dfdaa18c6e44d0fa2 [file] [log] [blame]
Guido van Rossumfcce6301996-08-08 18:26:25 +00001# Python test set -- math module
2# XXXX Should not do tests around zero only
3
Eric Smithf24a0d92010-12-04 13:32:18 +00004from test.support import run_unittest, verbose, requires_IEEE_754
Victor Stinnerfce92332011-06-01 12:28:04 +02005from test import support
Thomas Wouters89f507f2006-12-13 04:49:30 +00006import unittest
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -07007import itertools
Pablo Galindoe9ba3702018-09-03 22:20:06 +01008import decimal
Thomas Wouters89f507f2006-12-13 04:49:30 +00009import math
Christian Heimes53876d92008-04-19 00:31:39 +000010import os
Mark Dickinson85746542016-09-04 09:58:51 +010011import platform
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -070012import random
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000013import struct
Mark Dickinson85746542016-09-04 09:58:51 +010014import sys
Victor Stinner8f4ef3b2019-07-01 18:28:25 +020015
Guido van Rossumfcce6301996-08-08 18:26:25 +000016
Christian Heimes53876d92008-04-19 00:31:39 +000017eps = 1E-05
18NAN = float('nan')
19INF = float('inf')
20NINF = float('-inf')
Mark Dickinson31ba1c32016-09-04 12:29:14 +010021FLOAT_MAX = sys.float_info.max
Raymond Hettingerc6dabe32018-07-28 07:48:04 -070022FLOAT_MIN = sys.float_info.min
Christian Heimes53876d92008-04-19 00:31:39 +000023
Mark Dickinson5c567082009-04-24 16:39:07 +000024# detect evidence of double-rounding: fsum is not always correctly
25# rounded on machines that suffer from double rounding.
26x, y = 1e16, 2.9999 # use temporary values to defeat peephole optimizer
27HAVE_DOUBLE_ROUNDING = (x + y == 1e16 + 4)
28
Christian Heimes53876d92008-04-19 00:31:39 +000029# locate file with test values
30if __name__ == '__main__':
31 file = sys.argv[0]
32else:
33 file = __file__
34test_dir = os.path.dirname(file) or os.curdir
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000035math_testcases = os.path.join(test_dir, 'math_testcases.txt')
Christian Heimes53876d92008-04-19 00:31:39 +000036test_file = os.path.join(test_dir, 'cmath_testcases.txt')
37
Mark Dickinson96f774d2016-09-03 19:30:22 +010038
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000039def to_ulps(x):
40 """Convert a non-NaN float x to an integer, in such a way that
41 adjacent floats are converted to adjacent integers. Then
42 abs(ulps(x) - ulps(y)) gives the difference in ulps between two
43 floats.
44
45 The results from this function will only make sense on platforms
Mark Dickinson96f774d2016-09-03 19:30:22 +010046 where native doubles are represented in IEEE 754 binary64 format.
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000047
Mark Dickinson96f774d2016-09-03 19:30:22 +010048 Note: 0.0 and -0.0 are converted to 0 and -1, respectively.
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000049 """
Mark Dickinsond412ab52009-10-17 07:10:00 +000050 n = struct.unpack('<q', struct.pack('<d', x))[0]
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000051 if n < 0:
52 n = ~(n+2**63)
53 return n
54
Mark Dickinson05d2e082009-12-11 20:17:17 +000055
Mark Dickinson4c8a9a22010-05-15 17:02:38 +000056# Here's a pure Python version of the math.factorial algorithm, for
57# documentation and comparison purposes.
58#
59# Formula:
60#
61# factorial(n) = factorial_odd_part(n) << (n - count_set_bits(n))
62#
63# where
64#
65# factorial_odd_part(n) = product_{i >= 0} product_{0 < j <= n >> i; j odd} j
66#
67# The outer product above is an infinite product, but once i >= n.bit_length,
68# (n >> i) < 1 and the corresponding term of the product is empty. So only the
69# finitely many terms for 0 <= i < n.bit_length() contribute anything.
70#
71# We iterate downwards from i == n.bit_length() - 1 to i == 0. The inner
72# product in the formula above starts at 1 for i == n.bit_length(); for each i
73# < n.bit_length() we get the inner product for i from that for i + 1 by
74# multiplying by all j in {n >> i+1 < j <= n >> i; j odd}. In Python terms,
75# this set is range((n >> i+1) + 1 | 1, (n >> i) + 1 | 1, 2).
76
77def count_set_bits(n):
78 """Number of '1' bits in binary expansion of a nonnnegative integer."""
79 return 1 + count_set_bits(n & n - 1) if n else 0
80
81def partial_product(start, stop):
82 """Product of integers in range(start, stop, 2), computed recursively.
83 start and stop should both be odd, with start <= stop.
84
85 """
86 numfactors = (stop - start) >> 1
87 if not numfactors:
88 return 1
89 elif numfactors == 1:
90 return start
91 else:
92 mid = (start + numfactors) | 1
93 return partial_product(start, mid) * partial_product(mid, stop)
94
95def py_factorial(n):
96 """Factorial of nonnegative integer n, via "Binary Split Factorial Formula"
97 described at http://www.luschny.de/math/factorial/binarysplitfact.html
98
99 """
100 inner = outer = 1
101 for i in reversed(range(n.bit_length())):
102 inner *= partial_product((n >> i + 1) + 1 | 1, (n >> i) + 1 | 1)
103 outer *= inner
104 return outer << (n - count_set_bits(n))
105
Mark Dickinson96f774d2016-09-03 19:30:22 +0100106def ulp_abs_check(expected, got, ulp_tol, abs_tol):
107 """Given finite floats `expected` and `got`, check that they're
108 approximately equal to within the given number of ulps or the
109 given absolute tolerance, whichever is bigger.
Mark Dickinson05d2e082009-12-11 20:17:17 +0000110
Mark Dickinson96f774d2016-09-03 19:30:22 +0100111 Returns None on success and an error message on failure.
112 """
113 ulp_error = abs(to_ulps(expected) - to_ulps(got))
114 abs_error = abs(expected - got)
115
116 # Succeed if either abs_error <= abs_tol or ulp_error <= ulp_tol.
117 if abs_error <= abs_tol or ulp_error <= ulp_tol:
Mark Dickinson05d2e082009-12-11 20:17:17 +0000118 return None
Mark Dickinson96f774d2016-09-03 19:30:22 +0100119 else:
120 fmt = ("error = {:.3g} ({:d} ulps); "
121 "permitted error = {:.3g} or {:d} ulps")
122 return fmt.format(abs_error, ulp_error, abs_tol, ulp_tol)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000123
124def parse_mtestfile(fname):
125 """Parse a file with test values
126
127 -- starts a comment
128 blank lines, or lines containing only a comment, are ignored
129 other lines are expected to have the form
130 id fn arg -> expected [flag]*
131
132 """
133 with open(fname) as fp:
134 for line in fp:
135 # strip comments, and skip blank lines
136 if '--' in line:
137 line = line[:line.index('--')]
138 if not line.strip():
139 continue
140
141 lhs, rhs = line.split('->')
142 id, fn, arg = lhs.split()
143 rhs_pieces = rhs.split()
144 exp = rhs_pieces[0]
145 flags = rhs_pieces[1:]
146
147 yield (id, fn, float(arg), float(exp), flags)
148
Mark Dickinson96f774d2016-09-03 19:30:22 +0100149
Christian Heimes53876d92008-04-19 00:31:39 +0000150def parse_testfile(fname):
151 """Parse a file with test values
152
153 Empty lines or lines starting with -- are ignored
154 yields id, fn, arg_real, arg_imag, exp_real, exp_imag
155 """
156 with open(fname) as fp:
157 for line in fp:
158 # skip comment lines and blank lines
159 if line.startswith('--') or not line.strip():
160 continue
161
162 lhs, rhs = line.split('->')
163 id, fn, arg_real, arg_imag = lhs.split()
164 rhs_pieces = rhs.split()
165 exp_real, exp_imag = rhs_pieces[0], rhs_pieces[1]
166 flags = rhs_pieces[2:]
167
168 yield (id, fn,
169 float(arg_real), float(arg_imag),
170 float(exp_real), float(exp_imag),
Mark Dickinson96f774d2016-09-03 19:30:22 +0100171 flags)
172
173
174def result_check(expected, got, ulp_tol=5, abs_tol=0.0):
175 # Common logic of MathTests.(ftest, test_testcases, test_mtestcases)
176 """Compare arguments expected and got, as floats, if either
177 is a float, using a tolerance expressed in multiples of
178 ulp(expected) or absolutely (if given and greater).
179
180 As a convenience, when neither argument is a float, and for
181 non-finite floats, exact equality is demanded. Also, nan==nan
182 as far as this function is concerned.
183
184 Returns None on success and an error message on failure.
185 """
186
187 # Check exactly equal (applies also to strings representing exceptions)
188 if got == expected:
189 return None
190
191 failure = "not equal"
192
193 # Turn mixed float and int comparison (e.g. floor()) to all-float
194 if isinstance(expected, float) and isinstance(got, int):
195 got = float(got)
196 elif isinstance(got, float) and isinstance(expected, int):
197 expected = float(expected)
198
199 if isinstance(expected, float) and isinstance(got, float):
200 if math.isnan(expected) and math.isnan(got):
201 # Pass, since both nan
202 failure = None
203 elif math.isinf(expected) or math.isinf(got):
204 # We already know they're not equal, drop through to failure
205 pass
206 else:
207 # Both are finite floats (now). Are they close enough?
208 failure = ulp_abs_check(expected, got, ulp_tol, abs_tol)
209
210 # arguments are not equal, and if numeric, are too far apart
211 if failure is not None:
212 fail_fmt = "expected {!r}, got {!r}"
213 fail_msg = fail_fmt.format(expected, got)
214 fail_msg += ' ({})'.format(failure)
215 return fail_msg
216 else:
217 return None
Guido van Rossumfcce6301996-08-08 18:26:25 +0000218
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +0200219class FloatLike:
220 def __init__(self, value):
221 self.value = value
222
223 def __float__(self):
224 return self.value
225
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +0300226class IntSubclass(int):
227 pass
228
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300229# Class providing an __index__ method.
230class MyIndexable(object):
231 def __init__(self, value):
232 self.value = value
233
234 def __index__(self):
235 return self.value
236
Thomas Wouters89f507f2006-12-13 04:49:30 +0000237class MathTests(unittest.TestCase):
Guido van Rossumfcce6301996-08-08 18:26:25 +0000238
Mark Dickinson96f774d2016-09-03 19:30:22 +0100239 def ftest(self, name, got, expected, ulp_tol=5, abs_tol=0.0):
240 """Compare arguments expected and got, as floats, if either
241 is a float, using a tolerance expressed in multiples of
242 ulp(expected) or absolutely, whichever is greater.
243
244 As a convenience, when neither argument is a float, and for
245 non-finite floats, exact equality is demanded. Also, nan==nan
246 in this function.
247 """
248 failure = result_check(expected, got, ulp_tol, abs_tol)
249 if failure is not None:
250 self.fail("{}: {}".format(name, failure))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000251
Thomas Wouters89f507f2006-12-13 04:49:30 +0000252 def testConstants(self):
Mark Dickinson96f774d2016-09-03 19:30:22 +0100253 # Ref: Abramowitz & Stegun (Dover, 1965)
254 self.ftest('pi', math.pi, 3.141592653589793238462643)
255 self.ftest('e', math.e, 2.718281828459045235360287)
Guido van Rossum0a891d72016-08-15 09:12:52 -0700256 self.assertEqual(math.tau, 2*math.pi)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000257
Thomas Wouters89f507f2006-12-13 04:49:30 +0000258 def testAcos(self):
259 self.assertRaises(TypeError, math.acos)
260 self.ftest('acos(-1)', math.acos(-1), math.pi)
261 self.ftest('acos(0)', math.acos(0), math.pi/2)
262 self.ftest('acos(1)', math.acos(1), 0)
Christian Heimes53876d92008-04-19 00:31:39 +0000263 self.assertRaises(ValueError, math.acos, INF)
264 self.assertRaises(ValueError, math.acos, NINF)
Mark Dickinson31ba1c32016-09-04 12:29:14 +0100265 self.assertRaises(ValueError, math.acos, 1 + eps)
266 self.assertRaises(ValueError, math.acos, -1 - eps)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000267 self.assertTrue(math.isnan(math.acos(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000268
269 def testAcosh(self):
270 self.assertRaises(TypeError, math.acosh)
271 self.ftest('acosh(1)', math.acosh(1), 0)
272 self.ftest('acosh(2)', math.acosh(2), 1.3169578969248168)
273 self.assertRaises(ValueError, math.acosh, 0)
274 self.assertRaises(ValueError, math.acosh, -1)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000275 self.assertEqual(math.acosh(INF), INF)
Christian Heimes53876d92008-04-19 00:31:39 +0000276 self.assertRaises(ValueError, math.acosh, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000277 self.assertTrue(math.isnan(math.acosh(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000278
Thomas Wouters89f507f2006-12-13 04:49:30 +0000279 def testAsin(self):
280 self.assertRaises(TypeError, math.asin)
281 self.ftest('asin(-1)', math.asin(-1), -math.pi/2)
282 self.ftest('asin(0)', math.asin(0), 0)
283 self.ftest('asin(1)', math.asin(1), math.pi/2)
Christian Heimes53876d92008-04-19 00:31:39 +0000284 self.assertRaises(ValueError, math.asin, INF)
285 self.assertRaises(ValueError, math.asin, NINF)
Mark Dickinson31ba1c32016-09-04 12:29:14 +0100286 self.assertRaises(ValueError, math.asin, 1 + eps)
287 self.assertRaises(ValueError, math.asin, -1 - eps)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000288 self.assertTrue(math.isnan(math.asin(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000289
290 def testAsinh(self):
291 self.assertRaises(TypeError, math.asinh)
292 self.ftest('asinh(0)', math.asinh(0), 0)
293 self.ftest('asinh(1)', math.asinh(1), 0.88137358701954305)
294 self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000295 self.assertEqual(math.asinh(INF), INF)
296 self.assertEqual(math.asinh(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000297 self.assertTrue(math.isnan(math.asinh(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000298
Thomas Wouters89f507f2006-12-13 04:49:30 +0000299 def testAtan(self):
300 self.assertRaises(TypeError, math.atan)
301 self.ftest('atan(-1)', math.atan(-1), -math.pi/4)
302 self.ftest('atan(0)', math.atan(0), 0)
303 self.ftest('atan(1)', math.atan(1), math.pi/4)
Christian Heimes53876d92008-04-19 00:31:39 +0000304 self.ftest('atan(inf)', math.atan(INF), math.pi/2)
Christian Heimesa342c012008-04-20 21:01:16 +0000305 self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000306 self.assertTrue(math.isnan(math.atan(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000307
308 def testAtanh(self):
309 self.assertRaises(TypeError, math.atan)
310 self.ftest('atanh(0)', math.atanh(0), 0)
311 self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489)
312 self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489)
313 self.assertRaises(ValueError, math.atanh, 1)
314 self.assertRaises(ValueError, math.atanh, -1)
315 self.assertRaises(ValueError, math.atanh, INF)
316 self.assertRaises(ValueError, math.atanh, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000317 self.assertTrue(math.isnan(math.atanh(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000318
Thomas Wouters89f507f2006-12-13 04:49:30 +0000319 def testAtan2(self):
320 self.assertRaises(TypeError, math.atan2)
321 self.ftest('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2)
322 self.ftest('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4)
323 self.ftest('atan2(0, 1)', math.atan2(0, 1), 0)
324 self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4)
325 self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000326
Christian Heimese57950f2008-04-21 13:08:03 +0000327 # math.atan2(0, x)
328 self.ftest('atan2(0., -inf)', math.atan2(0., NINF), math.pi)
329 self.ftest('atan2(0., -2.3)', math.atan2(0., -2.3), math.pi)
330 self.ftest('atan2(0., -0.)', math.atan2(0., -0.), math.pi)
331 self.assertEqual(math.atan2(0., 0.), 0.)
332 self.assertEqual(math.atan2(0., 2.3), 0.)
333 self.assertEqual(math.atan2(0., INF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000334 self.assertTrue(math.isnan(math.atan2(0., NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000335 # math.atan2(-0, x)
336 self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi)
337 self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi)
338 self.ftest('atan2(-0., -0.)', math.atan2(-0., -0.), -math.pi)
339 self.assertEqual(math.atan2(-0., 0.), -0.)
340 self.assertEqual(math.atan2(-0., 2.3), -0.)
341 self.assertEqual(math.atan2(-0., INF), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000342 self.assertTrue(math.isnan(math.atan2(-0., NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000343 # math.atan2(INF, x)
344 self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4)
345 self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2)
346 self.ftest('atan2(inf, -0.)', math.atan2(INF, -0.0), math.pi/2)
347 self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2)
348 self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2)
349 self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000350 self.assertTrue(math.isnan(math.atan2(INF, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000351 # math.atan2(NINF, x)
352 self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4)
353 self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2)
354 self.ftest('atan2(-inf, -0.)', math.atan2(NINF, -0.0), -math.pi/2)
355 self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2)
356 self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2)
357 self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000358 self.assertTrue(math.isnan(math.atan2(NINF, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000359 # math.atan2(+finite, x)
360 self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi)
361 self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2)
362 self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2)
363 self.assertEqual(math.atan2(2.3, INF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000364 self.assertTrue(math.isnan(math.atan2(2.3, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000365 # math.atan2(-finite, x)
366 self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi)
367 self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2)
368 self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2)
369 self.assertEqual(math.atan2(-2.3, INF), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000370 self.assertTrue(math.isnan(math.atan2(-2.3, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000371 # math.atan2(NAN, x)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000372 self.assertTrue(math.isnan(math.atan2(NAN, NINF)))
373 self.assertTrue(math.isnan(math.atan2(NAN, -2.3)))
374 self.assertTrue(math.isnan(math.atan2(NAN, -0.)))
375 self.assertTrue(math.isnan(math.atan2(NAN, 0.)))
376 self.assertTrue(math.isnan(math.atan2(NAN, 2.3)))
377 self.assertTrue(math.isnan(math.atan2(NAN, INF)))
378 self.assertTrue(math.isnan(math.atan2(NAN, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000379
Thomas Wouters89f507f2006-12-13 04:49:30 +0000380 def testCeil(self):
381 self.assertRaises(TypeError, math.ceil)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000382 self.assertEqual(int, type(math.ceil(0.5)))
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +0200383 self.assertEqual(math.ceil(0.5), 1)
384 self.assertEqual(math.ceil(1.0), 1)
385 self.assertEqual(math.ceil(1.5), 2)
386 self.assertEqual(math.ceil(-0.5), 0)
387 self.assertEqual(math.ceil(-1.0), -1)
388 self.assertEqual(math.ceil(-1.5), -1)
389 self.assertEqual(math.ceil(0.0), 0)
390 self.assertEqual(math.ceil(-0.0), 0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000391 #self.assertEqual(math.ceil(INF), INF)
392 #self.assertEqual(math.ceil(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000393 #self.assertTrue(math.isnan(math.ceil(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000394
Guido van Rossum13e05de2007-08-23 22:56:55 +0000395 class TestCeil:
396 def __ceil__(self):
397 return 42
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +0200398 class FloatCeil(float):
399 def __ceil__(self):
400 return 42
Guido van Rossum13e05de2007-08-23 22:56:55 +0000401 class TestNoCeil:
402 pass
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +0200403 self.assertEqual(math.ceil(TestCeil()), 42)
404 self.assertEqual(math.ceil(FloatCeil()), 42)
405 self.assertEqual(math.ceil(FloatLike(42.5)), 43)
Guido van Rossum13e05de2007-08-23 22:56:55 +0000406 self.assertRaises(TypeError, math.ceil, TestNoCeil())
407
408 t = TestNoCeil()
409 t.__ceil__ = lambda *args: args
410 self.assertRaises(TypeError, math.ceil, t)
411 self.assertRaises(TypeError, math.ceil, t, 0)
412
Mark Dickinson63566232009-09-18 21:04:19 +0000413 @requires_IEEE_754
414 def testCopysign(self):
Mark Dickinson06b59e02010-02-06 23:16:50 +0000415 self.assertEqual(math.copysign(1, 42), 1.0)
416 self.assertEqual(math.copysign(0., 42), 0.0)
417 self.assertEqual(math.copysign(1., -42), -1.0)
418 self.assertEqual(math.copysign(3, 0.), 3.0)
419 self.assertEqual(math.copysign(4., -0.), -4.0)
420
Mark Dickinson63566232009-09-18 21:04:19 +0000421 self.assertRaises(TypeError, math.copysign)
422 # copysign should let us distinguish signs of zeros
Ezio Melottib3aedd42010-11-20 19:04:17 +0000423 self.assertEqual(math.copysign(1., 0.), 1.)
424 self.assertEqual(math.copysign(1., -0.), -1.)
425 self.assertEqual(math.copysign(INF, 0.), INF)
426 self.assertEqual(math.copysign(INF, -0.), NINF)
427 self.assertEqual(math.copysign(NINF, 0.), INF)
428 self.assertEqual(math.copysign(NINF, -0.), NINF)
Mark Dickinson63566232009-09-18 21:04:19 +0000429 # and of infinities
Ezio Melottib3aedd42010-11-20 19:04:17 +0000430 self.assertEqual(math.copysign(1., INF), 1.)
431 self.assertEqual(math.copysign(1., NINF), -1.)
432 self.assertEqual(math.copysign(INF, INF), INF)
433 self.assertEqual(math.copysign(INF, NINF), NINF)
434 self.assertEqual(math.copysign(NINF, INF), INF)
435 self.assertEqual(math.copysign(NINF, NINF), NINF)
Mark Dickinson06b59e02010-02-06 23:16:50 +0000436 self.assertTrue(math.isnan(math.copysign(NAN, 1.)))
437 self.assertTrue(math.isnan(math.copysign(NAN, INF)))
438 self.assertTrue(math.isnan(math.copysign(NAN, NINF)))
439 self.assertTrue(math.isnan(math.copysign(NAN, NAN)))
Mark Dickinson63566232009-09-18 21:04:19 +0000440 # copysign(INF, NAN) may be INF or it may be NINF, since
441 # we don't know whether the sign bit of NAN is set on any
442 # given platform.
Mark Dickinson06b59e02010-02-06 23:16:50 +0000443 self.assertTrue(math.isinf(math.copysign(INF, NAN)))
Mark Dickinson63566232009-09-18 21:04:19 +0000444 # similarly, copysign(2., NAN) could be 2. or -2.
Ezio Melottib3aedd42010-11-20 19:04:17 +0000445 self.assertEqual(abs(math.copysign(2., NAN)), 2.)
Christian Heimes53876d92008-04-19 00:31:39 +0000446
Thomas Wouters89f507f2006-12-13 04:49:30 +0000447 def testCos(self):
448 self.assertRaises(TypeError, math.cos)
Victor Stinner0b2ab212020-01-13 12:44:35 +0100449 self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0, abs_tol=math.ulp(1))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000450 self.ftest('cos(0)', math.cos(0), 1)
Victor Stinner0b2ab212020-01-13 12:44:35 +0100451 self.ftest('cos(pi/2)', math.cos(math.pi/2), 0, abs_tol=math.ulp(1))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000452 self.ftest('cos(pi)', math.cos(math.pi), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000453 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000454 self.assertTrue(math.isnan(math.cos(INF)))
455 self.assertTrue(math.isnan(math.cos(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +0000456 except ValueError:
457 self.assertRaises(ValueError, math.cos, INF)
458 self.assertRaises(ValueError, math.cos, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000459 self.assertTrue(math.isnan(math.cos(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000460
Paul Monsonf3550692019-06-19 13:09:54 -0700461 @unittest.skipIf(sys.platform == 'win32' and platform.machine() in ('ARM', 'ARM64'),
462 "Windows UCRT is off by 2 ULP this test requires accuracy within 1 ULP")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000463 def testCosh(self):
464 self.assertRaises(TypeError, math.cosh)
465 self.ftest('cosh(0)', math.cosh(0), 1)
466 self.ftest('cosh(2)-2*cosh(1)**2', math.cosh(2)-2*math.cosh(1)**2, -1) # Thanks to Lambert
Ezio Melottib3aedd42010-11-20 19:04:17 +0000467 self.assertEqual(math.cosh(INF), INF)
468 self.assertEqual(math.cosh(NINF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000469 self.assertTrue(math.isnan(math.cosh(NAN)))
Raymond Hettinger64108af2002-05-13 03:55:01 +0000470
Thomas Wouters89f507f2006-12-13 04:49:30 +0000471 def testDegrees(self):
472 self.assertRaises(TypeError, math.degrees)
473 self.ftest('degrees(pi)', math.degrees(math.pi), 180.0)
474 self.ftest('degrees(pi/2)', math.degrees(math.pi/2), 90.0)
475 self.ftest('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0)
Mark Dickinson31ba1c32016-09-04 12:29:14 +0100476 self.ftest('degrees(0)', math.degrees(0), 0)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000477
Thomas Wouters89f507f2006-12-13 04:49:30 +0000478 def testExp(self):
479 self.assertRaises(TypeError, math.exp)
480 self.ftest('exp(-1)', math.exp(-1), 1/math.e)
481 self.ftest('exp(0)', math.exp(0), 1)
482 self.ftest('exp(1)', math.exp(1), math.e)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000483 self.assertEqual(math.exp(INF), INF)
484 self.assertEqual(math.exp(NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000485 self.assertTrue(math.isnan(math.exp(NAN)))
Mark Dickinson31ba1c32016-09-04 12:29:14 +0100486 self.assertRaises(OverflowError, math.exp, 1000000)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000487
Thomas Wouters89f507f2006-12-13 04:49:30 +0000488 def testFabs(self):
489 self.assertRaises(TypeError, math.fabs)
490 self.ftest('fabs(-1)', math.fabs(-1), 1)
491 self.ftest('fabs(0)', math.fabs(0), 0)
492 self.ftest('fabs(1)', math.fabs(1), 1)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000493
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000494 def testFactorial(self):
Mark Dickinson4c8a9a22010-05-15 17:02:38 +0000495 self.assertEqual(math.factorial(0), 1)
Mark Dickinson4c8a9a22010-05-15 17:02:38 +0000496 total = 1
497 for i in range(1, 1000):
498 total *= i
499 self.assertEqual(math.factorial(i), total)
Mark Dickinson4c8a9a22010-05-15 17:02:38 +0000500 self.assertEqual(math.factorial(i), py_factorial(i))
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000501 self.assertRaises(ValueError, math.factorial, -1)
Mark Dickinson5990d282014-04-10 09:29:39 -0400502 self.assertRaises(ValueError, math.factorial, -10**100)
Mark Dickinson5990d282014-04-10 09:29:39 -0400503
Pablo Galindoe9ba3702018-09-03 22:20:06 +0100504 def testFactorialNonIntegers(self):
Serhiy Storchaka578c3952020-05-26 18:43:38 +0300505 self.assertRaises(TypeError, math.factorial, 5.0)
506 self.assertRaises(TypeError, math.factorial, 5.2)
507 self.assertRaises(TypeError, math.factorial, -1.0)
508 self.assertRaises(TypeError, math.factorial, -1e100)
Serhiy Storchaka231aad32019-06-17 16:57:27 +0300509 self.assertRaises(TypeError, math.factorial, decimal.Decimal('5'))
510 self.assertRaises(TypeError, math.factorial, decimal.Decimal('5.2'))
Pablo Galindoe9ba3702018-09-03 22:20:06 +0100511 self.assertRaises(TypeError, math.factorial, "5")
512
Mark Dickinson5990d282014-04-10 09:29:39 -0400513 # Other implementations may place different upper bounds.
514 @support.cpython_only
515 def testFactorialHugeInputs(self):
Serhiy Storchaka1b8a46d2019-06-17 16:58:32 +0300516 # Currently raises OverflowError for inputs that are too large
Mark Dickinson5990d282014-04-10 09:29:39 -0400517 # to fit into a C long.
518 self.assertRaises(OverflowError, math.factorial, 10**100)
Serhiy Storchaka578c3952020-05-26 18:43:38 +0300519 self.assertRaises(TypeError, math.factorial, 1e100)
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000520
Thomas Wouters89f507f2006-12-13 04:49:30 +0000521 def testFloor(self):
522 self.assertRaises(TypeError, math.floor)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000523 self.assertEqual(int, type(math.floor(0.5)))
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +0200524 self.assertEqual(math.floor(0.5), 0)
525 self.assertEqual(math.floor(1.0), 1)
526 self.assertEqual(math.floor(1.5), 1)
527 self.assertEqual(math.floor(-0.5), -1)
528 self.assertEqual(math.floor(-1.0), -1)
529 self.assertEqual(math.floor(-1.5), -2)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000530 #self.assertEqual(math.ceil(INF), INF)
531 #self.assertEqual(math.ceil(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000532 #self.assertTrue(math.isnan(math.floor(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000533
Guido van Rossum13e05de2007-08-23 22:56:55 +0000534 class TestFloor:
535 def __floor__(self):
536 return 42
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +0200537 class FloatFloor(float):
538 def __floor__(self):
539 return 42
Guido van Rossum13e05de2007-08-23 22:56:55 +0000540 class TestNoFloor:
541 pass
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +0200542 self.assertEqual(math.floor(TestFloor()), 42)
543 self.assertEqual(math.floor(FloatFloor()), 42)
544 self.assertEqual(math.floor(FloatLike(41.9)), 41)
Guido van Rossum13e05de2007-08-23 22:56:55 +0000545 self.assertRaises(TypeError, math.floor, TestNoFloor())
546
547 t = TestNoFloor()
548 t.__floor__ = lambda *args: args
549 self.assertRaises(TypeError, math.floor, t)
550 self.assertRaises(TypeError, math.floor, t, 0)
551
Thomas Wouters89f507f2006-12-13 04:49:30 +0000552 def testFmod(self):
553 self.assertRaises(TypeError, math.fmod)
Mark Dickinson5bc7a442011-05-03 21:13:40 +0100554 self.ftest('fmod(10, 1)', math.fmod(10, 1), 0.0)
555 self.ftest('fmod(10, 0.5)', math.fmod(10, 0.5), 0.0)
556 self.ftest('fmod(10, 1.5)', math.fmod(10, 1.5), 1.0)
557 self.ftest('fmod(-10, 1)', math.fmod(-10, 1), -0.0)
558 self.ftest('fmod(-10, 0.5)', math.fmod(-10, 0.5), -0.0)
559 self.ftest('fmod(-10, 1.5)', math.fmod(-10, 1.5), -1.0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000560 self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
561 self.assertTrue(math.isnan(math.fmod(1., NAN)))
562 self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000563 self.assertRaises(ValueError, math.fmod, 1., 0.)
564 self.assertRaises(ValueError, math.fmod, INF, 1.)
565 self.assertRaises(ValueError, math.fmod, NINF, 1.)
566 self.assertRaises(ValueError, math.fmod, INF, 0.)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000567 self.assertEqual(math.fmod(3.0, INF), 3.0)
568 self.assertEqual(math.fmod(-3.0, INF), -3.0)
569 self.assertEqual(math.fmod(3.0, NINF), 3.0)
570 self.assertEqual(math.fmod(-3.0, NINF), -3.0)
571 self.assertEqual(math.fmod(0.0, 3.0), 0.0)
572 self.assertEqual(math.fmod(0.0, NINF), 0.0)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000573
Thomas Wouters89f507f2006-12-13 04:49:30 +0000574 def testFrexp(self):
575 self.assertRaises(TypeError, math.frexp)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000576
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000577 def testfrexp(name, result, expected):
578 (mant, exp), (emant, eexp) = result, expected
Thomas Wouters89f507f2006-12-13 04:49:30 +0000579 if abs(mant-emant) > eps or exp != eexp:
580 self.fail('%s returned %r, expected %r'%\
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000581 (name, result, expected))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000582
Thomas Wouters89f507f2006-12-13 04:49:30 +0000583 testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
584 testfrexp('frexp(0)', math.frexp(0), (0, 0))
585 testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
586 testfrexp('frexp(2)', math.frexp(2), (0.5, 2))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000587
Ezio Melottib3aedd42010-11-20 19:04:17 +0000588 self.assertEqual(math.frexp(INF)[0], INF)
589 self.assertEqual(math.frexp(NINF)[0], NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000590 self.assertTrue(math.isnan(math.frexp(NAN)[0]))
Christian Heimes53876d92008-04-19 00:31:39 +0000591
Mark Dickinson63566232009-09-18 21:04:19 +0000592 @requires_IEEE_754
Mark Dickinson5c567082009-04-24 16:39:07 +0000593 @unittest.skipIf(HAVE_DOUBLE_ROUNDING,
594 "fsum is not exact on machines with double rounding")
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000595 def testFsum(self):
596 # math.fsum relies on exact rounding for correct operation.
597 # There's a known problem with IA32 floating-point that causes
598 # inexact rounding in some situations, and will cause the
599 # math.fsum tests below to fail; see issue #2937. On non IEEE
600 # 754 platforms, and on IEEE 754 platforms that exhibit the
601 # problem described in issue #2937, we simply skip the whole
602 # test.
603
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000604 # Python version of math.fsum, for comparison. Uses a
605 # different algorithm based on frexp, ldexp and integer
606 # arithmetic.
607 from sys import float_info
608 mant_dig = float_info.mant_dig
609 etiny = float_info.min_exp - mant_dig
610
611 def msum(iterable):
612 """Full precision summation. Compute sum(iterable) without any
613 intermediate accumulation of error. Based on the 'lsum' function
Andre Delfinoac0333e2020-09-15 17:13:26 -0300614 at https://github.com/ActiveState/code/tree/master/recipes/Python/393090_Binary_floating_point_summatiaccurate_full/recipe-393090.py
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000615
616 """
617 tmant, texp = 0, 0
618 for x in iterable:
619 mant, exp = math.frexp(x)
620 mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig
621 if texp > exp:
622 tmant <<= texp-exp
623 texp = exp
624 else:
625 mant <<= exp-texp
626 tmant += mant
627 # Round tmant * 2**texp to a float. The original recipe
628 # used float(str(tmant)) * 2.0**texp for this, but that's
629 # a little unsafe because str -> float conversion can't be
630 # relied upon to do correct rounding on all platforms.
631 tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp)
632 if tail > 0:
633 h = 1 << (tail-1)
634 tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1)
635 texp += tail
636 return math.ldexp(tmant, texp)
637
638 test_values = [
639 ([], 0.0),
640 ([0.0], 0.0),
641 ([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100),
642 ([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0),
643 ([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0),
644 ([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0),
645 ([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0),
646 ([1./n for n in range(1, 1001)],
647 float.fromhex('0x1.df11f45f4e61ap+2')),
648 ([(-1.)**n/n for n in range(1, 1001)],
649 float.fromhex('-0x1.62a2af1bd3624p-1')),
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000650 ([1e16, 1., 1e-16], 10000000000000002.0),
651 ([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0),
652 # exercise code for resizing partials array
653 ([2.**n - 2.**(n+50) + 2.**(n+52) for n in range(-1074, 972, 2)] +
654 [-2.**1022],
655 float.fromhex('0x1.5555555555555p+970')),
656 ]
657
Mark Dickinsonbba873e2019-12-09 08:36:34 -0600658 # Telescoping sum, with exact differences (due to Sterbenz)
659 terms = [1.7**i for i in range(1001)]
660 test_values.append((
661 [terms[i+1] - terms[i] for i in range(1000)] + [-terms[1000]],
662 -terms[0]
663 ))
664
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000665 for i, (vals, expected) in enumerate(test_values):
666 try:
667 actual = math.fsum(vals)
668 except OverflowError:
669 self.fail("test %d failed: got OverflowError, expected %r "
670 "for math.fsum(%.100r)" % (i, expected, vals))
671 except ValueError:
672 self.fail("test %d failed: got ValueError, expected %r "
673 "for math.fsum(%.100r)" % (i, expected, vals))
674 self.assertEqual(actual, expected)
675
676 from random import random, gauss, shuffle
677 for j in range(1000):
678 vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10
679 s = 0
680 for i in range(200):
681 v = gauss(0, random()) ** 7 - s
682 s += v
683 vals.append(v)
684 shuffle(vals)
685
686 s = msum(vals)
687 self.assertEqual(msum(vals), math.fsum(vals))
688
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300689 def testGcd(self):
690 gcd = math.gcd
691 self.assertEqual(gcd(0, 0), 0)
692 self.assertEqual(gcd(1, 0), 1)
693 self.assertEqual(gcd(-1, 0), 1)
694 self.assertEqual(gcd(0, 1), 1)
695 self.assertEqual(gcd(0, -1), 1)
696 self.assertEqual(gcd(7, 1), 1)
697 self.assertEqual(gcd(7, -1), 1)
698 self.assertEqual(gcd(-23, 15), 1)
699 self.assertEqual(gcd(120, 84), 12)
700 self.assertEqual(gcd(84, -120), 12)
701 self.assertEqual(gcd(1216342683557601535506311712,
702 436522681849110124616458784), 32)
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200703
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300704 x = 434610456570399902378880679233098819019853229470286994367836600566
705 y = 1064502245825115327754847244914921553977
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200706 for c in (652560,
707 576559230871654959816130551884856912003141446781646602790216406874):
708 a = x * c
709 b = y * c
710 self.assertEqual(gcd(a, b), c)
711 self.assertEqual(gcd(b, a), c)
712 self.assertEqual(gcd(-a, b), c)
713 self.assertEqual(gcd(b, -a), c)
714 self.assertEqual(gcd(a, -b), c)
715 self.assertEqual(gcd(-b, a), c)
716 self.assertEqual(gcd(-a, -b), c)
717 self.assertEqual(gcd(-b, -a), c)
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300718
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200719 self.assertEqual(gcd(), 0)
720 self.assertEqual(gcd(120), 120)
721 self.assertEqual(gcd(-120), 120)
722 self.assertEqual(gcd(120, 84, 102), 6)
723 self.assertEqual(gcd(120, 1, 84), 1)
724
725 self.assertRaises(TypeError, gcd, 120.0)
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300726 self.assertRaises(TypeError, gcd, 120.0, 84)
727 self.assertRaises(TypeError, gcd, 120, 84.0)
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200728 self.assertRaises(TypeError, gcd, 120, 1, 84.0)
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300729 self.assertEqual(gcd(MyIndexable(120), MyIndexable(84)), 12)
730
Thomas Wouters89f507f2006-12-13 04:49:30 +0000731 def testHypot(self):
Raymond Hettingerc6dabe32018-07-28 07:48:04 -0700732 from decimal import Decimal
733 from fractions import Fraction
734
735 hypot = math.hypot
736
737 # Test different numbers of arguments (from zero to five)
738 # against a straightforward pure python implementation
739 args = math.e, math.pi, math.sqrt(2.0), math.gamma(3.5), math.sin(2.1)
740 for i in range(len(args)+1):
741 self.assertAlmostEqual(
742 hypot(*args[:i]),
743 math.sqrt(sum(s**2 for s in args[:i]))
744 )
745
746 # Test allowable types (those with __float__)
747 self.assertEqual(hypot(12.0, 5.0), 13.0)
748 self.assertEqual(hypot(12, 5), 13)
749 self.assertEqual(hypot(Decimal(12), Decimal(5)), 13)
750 self.assertEqual(hypot(Fraction(12, 32), Fraction(5, 32)), Fraction(13, 32))
751 self.assertEqual(hypot(bool(1), bool(0), bool(1), bool(1)), math.sqrt(3))
752
753 # Test corner cases
754 self.assertEqual(hypot(0.0, 0.0), 0.0) # Max input is zero
755 self.assertEqual(hypot(-10.5), 10.5) # Negative input
756 self.assertEqual(hypot(), 0.0) # Negative input
757 self.assertEqual(1.0,
758 math.copysign(1.0, hypot(-0.0)) # Convert negative zero to positive zero
759 )
Raymond Hettinger00414592018-08-12 12:15:23 -0700760 self.assertEqual( # Handling of moving max to the end
761 hypot(1.5, 1.5, 0.5),
762 hypot(1.5, 0.5, 1.5),
763 )
Raymond Hettingerc6dabe32018-07-28 07:48:04 -0700764
765 # Test handling of bad arguments
766 with self.assertRaises(TypeError): # Reject keyword args
767 hypot(x=1)
768 with self.assertRaises(TypeError): # Reject values without __float__
769 hypot(1.1, 'string', 2.2)
Raymond Hettinger808180c2019-01-28 13:59:56 -0800770 int_too_big_for_float = 10 ** (sys.float_info.max_10_exp + 5)
771 with self.assertRaises((ValueError, OverflowError)):
772 hypot(1, int_too_big_for_float)
Raymond Hettingerc6dabe32018-07-28 07:48:04 -0700773
774 # Any infinity gives positive infinity.
775 self.assertEqual(hypot(INF), INF)
776 self.assertEqual(hypot(0, INF), INF)
777 self.assertEqual(hypot(10, INF), INF)
778 self.assertEqual(hypot(-10, INF), INF)
779 self.assertEqual(hypot(NAN, INF), INF)
780 self.assertEqual(hypot(INF, NAN), INF)
781 self.assertEqual(hypot(NINF, NAN), INF)
782 self.assertEqual(hypot(NAN, NINF), INF)
783 self.assertEqual(hypot(-INF, INF), INF)
784 self.assertEqual(hypot(-INF, -INF), INF)
785 self.assertEqual(hypot(10, -INF), INF)
786
Raymond Hettinger00414592018-08-12 12:15:23 -0700787 # If no infinity, any NaN gives a NaN.
Raymond Hettingerc6dabe32018-07-28 07:48:04 -0700788 self.assertTrue(math.isnan(hypot(NAN)))
789 self.assertTrue(math.isnan(hypot(0, NAN)))
790 self.assertTrue(math.isnan(hypot(NAN, 10)))
791 self.assertTrue(math.isnan(hypot(10, NAN)))
792 self.assertTrue(math.isnan(hypot(NAN, NAN)))
793 self.assertTrue(math.isnan(hypot(NAN)))
794
795 # Verify scaling for extremely large values
796 fourthmax = FLOAT_MAX / 4.0
797 for n in range(32):
Raymond Hettingerfff3c282020-08-15 19:38:19 -0700798 self.assertTrue(math.isclose(hypot(*([fourthmax]*n)),
799 fourthmax * math.sqrt(n)))
Raymond Hettingerc6dabe32018-07-28 07:48:04 -0700800
801 # Verify scaling for extremely small values
802 for exp in range(32):
803 scale = FLOAT_MIN / 2.0 ** exp
804 self.assertEqual(math.hypot(4*scale, 3*scale), 5*scale)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000805
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700806 def testDist(self):
807 from decimal import Decimal as D
808 from fractions import Fraction as F
809
810 dist = math.dist
811 sqrt = math.sqrt
812
Raymond Hettinger808180c2019-01-28 13:59:56 -0800813 # Simple exact cases
814 self.assertEqual(dist((1.0, 2.0, 3.0), (4.0, 2.0, -1.0)), 5.0)
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700815 self.assertEqual(dist((1, 2, 3), (4, 2, -1)), 5.0)
816
817 # Test different numbers of arguments (from zero to nine)
818 # against a straightforward pure python implementation
819 for i in range(9):
820 for j in range(5):
821 p = tuple(random.uniform(-5, 5) for k in range(i))
822 q = tuple(random.uniform(-5, 5) for k in range(i))
823 self.assertAlmostEqual(
824 dist(p, q),
825 sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
826 )
827
Raymond Hettinger6b5f1b42019-07-27 14:04:29 -0700828 # Test non-tuple inputs
829 self.assertEqual(dist([1.0, 2.0, 3.0], [4.0, 2.0, -1.0]), 5.0)
830 self.assertEqual(dist(iter([1.0, 2.0, 3.0]), iter([4.0, 2.0, -1.0])), 5.0)
831
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700832 # Test allowable types (those with __float__)
833 self.assertEqual(dist((14.0, 1.0), (2.0, -4.0)), 13.0)
834 self.assertEqual(dist((14, 1), (2, -4)), 13)
835 self.assertEqual(dist((D(14), D(1)), (D(2), D(-4))), D(13))
836 self.assertEqual(dist((F(14, 32), F(1, 32)), (F(2, 32), F(-4, 32))),
837 F(13, 32))
838 self.assertEqual(dist((True, True, False, True, False),
839 (True, False, True, True, False)),
840 sqrt(2.0))
841
842 # Test corner cases
843 self.assertEqual(dist((13.25, 12.5, -3.25),
844 (13.25, 12.5, -3.25)),
845 0.0) # Distance with self is zero
846 self.assertEqual(dist((), ()), 0.0) # Zero-dimensional case
847 self.assertEqual(1.0, # Convert negative zero to positive zero
848 math.copysign(1.0, dist((-0.0,), (0.0,)))
849 )
850 self.assertEqual(1.0, # Convert negative zero to positive zero
851 math.copysign(1.0, dist((0.0,), (-0.0,)))
852 )
Raymond Hettinger00414592018-08-12 12:15:23 -0700853 self.assertEqual( # Handling of moving max to the end
854 dist((1.5, 1.5, 0.5), (0, 0, 0)),
855 dist((1.5, 0.5, 1.5), (0, 0, 0))
856 )
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700857
858 # Verify tuple subclasses are allowed
Raymond Hettinger00414592018-08-12 12:15:23 -0700859 class T(tuple):
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700860 pass
861 self.assertEqual(dist(T((1, 2, 3)), ((4, 2, -1))), 5.0)
862
863 # Test handling of bad arguments
864 with self.assertRaises(TypeError): # Reject keyword args
865 dist(p=(1, 2, 3), q=(4, 5, 6))
866 with self.assertRaises(TypeError): # Too few args
867 dist((1, 2, 3))
868 with self.assertRaises(TypeError): # Too many args
869 dist((1, 2, 3), (4, 5, 6), (7, 8, 9))
870 with self.assertRaises(TypeError): # Scalars not allowed
871 dist(1, 2)
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700872 with self.assertRaises(TypeError): # Reject values without __float__
873 dist((1.1, 'string', 2.2), (1, 2, 3))
874 with self.assertRaises(ValueError): # Check dimension agree
875 dist((1, 2, 3, 4), (5, 6, 7))
876 with self.assertRaises(ValueError): # Check dimension agree
877 dist((1, 2, 3), (4, 5, 6, 7))
Ammar Askarcb08a712019-01-12 01:23:41 -0500878 with self.assertRaises(TypeError): # Rejects invalid types
879 dist("abc", "xyz")
Raymond Hettinger808180c2019-01-28 13:59:56 -0800880 int_too_big_for_float = 10 ** (sys.float_info.max_10_exp + 5)
881 with self.assertRaises((ValueError, OverflowError)):
882 dist((1, int_too_big_for_float), (2, 3))
883 with self.assertRaises((ValueError, OverflowError)):
884 dist((2, 3), (1, int_too_big_for_float))
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700885
Raymond Hettinger00414592018-08-12 12:15:23 -0700886 # Verify that the one dimensional case is equivalent to abs()
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700887 for i in range(20):
888 p, q = random.random(), random.random()
889 self.assertEqual(dist((p,), (q,)), abs(p - q))
890
891 # Test special values
892 values = [NINF, -10.5, -0.0, 0.0, 10.5, INF, NAN]
893 for p in itertools.product(values, repeat=3):
894 for q in itertools.product(values, repeat=3):
895 diffs = [px - qx for px, qx in zip(p, q)]
896 if any(map(math.isinf, diffs)):
897 # Any infinite difference gives positive infinity.
898 self.assertEqual(dist(p, q), INF)
899 elif any(map(math.isnan, diffs)):
Raymond Hettinger00414592018-08-12 12:15:23 -0700900 # If no infinity, any NaN gives a NaN.
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700901 self.assertTrue(math.isnan(dist(p, q)))
902
903 # Verify scaling for extremely large values
904 fourthmax = FLOAT_MAX / 4.0
905 for n in range(32):
906 p = (fourthmax,) * n
907 q = (0.0,) * n
Raymond Hettingerfff3c282020-08-15 19:38:19 -0700908 self.assertTrue(math.isclose(dist(p, q), fourthmax * math.sqrt(n)))
909 self.assertTrue(math.isclose(dist(q, p), fourthmax * math.sqrt(n)))
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700910
911 # Verify scaling for extremely small values
912 for exp in range(32):
913 scale = FLOAT_MIN / 2.0 ** exp
914 p = (4*scale, 3*scale)
915 q = (0.0, 0.0)
916 self.assertEqual(math.dist(p, q), 5*scale)
917 self.assertEqual(math.dist(q, p), 5*scale)
918
Mark Dickinson73934b92019-05-18 12:29:50 +0100919 def testIsqrt(self):
920 # Test a variety of inputs, large and small.
921 test_values = (
922 list(range(1000))
923 + list(range(10**6 - 1000, 10**6 + 1000))
Mark Dickinson5c08ce92019-05-19 17:51:56 +0100924 + [2**e + i for e in range(60, 200) for i in range(-40, 40)]
Mark Dickinson73934b92019-05-18 12:29:50 +0100925 + [3**9999, 10**5001]
926 )
927
928 for value in test_values:
929 with self.subTest(value=value):
930 s = math.isqrt(value)
931 self.assertIs(type(s), int)
932 self.assertLessEqual(s*s, value)
933 self.assertLess(value, (s+1)*(s+1))
934
935 # Negative values
936 with self.assertRaises(ValueError):
937 math.isqrt(-1)
938
939 # Integer-like things
940 s = math.isqrt(True)
941 self.assertIs(type(s), int)
942 self.assertEqual(s, 1)
943
944 s = math.isqrt(False)
945 self.assertIs(type(s), int)
946 self.assertEqual(s, 0)
947
948 class IntegerLike(object):
949 def __init__(self, value):
950 self.value = value
951
952 def __index__(self):
953 return self.value
954
955 s = math.isqrt(IntegerLike(1729))
956 self.assertIs(type(s), int)
957 self.assertEqual(s, 41)
958
959 with self.assertRaises(ValueError):
960 math.isqrt(IntegerLike(-3))
961
962 # Non-integer-like things
963 bad_values = [
964 3.5, "a string", decimal.Decimal("3.5"), 3.5j,
965 100.0, -4.0,
966 ]
967 for value in bad_values:
968 with self.subTest(value=value):
969 with self.assertRaises(TypeError):
970 math.isqrt(value)
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700971
ananthan-123f2ee21d2020-02-19 23:51:37 +0530972 def test_lcm(self):
973 lcm = math.lcm
974 self.assertEqual(lcm(0, 0), 0)
975 self.assertEqual(lcm(1, 0), 0)
976 self.assertEqual(lcm(-1, 0), 0)
977 self.assertEqual(lcm(0, 1), 0)
978 self.assertEqual(lcm(0, -1), 0)
979 self.assertEqual(lcm(7, 1), 7)
980 self.assertEqual(lcm(7, -1), 7)
981 self.assertEqual(lcm(-23, 15), 345)
982 self.assertEqual(lcm(120, 84), 840)
983 self.assertEqual(lcm(84, -120), 840)
984 self.assertEqual(lcm(1216342683557601535506311712,
985 436522681849110124616458784),
986 16592536571065866494401400422922201534178938447014944)
Serhiy Storchaka559e7f12020-02-23 13:21:29 +0200987
ananthan-123f2ee21d2020-02-19 23:51:37 +0530988 x = 43461045657039990237
989 y = 10645022458251153277
ananthan-123f2ee21d2020-02-19 23:51:37 +0530990 for c in (652560,
991 57655923087165495981):
992 a = x * c
993 b = y * c
994 d = x * y * c
995 self.assertEqual(lcm(a, b), d)
996 self.assertEqual(lcm(b, a), d)
997 self.assertEqual(lcm(-a, b), d)
998 self.assertEqual(lcm(b, -a), d)
999 self.assertEqual(lcm(a, -b), d)
1000 self.assertEqual(lcm(-b, a), d)
1001 self.assertEqual(lcm(-a, -b), d)
1002 self.assertEqual(lcm(-b, -a), d)
Serhiy Storchaka559e7f12020-02-23 13:21:29 +02001003
1004 self.assertEqual(lcm(), 1)
1005 self.assertEqual(lcm(120), 120)
1006 self.assertEqual(lcm(-120), 120)
1007 self.assertEqual(lcm(120, 84, 102), 14280)
1008 self.assertEqual(lcm(120, 0, 84), 0)
1009
1010 self.assertRaises(TypeError, lcm, 120.0)
ananthan-123f2ee21d2020-02-19 23:51:37 +05301011 self.assertRaises(TypeError, lcm, 120.0, 84)
1012 self.assertRaises(TypeError, lcm, 120, 84.0)
Serhiy Storchaka559e7f12020-02-23 13:21:29 +02001013 self.assertRaises(TypeError, lcm, 120, 0, 84.0)
1014 self.assertEqual(lcm(MyIndexable(120), MyIndexable(84)), 840)
ananthan-123f2ee21d2020-02-19 23:51:37 +05301015
Thomas Wouters89f507f2006-12-13 04:49:30 +00001016 def testLdexp(self):
1017 self.assertRaises(TypeError, math.ldexp)
1018 self.ftest('ldexp(0,1)', math.ldexp(0,1), 0)
1019 self.ftest('ldexp(1,1)', math.ldexp(1,1), 2)
1020 self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5)
1021 self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2)
Christian Heimes53876d92008-04-19 00:31:39 +00001022 self.assertRaises(OverflowError, math.ldexp, 1., 1000000)
1023 self.assertRaises(OverflowError, math.ldexp, -1., 1000000)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001024 self.assertEqual(math.ldexp(1., -1000000), 0.)
1025 self.assertEqual(math.ldexp(-1., -1000000), -0.)
1026 self.assertEqual(math.ldexp(INF, 30), INF)
1027 self.assertEqual(math.ldexp(NINF, -213), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001028 self.assertTrue(math.isnan(math.ldexp(NAN, 0)))
Guido van Rossumfcce6301996-08-08 18:26:25 +00001029
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001030 # large second argument
1031 for n in [10**5, 10**10, 10**20, 10**40]:
Ezio Melottib3aedd42010-11-20 19:04:17 +00001032 self.assertEqual(math.ldexp(INF, -n), INF)
1033 self.assertEqual(math.ldexp(NINF, -n), NINF)
1034 self.assertEqual(math.ldexp(1., -n), 0.)
1035 self.assertEqual(math.ldexp(-1., -n), -0.)
1036 self.assertEqual(math.ldexp(0., -n), 0.)
1037 self.assertEqual(math.ldexp(-0., -n), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001038 self.assertTrue(math.isnan(math.ldexp(NAN, -n)))
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001039
1040 self.assertRaises(OverflowError, math.ldexp, 1., n)
1041 self.assertRaises(OverflowError, math.ldexp, -1., n)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001042 self.assertEqual(math.ldexp(0., n), 0.)
1043 self.assertEqual(math.ldexp(-0., n), -0.)
1044 self.assertEqual(math.ldexp(INF, n), INF)
1045 self.assertEqual(math.ldexp(NINF, n), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001046 self.assertTrue(math.isnan(math.ldexp(NAN, n)))
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00001047
Thomas Wouters89f507f2006-12-13 04:49:30 +00001048 def testLog(self):
1049 self.assertRaises(TypeError, math.log)
1050 self.ftest('log(1/e)', math.log(1/math.e), -1)
1051 self.ftest('log(1)', math.log(1), 0)
1052 self.ftest('log(e)', math.log(math.e), 1)
1053 self.ftest('log(32,2)', math.log(32,2), 5)
1054 self.ftest('log(10**40, 10)', math.log(10**40, 10), 40)
1055 self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2)
Mark Dickinsonc6037172010-09-29 19:06:36 +00001056 self.ftest('log(10**1000)', math.log(10**1000),
1057 2302.5850929940457)
1058 self.assertRaises(ValueError, math.log, -1.5)
1059 self.assertRaises(ValueError, math.log, -10**1000)
Christian Heimes53876d92008-04-19 00:31:39 +00001060 self.assertRaises(ValueError, math.log, NINF)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001061 self.assertEqual(math.log(INF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001062 self.assertTrue(math.isnan(math.log(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +00001063
1064 def testLog1p(self):
1065 self.assertRaises(TypeError, math.log1p)
Mark Dickinson31ba1c32016-09-04 12:29:14 +01001066 for n in [2, 2**90, 2**300]:
1067 self.assertAlmostEqual(math.log1p(n), math.log1p(float(n)))
1068 self.assertRaises(ValueError, math.log1p, -1)
1069 self.assertEqual(math.log1p(INF), INF)
Guido van Rossumfcce6301996-08-08 18:26:25 +00001070
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001071 @requires_IEEE_754
1072 def testLog2(self):
1073 self.assertRaises(TypeError, math.log2)
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001074
1075 # Check some integer values
1076 self.assertEqual(math.log2(1), 0.0)
1077 self.assertEqual(math.log2(2), 1.0)
1078 self.assertEqual(math.log2(4), 2.0)
1079
1080 # Large integer values
1081 self.assertEqual(math.log2(2**1023), 1023.0)
1082 self.assertEqual(math.log2(2**1024), 1024.0)
1083 self.assertEqual(math.log2(2**2000), 2000.0)
1084
1085 self.assertRaises(ValueError, math.log2, -1.5)
1086 self.assertRaises(ValueError, math.log2, NINF)
1087 self.assertTrue(math.isnan(math.log2(NAN)))
1088
Victor Stinnercd9dd372011-05-10 23:40:17 +02001089 @requires_IEEE_754
Victor Stinnerebbbdaf2011-06-01 13:19:07 +02001090 # log2() is not accurate enough on Mac OS X Tiger (10.4)
1091 @support.requires_mac_ver(10, 5)
Victor Stinnercd9dd372011-05-10 23:40:17 +02001092 def testLog2Exact(self):
1093 # Check that we get exact equality for log2 of powers of 2.
1094 actual = [math.log2(math.ldexp(1.0, n)) for n in range(-1074, 1024)]
1095 expected = [float(n) for n in range(-1074, 1024)]
1096 self.assertEqual(actual, expected)
1097
Thomas Wouters89f507f2006-12-13 04:49:30 +00001098 def testLog10(self):
1099 self.assertRaises(TypeError, math.log10)
1100 self.ftest('log10(0.1)', math.log10(0.1), -1)
1101 self.ftest('log10(1)', math.log10(1), 0)
1102 self.ftest('log10(10)', math.log10(10), 1)
Mark Dickinsonc6037172010-09-29 19:06:36 +00001103 self.ftest('log10(10**1000)', math.log10(10**1000), 1000.0)
1104 self.assertRaises(ValueError, math.log10, -1.5)
1105 self.assertRaises(ValueError, math.log10, -10**1000)
Christian Heimes53876d92008-04-19 00:31:39 +00001106 self.assertRaises(ValueError, math.log10, NINF)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001107 self.assertEqual(math.log(INF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001108 self.assertTrue(math.isnan(math.log10(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +00001109
Thomas Wouters89f507f2006-12-13 04:49:30 +00001110 def testModf(self):
1111 self.assertRaises(TypeError, math.modf)
Guido van Rossumfcce6301996-08-08 18:26:25 +00001112
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001113 def testmodf(name, result, expected):
1114 (v1, v2), (e1, e2) = result, expected
Thomas Wouters89f507f2006-12-13 04:49:30 +00001115 if abs(v1-e1) > eps or abs(v2-e2):
1116 self.fail('%s returned %r, expected %r'%\
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001117 (name, result, expected))
Raymond Hettinger64108af2002-05-13 03:55:01 +00001118
Thomas Wouters89f507f2006-12-13 04:49:30 +00001119 testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
1120 testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
Guido van Rossumfcce6301996-08-08 18:26:25 +00001121
Ezio Melottib3aedd42010-11-20 19:04:17 +00001122 self.assertEqual(math.modf(INF), (0.0, INF))
1123 self.assertEqual(math.modf(NINF), (-0.0, NINF))
Christian Heimes53876d92008-04-19 00:31:39 +00001124
1125 modf_nan = math.modf(NAN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001126 self.assertTrue(math.isnan(modf_nan[0]))
1127 self.assertTrue(math.isnan(modf_nan[1]))
Christian Heimes53876d92008-04-19 00:31:39 +00001128
Thomas Wouters89f507f2006-12-13 04:49:30 +00001129 def testPow(self):
1130 self.assertRaises(TypeError, math.pow)
1131 self.ftest('pow(0,1)', math.pow(0,1), 0)
1132 self.ftest('pow(1,0)', math.pow(1,0), 1)
1133 self.ftest('pow(2,1)', math.pow(2,1), 2)
1134 self.ftest('pow(2,-1)', math.pow(2,-1), 0.5)
Christian Heimes53876d92008-04-19 00:31:39 +00001135 self.assertEqual(math.pow(INF, 1), INF)
1136 self.assertEqual(math.pow(NINF, 1), NINF)
1137 self.assertEqual((math.pow(1, INF)), 1.)
1138 self.assertEqual((math.pow(1, NINF)), 1.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001139 self.assertTrue(math.isnan(math.pow(NAN, 1)))
1140 self.assertTrue(math.isnan(math.pow(2, NAN)))
1141 self.assertTrue(math.isnan(math.pow(0, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +00001142 self.assertEqual(math.pow(1, NAN), 1)
Christian Heimesa342c012008-04-20 21:01:16 +00001143
1144 # pow(0., x)
1145 self.assertEqual(math.pow(0., INF), 0.)
1146 self.assertEqual(math.pow(0., 3.), 0.)
1147 self.assertEqual(math.pow(0., 2.3), 0.)
1148 self.assertEqual(math.pow(0., 2.), 0.)
1149 self.assertEqual(math.pow(0., 0.), 1.)
1150 self.assertEqual(math.pow(0., -0.), 1.)
1151 self.assertRaises(ValueError, math.pow, 0., -2.)
1152 self.assertRaises(ValueError, math.pow, 0., -2.3)
1153 self.assertRaises(ValueError, math.pow, 0., -3.)
1154 self.assertRaises(ValueError, math.pow, 0., NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001155 self.assertTrue(math.isnan(math.pow(0., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +00001156
1157 # pow(INF, x)
1158 self.assertEqual(math.pow(INF, INF), INF)
1159 self.assertEqual(math.pow(INF, 3.), INF)
1160 self.assertEqual(math.pow(INF, 2.3), INF)
1161 self.assertEqual(math.pow(INF, 2.), INF)
1162 self.assertEqual(math.pow(INF, 0.), 1.)
1163 self.assertEqual(math.pow(INF, -0.), 1.)
1164 self.assertEqual(math.pow(INF, -2.), 0.)
1165 self.assertEqual(math.pow(INF, -2.3), 0.)
1166 self.assertEqual(math.pow(INF, -3.), 0.)
1167 self.assertEqual(math.pow(INF, NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001168 self.assertTrue(math.isnan(math.pow(INF, NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +00001169
1170 # pow(-0., x)
1171 self.assertEqual(math.pow(-0., INF), 0.)
1172 self.assertEqual(math.pow(-0., 3.), -0.)
1173 self.assertEqual(math.pow(-0., 2.3), 0.)
1174 self.assertEqual(math.pow(-0., 2.), 0.)
1175 self.assertEqual(math.pow(-0., 0.), 1.)
1176 self.assertEqual(math.pow(-0., -0.), 1.)
1177 self.assertRaises(ValueError, math.pow, -0., -2.)
1178 self.assertRaises(ValueError, math.pow, -0., -2.3)
1179 self.assertRaises(ValueError, math.pow, -0., -3.)
1180 self.assertRaises(ValueError, math.pow, -0., NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001181 self.assertTrue(math.isnan(math.pow(-0., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +00001182
1183 # pow(NINF, x)
1184 self.assertEqual(math.pow(NINF, INF), INF)
1185 self.assertEqual(math.pow(NINF, 3.), NINF)
1186 self.assertEqual(math.pow(NINF, 2.3), INF)
1187 self.assertEqual(math.pow(NINF, 2.), INF)
1188 self.assertEqual(math.pow(NINF, 0.), 1.)
1189 self.assertEqual(math.pow(NINF, -0.), 1.)
1190 self.assertEqual(math.pow(NINF, -2.), 0.)
1191 self.assertEqual(math.pow(NINF, -2.3), 0.)
1192 self.assertEqual(math.pow(NINF, -3.), -0.)
1193 self.assertEqual(math.pow(NINF, NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001194 self.assertTrue(math.isnan(math.pow(NINF, NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +00001195
1196 # pow(-1, x)
1197 self.assertEqual(math.pow(-1., INF), 1.)
1198 self.assertEqual(math.pow(-1., 3.), -1.)
1199 self.assertRaises(ValueError, math.pow, -1., 2.3)
1200 self.assertEqual(math.pow(-1., 2.), 1.)
1201 self.assertEqual(math.pow(-1., 0.), 1.)
1202 self.assertEqual(math.pow(-1., -0.), 1.)
1203 self.assertEqual(math.pow(-1., -2.), 1.)
1204 self.assertRaises(ValueError, math.pow, -1., -2.3)
1205 self.assertEqual(math.pow(-1., -3.), -1.)
1206 self.assertEqual(math.pow(-1., NINF), 1.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001207 self.assertTrue(math.isnan(math.pow(-1., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +00001208
1209 # pow(1, x)
1210 self.assertEqual(math.pow(1., INF), 1.)
1211 self.assertEqual(math.pow(1., 3.), 1.)
1212 self.assertEqual(math.pow(1., 2.3), 1.)
1213 self.assertEqual(math.pow(1., 2.), 1.)
1214 self.assertEqual(math.pow(1., 0.), 1.)
1215 self.assertEqual(math.pow(1., -0.), 1.)
1216 self.assertEqual(math.pow(1., -2.), 1.)
1217 self.assertEqual(math.pow(1., -2.3), 1.)
1218 self.assertEqual(math.pow(1., -3.), 1.)
1219 self.assertEqual(math.pow(1., NINF), 1.)
1220 self.assertEqual(math.pow(1., NAN), 1.)
1221
1222 # pow(x, 0) should be 1 for any x
1223 self.assertEqual(math.pow(2.3, 0.), 1.)
1224 self.assertEqual(math.pow(-2.3, 0.), 1.)
1225 self.assertEqual(math.pow(NAN, 0.), 1.)
1226 self.assertEqual(math.pow(2.3, -0.), 1.)
1227 self.assertEqual(math.pow(-2.3, -0.), 1.)
1228 self.assertEqual(math.pow(NAN, -0.), 1.)
1229
1230 # pow(x, y) is invalid if x is negative and y is not integral
1231 self.assertRaises(ValueError, math.pow, -1., 2.3)
1232 self.assertRaises(ValueError, math.pow, -15., -3.1)
1233
1234 # pow(x, NINF)
1235 self.assertEqual(math.pow(1.9, NINF), 0.)
1236 self.assertEqual(math.pow(1.1, NINF), 0.)
1237 self.assertEqual(math.pow(0.9, NINF), INF)
1238 self.assertEqual(math.pow(0.1, NINF), INF)
1239 self.assertEqual(math.pow(-0.1, NINF), INF)
1240 self.assertEqual(math.pow(-0.9, NINF), INF)
1241 self.assertEqual(math.pow(-1.1, NINF), 0.)
1242 self.assertEqual(math.pow(-1.9, NINF), 0.)
1243
1244 # pow(x, INF)
1245 self.assertEqual(math.pow(1.9, INF), INF)
1246 self.assertEqual(math.pow(1.1, INF), INF)
1247 self.assertEqual(math.pow(0.9, INF), 0.)
1248 self.assertEqual(math.pow(0.1, INF), 0.)
1249 self.assertEqual(math.pow(-0.1, INF), 0.)
1250 self.assertEqual(math.pow(-0.9, INF), 0.)
1251 self.assertEqual(math.pow(-1.1, INF), INF)
1252 self.assertEqual(math.pow(-1.9, INF), INF)
1253
1254 # pow(x, y) should work for x negative, y an integer
1255 self.ftest('(-2.)**3.', math.pow(-2.0, 3.0), -8.0)
1256 self.ftest('(-2.)**2.', math.pow(-2.0, 2.0), 4.0)
1257 self.ftest('(-2.)**1.', math.pow(-2.0, 1.0), -2.0)
1258 self.ftest('(-2.)**0.', math.pow(-2.0, 0.0), 1.0)
1259 self.ftest('(-2.)**-0.', math.pow(-2.0, -0.0), 1.0)
1260 self.ftest('(-2.)**-1.', math.pow(-2.0, -1.0), -0.5)
1261 self.ftest('(-2.)**-2.', math.pow(-2.0, -2.0), 0.25)
1262 self.ftest('(-2.)**-3.', math.pow(-2.0, -3.0), -0.125)
1263 self.assertRaises(ValueError, math.pow, -2.0, -0.5)
1264 self.assertRaises(ValueError, math.pow, -2.0, 0.5)
1265
1266 # the following tests have been commented out since they don't
1267 # really belong here: the implementation of ** for floats is
Ezio Melotti13925002011-03-16 11:05:33 +02001268 # independent of the implementation of math.pow
Christian Heimesa342c012008-04-20 21:01:16 +00001269 #self.assertEqual(1**NAN, 1)
1270 #self.assertEqual(1**INF, 1)
1271 #self.assertEqual(1**NINF, 1)
1272 #self.assertEqual(1**0, 1)
1273 #self.assertEqual(1.**NAN, 1)
1274 #self.assertEqual(1.**INF, 1)
1275 #self.assertEqual(1.**NINF, 1)
1276 #self.assertEqual(1.**0, 1)
Guido van Rossumfcce6301996-08-08 18:26:25 +00001277
Thomas Wouters89f507f2006-12-13 04:49:30 +00001278 def testRadians(self):
1279 self.assertRaises(TypeError, math.radians)
1280 self.ftest('radians(180)', math.radians(180), math.pi)
1281 self.ftest('radians(90)', math.radians(90), math.pi/2)
1282 self.ftest('radians(-45)', math.radians(-45), -math.pi/4)
Mark Dickinson31ba1c32016-09-04 12:29:14 +01001283 self.ftest('radians(0)', math.radians(0), 0)
Guido van Rossumfcce6301996-08-08 18:26:25 +00001284
Mark Dickinsona0ce3752017-04-05 18:34:27 +01001285 @requires_IEEE_754
1286 def testRemainder(self):
1287 from fractions import Fraction
1288
1289 def validate_spec(x, y, r):
1290 """
1291 Check that r matches remainder(x, y) according to the IEEE 754
1292 specification. Assumes that x, y and r are finite and y is nonzero.
1293 """
1294 fx, fy, fr = Fraction(x), Fraction(y), Fraction(r)
1295 # r should not exceed y/2 in absolute value
1296 self.assertLessEqual(abs(fr), abs(fy/2))
1297 # x - r should be an exact integer multiple of y
1298 n = (fx - fr) / fy
1299 self.assertEqual(n, int(n))
1300 if abs(fr) == abs(fy/2):
1301 # If |r| == |y/2|, n should be even.
1302 self.assertEqual(n/2, int(n/2))
1303
1304 # triples (x, y, remainder(x, y)) in hexadecimal form.
1305 testcases = [
1306 # Remainders modulo 1, showing the ties-to-even behaviour.
1307 '-4.0 1 -0.0',
1308 '-3.8 1 0.8',
1309 '-3.0 1 -0.0',
1310 '-2.8 1 -0.8',
1311 '-2.0 1 -0.0',
1312 '-1.8 1 0.8',
1313 '-1.0 1 -0.0',
1314 '-0.8 1 -0.8',
1315 '-0.0 1 -0.0',
1316 ' 0.0 1 0.0',
1317 ' 0.8 1 0.8',
1318 ' 1.0 1 0.0',
1319 ' 1.8 1 -0.8',
1320 ' 2.0 1 0.0',
1321 ' 2.8 1 0.8',
1322 ' 3.0 1 0.0',
1323 ' 3.8 1 -0.8',
1324 ' 4.0 1 0.0',
1325
1326 # Reductions modulo 2*pi
1327 '0x0.0p+0 0x1.921fb54442d18p+2 0x0.0p+0',
1328 '0x1.921fb54442d18p+0 0x1.921fb54442d18p+2 0x1.921fb54442d18p+0',
1329 '0x1.921fb54442d17p+1 0x1.921fb54442d18p+2 0x1.921fb54442d17p+1',
1330 '0x1.921fb54442d18p+1 0x1.921fb54442d18p+2 0x1.921fb54442d18p+1',
1331 '0x1.921fb54442d19p+1 0x1.921fb54442d18p+2 -0x1.921fb54442d17p+1',
1332 '0x1.921fb54442d17p+2 0x1.921fb54442d18p+2 -0x0.0000000000001p+2',
1333 '0x1.921fb54442d18p+2 0x1.921fb54442d18p+2 0x0p0',
1334 '0x1.921fb54442d19p+2 0x1.921fb54442d18p+2 0x0.0000000000001p+2',
1335 '0x1.2d97c7f3321d1p+3 0x1.921fb54442d18p+2 0x1.921fb54442d14p+1',
1336 '0x1.2d97c7f3321d2p+3 0x1.921fb54442d18p+2 -0x1.921fb54442d18p+1',
1337 '0x1.2d97c7f3321d3p+3 0x1.921fb54442d18p+2 -0x1.921fb54442d14p+1',
1338 '0x1.921fb54442d17p+3 0x1.921fb54442d18p+2 -0x0.0000000000001p+3',
1339 '0x1.921fb54442d18p+3 0x1.921fb54442d18p+2 0x0p0',
1340 '0x1.921fb54442d19p+3 0x1.921fb54442d18p+2 0x0.0000000000001p+3',
1341 '0x1.f6a7a2955385dp+3 0x1.921fb54442d18p+2 0x1.921fb54442d14p+1',
1342 '0x1.f6a7a2955385ep+3 0x1.921fb54442d18p+2 0x1.921fb54442d18p+1',
1343 '0x1.f6a7a2955385fp+3 0x1.921fb54442d18p+2 -0x1.921fb54442d14p+1',
1344 '0x1.1475cc9eedf00p+5 0x1.921fb54442d18p+2 0x1.921fb54442d10p+1',
1345 '0x1.1475cc9eedf01p+5 0x1.921fb54442d18p+2 -0x1.921fb54442d10p+1',
1346
1347 # Symmetry with respect to signs.
1348 ' 1 0.c 0.4',
1349 '-1 0.c -0.4',
1350 ' 1 -0.c 0.4',
1351 '-1 -0.c -0.4',
1352 ' 1.4 0.c -0.4',
1353 '-1.4 0.c 0.4',
1354 ' 1.4 -0.c -0.4',
1355 '-1.4 -0.c 0.4',
1356
1357 # Huge modulus, to check that the underlying algorithm doesn't
1358 # rely on 2.0 * modulus being representable.
1359 '0x1.dp+1023 0x1.4p+1023 0x0.9p+1023',
1360 '0x1.ep+1023 0x1.4p+1023 -0x0.ap+1023',
1361 '0x1.fp+1023 0x1.4p+1023 -0x0.9p+1023',
1362 ]
1363
1364 for case in testcases:
1365 with self.subTest(case=case):
1366 x_hex, y_hex, expected_hex = case.split()
1367 x = float.fromhex(x_hex)
1368 y = float.fromhex(y_hex)
1369 expected = float.fromhex(expected_hex)
1370 validate_spec(x, y, expected)
1371 actual = math.remainder(x, y)
1372 # Cheap way of checking that the floats are
1373 # as identical as we need them to be.
1374 self.assertEqual(actual.hex(), expected.hex())
1375
1376 # Test tiny subnormal modulus: there's potential for
1377 # getting the implementation wrong here (for example,
1378 # by assuming that modulus/2 is exactly representable).
1379 tiny = float.fromhex('1p-1074') # min +ve subnormal
1380 for n in range(-25, 25):
1381 if n == 0:
1382 continue
1383 y = n * tiny
1384 for m in range(100):
1385 x = m * tiny
1386 actual = math.remainder(x, y)
1387 validate_spec(x, y, actual)
1388 actual = math.remainder(-x, y)
1389 validate_spec(-x, y, actual)
1390
1391 # Special values.
1392 # NaNs should propagate as usual.
1393 for value in [NAN, 0.0, -0.0, 2.0, -2.3, NINF, INF]:
1394 self.assertIsNaN(math.remainder(NAN, value))
1395 self.assertIsNaN(math.remainder(value, NAN))
1396
1397 # remainder(x, inf) is x, for non-nan non-infinite x.
1398 for value in [-2.3, -0.0, 0.0, 2.3]:
1399 self.assertEqual(math.remainder(value, INF), value)
1400 self.assertEqual(math.remainder(value, NINF), value)
1401
1402 # remainder(x, 0) and remainder(infinity, x) for non-NaN x are invalid
1403 # operations according to IEEE 754-2008 7.2(f), and should raise.
1404 for value in [NINF, -2.3, -0.0, 0.0, 2.3, INF]:
1405 with self.assertRaises(ValueError):
1406 math.remainder(INF, value)
1407 with self.assertRaises(ValueError):
1408 math.remainder(NINF, value)
1409 with self.assertRaises(ValueError):
1410 math.remainder(value, 0.0)
1411 with self.assertRaises(ValueError):
1412 math.remainder(value, -0.0)
1413
Thomas Wouters89f507f2006-12-13 04:49:30 +00001414 def testSin(self):
1415 self.assertRaises(TypeError, math.sin)
1416 self.ftest('sin(0)', math.sin(0), 0)
1417 self.ftest('sin(pi/2)', math.sin(math.pi/2), 1)
1418 self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1)
Christian Heimes53876d92008-04-19 00:31:39 +00001419 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001420 self.assertTrue(math.isnan(math.sin(INF)))
1421 self.assertTrue(math.isnan(math.sin(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +00001422 except ValueError:
1423 self.assertRaises(ValueError, math.sin, INF)
1424 self.assertRaises(ValueError, math.sin, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001425 self.assertTrue(math.isnan(math.sin(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +00001426
Thomas Wouters89f507f2006-12-13 04:49:30 +00001427 def testSinh(self):
1428 self.assertRaises(TypeError, math.sinh)
1429 self.ftest('sinh(0)', math.sinh(0), 0)
1430 self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1)
1431 self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001432 self.assertEqual(math.sinh(INF), INF)
1433 self.assertEqual(math.sinh(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001434 self.assertTrue(math.isnan(math.sinh(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +00001435
Thomas Wouters89f507f2006-12-13 04:49:30 +00001436 def testSqrt(self):
1437 self.assertRaises(TypeError, math.sqrt)
1438 self.ftest('sqrt(0)', math.sqrt(0), 0)
1439 self.ftest('sqrt(1)', math.sqrt(1), 1)
1440 self.ftest('sqrt(4)', math.sqrt(4), 2)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001441 self.assertEqual(math.sqrt(INF), INF)
Mark Dickinson31ba1c32016-09-04 12:29:14 +01001442 self.assertRaises(ValueError, math.sqrt, -1)
Christian Heimes53876d92008-04-19 00:31:39 +00001443 self.assertRaises(ValueError, math.sqrt, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001444 self.assertTrue(math.isnan(math.sqrt(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +00001445
Thomas Wouters89f507f2006-12-13 04:49:30 +00001446 def testTan(self):
1447 self.assertRaises(TypeError, math.tan)
1448 self.ftest('tan(0)', math.tan(0), 0)
1449 self.ftest('tan(pi/4)', math.tan(math.pi/4), 1)
1450 self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1)
Christian Heimes53876d92008-04-19 00:31:39 +00001451 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001452 self.assertTrue(math.isnan(math.tan(INF)))
1453 self.assertTrue(math.isnan(math.tan(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +00001454 except:
1455 self.assertRaises(ValueError, math.tan, INF)
1456 self.assertRaises(ValueError, math.tan, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001457 self.assertTrue(math.isnan(math.tan(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +00001458
Thomas Wouters89f507f2006-12-13 04:49:30 +00001459 def testTanh(self):
1460 self.assertRaises(TypeError, math.tanh)
1461 self.ftest('tanh(0)', math.tanh(0), 0)
Mark Dickinson96f774d2016-09-03 19:30:22 +01001462 self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0,
Victor Stinner0b2ab212020-01-13 12:44:35 +01001463 abs_tol=math.ulp(1))
Christian Heimes53876d92008-04-19 00:31:39 +00001464 self.ftest('tanh(inf)', math.tanh(INF), 1)
1465 self.ftest('tanh(-inf)', math.tanh(NINF), -1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001466 self.assertTrue(math.isnan(math.tanh(NAN)))
Victor Stinnerbe3da382010-11-07 14:14:27 +00001467
1468 @requires_IEEE_754
Victor Stinnerbe3da382010-11-07 14:14:27 +00001469 def testTanhSign(self):
Christian Heimese57950f2008-04-21 13:08:03 +00001470 # check that tanh(-0.) == -0. on IEEE 754 systems
Victor Stinnerbe3da382010-11-07 14:14:27 +00001471 self.assertEqual(math.tanh(-0.), -0.)
1472 self.assertEqual(math.copysign(1., math.tanh(-0.)),
1473 math.copysign(1., -0.))
Tim Peters1d120612000-10-12 06:10:25 +00001474
Christian Heimes400adb02008-02-01 08:12:03 +00001475 def test_trunc(self):
1476 self.assertEqual(math.trunc(1), 1)
1477 self.assertEqual(math.trunc(-1), -1)
1478 self.assertEqual(type(math.trunc(1)), int)
1479 self.assertEqual(type(math.trunc(1.5)), int)
1480 self.assertEqual(math.trunc(1.5), 1)
1481 self.assertEqual(math.trunc(-1.5), -1)
1482 self.assertEqual(math.trunc(1.999999), 1)
1483 self.assertEqual(math.trunc(-1.999999), -1)
1484 self.assertEqual(math.trunc(-0.999999), -0)
1485 self.assertEqual(math.trunc(-100.999), -100)
1486
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001487 class TestTrunc:
Christian Heimes400adb02008-02-01 08:12:03 +00001488 def __trunc__(self):
1489 return 23
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001490 class FloatTrunc(float):
1491 def __trunc__(self):
1492 return 23
1493 class TestNoTrunc:
Christian Heimes400adb02008-02-01 08:12:03 +00001494 pass
1495
1496 self.assertEqual(math.trunc(TestTrunc()), 23)
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001497 self.assertEqual(math.trunc(FloatTrunc()), 23)
Christian Heimes400adb02008-02-01 08:12:03 +00001498
1499 self.assertRaises(TypeError, math.trunc)
1500 self.assertRaises(TypeError, math.trunc, 1, 2)
Serhiy Storchaka5fd5cb82019-11-16 18:00:57 +02001501 self.assertRaises(TypeError, math.trunc, FloatLike(23.5))
Christian Heimes400adb02008-02-01 08:12:03 +00001502 self.assertRaises(TypeError, math.trunc, TestNoTrunc())
1503
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001504 def testIsfinite(self):
1505 self.assertTrue(math.isfinite(0.0))
1506 self.assertTrue(math.isfinite(-0.0))
1507 self.assertTrue(math.isfinite(1.0))
1508 self.assertTrue(math.isfinite(-1.0))
1509 self.assertFalse(math.isfinite(float("nan")))
1510 self.assertFalse(math.isfinite(float("inf")))
1511 self.assertFalse(math.isfinite(float("-inf")))
1512
Christian Heimes072c0f12008-01-03 23:01:04 +00001513 def testIsnan(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001514 self.assertTrue(math.isnan(float("nan")))
Mark Dickinson31ba1c32016-09-04 12:29:14 +01001515 self.assertTrue(math.isnan(float("-nan")))
1516 self.assertTrue(math.isnan(float("inf") * 0.))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001517 self.assertFalse(math.isnan(float("inf")))
1518 self.assertFalse(math.isnan(0.))
1519 self.assertFalse(math.isnan(1.))
Christian Heimes072c0f12008-01-03 23:01:04 +00001520
1521 def testIsinf(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001522 self.assertTrue(math.isinf(float("inf")))
1523 self.assertTrue(math.isinf(float("-inf")))
1524 self.assertTrue(math.isinf(1E400))
1525 self.assertTrue(math.isinf(-1E400))
1526 self.assertFalse(math.isinf(float("nan")))
1527 self.assertFalse(math.isinf(0.))
1528 self.assertFalse(math.isinf(1.))
Christian Heimes072c0f12008-01-03 23:01:04 +00001529
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00001530 @requires_IEEE_754
1531 def test_nan_constant(self):
1532 self.assertTrue(math.isnan(math.nan))
1533
1534 @requires_IEEE_754
1535 def test_inf_constant(self):
1536 self.assertTrue(math.isinf(math.inf))
1537 self.assertGreater(math.inf, 0.0)
1538 self.assertEqual(math.inf, float("inf"))
1539 self.assertEqual(-math.inf, float("-inf"))
1540
Thomas Wouters89f507f2006-12-13 04:49:30 +00001541 # RED_FLAG 16-Oct-2000 Tim
1542 # While 2.0 is more consistent about exceptions than previous releases, it
1543 # still fails this part of the test on some platforms. For now, we only
1544 # *run* test_exceptions() in verbose mode, so that this isn't normally
1545 # tested.
Serhiy Storchaka43767632013-11-03 21:31:38 +02001546 @unittest.skipUnless(verbose, 'requires verbose mode')
1547 def test_exceptions(self):
1548 try:
1549 x = math.exp(-1000000000)
1550 except:
1551 # mathmodule.c is failing to weed out underflows from libm, or
1552 # we've got an fp format with huge dynamic range
1553 self.fail("underflowing exp() should not have raised "
1554 "an exception")
1555 if x != 0:
1556 self.fail("underflowing exp() should have returned 0")
Tim Peters98c81842000-10-16 17:35:13 +00001557
Serhiy Storchaka43767632013-11-03 21:31:38 +02001558 # If this fails, probably using a strict IEEE-754 conforming libm, and x
1559 # is +Inf afterwards. But Python wants overflows detected by default.
1560 try:
1561 x = math.exp(1000000000)
1562 except OverflowError:
1563 pass
1564 else:
1565 self.fail("overflowing exp() didn't trigger OverflowError")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001566
Serhiy Storchaka43767632013-11-03 21:31:38 +02001567 # If this fails, it could be a puzzle. One odd possibility is that
1568 # mathmodule.c's macros are getting confused while comparing
1569 # Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE
1570 # as a result (and so raising OverflowError instead).
1571 try:
1572 x = math.sqrt(-1.0)
1573 except ValueError:
1574 pass
1575 else:
1576 self.fail("sqrt(-1) didn't raise ValueError")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001577
Mark Dickinson63566232009-09-18 21:04:19 +00001578 @requires_IEEE_754
Christian Heimes53876d92008-04-19 00:31:39 +00001579 def test_testfile(self):
Mark Dickinson85746542016-09-04 09:58:51 +01001580 # Some tests need to be skipped on ancient OS X versions.
1581 # See issue #27953.
1582 SKIP_ON_TIGER = {'tan0064'}
1583
1584 osx_version = None
1585 if sys.platform == 'darwin':
1586 version_txt = platform.mac_ver()[0]
1587 try:
1588 osx_version = tuple(map(int, version_txt.split('.')))
1589 except ValueError:
1590 pass
1591
Mark Dickinson96f774d2016-09-03 19:30:22 +01001592 fail_fmt = "{}: {}({!r}): {}"
1593
1594 failures = []
Christian Heimes53876d92008-04-19 00:31:39 +00001595 for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file):
Mark Dickinson96f774d2016-09-03 19:30:22 +01001596 # Skip if either the input or result is complex
1597 if ai != 0.0 or ei != 0.0:
Christian Heimes53876d92008-04-19 00:31:39 +00001598 continue
1599 if fn in ['rect', 'polar']:
1600 # no real versions of rect, polar
1601 continue
Mark Dickinson85746542016-09-04 09:58:51 +01001602 # Skip certain tests on OS X 10.4.
1603 if osx_version is not None and osx_version < (10, 5):
1604 if id in SKIP_ON_TIGER:
1605 continue
Mark Dickinson96f774d2016-09-03 19:30:22 +01001606
Christian Heimes53876d92008-04-19 00:31:39 +00001607 func = getattr(math, fn)
Mark Dickinson96f774d2016-09-03 19:30:22 +01001608
1609 if 'invalid' in flags or 'divide-by-zero' in flags:
1610 er = 'ValueError'
1611 elif 'overflow' in flags:
1612 er = 'OverflowError'
1613
Christian Heimesa342c012008-04-20 21:01:16 +00001614 try:
1615 result = func(ar)
Mark Dickinson96f774d2016-09-03 19:30:22 +01001616 except ValueError:
1617 result = 'ValueError'
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001618 except OverflowError:
Mark Dickinson96f774d2016-09-03 19:30:22 +01001619 result = 'OverflowError'
1620
1621 # Default tolerances
1622 ulp_tol, abs_tol = 5, 0.0
1623
1624 failure = result_check(er, result, ulp_tol, abs_tol)
1625 if failure is None:
1626 continue
1627
1628 msg = fail_fmt.format(id, fn, ar, failure)
1629 failures.append(msg)
1630
1631 if failures:
1632 self.fail('Failures in test_testfile:\n ' +
1633 '\n '.join(failures))
Thomas Wouters89f507f2006-12-13 04:49:30 +00001634
Victor Stinnerbe3da382010-11-07 14:14:27 +00001635 @requires_IEEE_754
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001636 def test_mtestfile(self):
Mark Dickinson96f774d2016-09-03 19:30:22 +01001637 fail_fmt = "{}: {}({!r}): {}"
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001638
1639 failures = []
1640 for id, fn, arg, expected, flags in parse_mtestfile(math_testcases):
1641 func = getattr(math, fn)
1642
1643 if 'invalid' in flags or 'divide-by-zero' in flags:
1644 expected = 'ValueError'
1645 elif 'overflow' in flags:
1646 expected = 'OverflowError'
1647
1648 try:
1649 got = func(arg)
1650 except ValueError:
1651 got = 'ValueError'
1652 except OverflowError:
1653 got = 'OverflowError'
1654
Mark Dickinson96f774d2016-09-03 19:30:22 +01001655 # Default tolerances
1656 ulp_tol, abs_tol = 5, 0.0
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +00001657
Mark Dickinson96f774d2016-09-03 19:30:22 +01001658 # Exceptions to the defaults
1659 if fn == 'gamma':
1660 # Experimental results on one platform gave
1661 # an accuracy of <= 10 ulps across the entire float
1662 # domain. We weaken that to require 20 ulp accuracy.
1663 ulp_tol = 20
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001664
Mark Dickinson96f774d2016-09-03 19:30:22 +01001665 elif fn == 'lgamma':
1666 # we use a weaker accuracy test for lgamma;
1667 # lgamma only achieves an absolute error of
1668 # a few multiples of the machine accuracy, in
1669 # general.
1670 abs_tol = 1e-15
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001671
Mark Dickinson96f774d2016-09-03 19:30:22 +01001672 elif fn == 'erfc' and arg >= 0.0:
1673 # erfc has less-than-ideal accuracy for large
1674 # arguments (x ~ 25 or so), mainly due to the
1675 # error involved in computing exp(-x*x).
1676 #
1677 # Observed between CPython and mpmath at 25 dp:
1678 # x < 0 : err <= 2 ulp
1679 # 0 <= x < 1 : err <= 10 ulp
1680 # 1 <= x < 10 : err <= 100 ulp
1681 # 10 <= x < 20 : err <= 300 ulp
1682 # 20 <= x : < 600 ulp
1683 #
1684 if arg < 1.0:
1685 ulp_tol = 10
1686 elif arg < 10.0:
1687 ulp_tol = 100
1688 else:
1689 ulp_tol = 1000
1690
1691 failure = result_check(expected, got, ulp_tol, abs_tol)
1692 if failure is None:
1693 continue
1694
1695 msg = fail_fmt.format(id, fn, arg, failure)
1696 failures.append(msg)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001697
1698 if failures:
1699 self.fail('Failures in test_mtestfile:\n ' +
1700 '\n '.join(failures))
1701
Pablo Galindo04114112019-03-09 19:18:08 +00001702 def test_prod(self):
1703 prod = math.prod
1704 self.assertEqual(prod([]), 1)
1705 self.assertEqual(prod([], start=5), 5)
1706 self.assertEqual(prod(list(range(2,8))), 5040)
1707 self.assertEqual(prod(iter(list(range(2,8)))), 5040)
1708 self.assertEqual(prod(range(1, 10), start=10), 3628800)
1709
1710 self.assertEqual(prod([1, 2, 3, 4, 5]), 120)
1711 self.assertEqual(prod([1.0, 2.0, 3.0, 4.0, 5.0]), 120.0)
1712 self.assertEqual(prod([1, 2, 3, 4.0, 5.0]), 120.0)
1713 self.assertEqual(prod([1.0, 2.0, 3.0, 4, 5]), 120.0)
1714
1715 # Test overflow in fast-path for integers
1716 self.assertEqual(prod([1, 1, 2**32, 1, 1]), 2**32)
1717 # Test overflow in fast-path for floats
1718 self.assertEqual(prod([1.0, 1.0, 2**32, 1, 1]), float(2**32))
1719
1720 self.assertRaises(TypeError, prod)
1721 self.assertRaises(TypeError, prod, 42)
1722 self.assertRaises(TypeError, prod, ['a', 'b', 'c'])
1723 self.assertRaises(TypeError, prod, ['a', 'b', 'c'], '')
1724 self.assertRaises(TypeError, prod, [b'a', b'c'], b'')
1725 values = [bytearray(b'a'), bytearray(b'b')]
1726 self.assertRaises(TypeError, prod, values, bytearray(b''))
1727 self.assertRaises(TypeError, prod, [[1], [2], [3]])
1728 self.assertRaises(TypeError, prod, [{2:3}])
1729 self.assertRaises(TypeError, prod, [{2:3}]*2, {2:3})
1730 self.assertRaises(TypeError, prod, [[1], [2], [3]], [])
1731 with self.assertRaises(TypeError):
1732 prod([10, 20], [30, 40]) # start is a keyword-only argument
1733
1734 self.assertEqual(prod([0, 1, 2, 3]), 0)
1735 self.assertEqual(prod([1, 0, 2, 3]), 0)
1736 self.assertEqual(prod([1, 2, 3, 0]), 0)
1737
1738 def _naive_prod(iterable, start=1):
1739 for elem in iterable:
1740 start *= elem
1741 return start
1742
1743 # Big integers
1744
1745 iterable = range(1, 10000)
1746 self.assertEqual(prod(iterable), _naive_prod(iterable))
1747 iterable = range(-10000, -1)
1748 self.assertEqual(prod(iterable), _naive_prod(iterable))
1749 iterable = range(-1000, 1000)
1750 self.assertEqual(prod(iterable), 0)
1751
1752 # Big floats
1753
1754 iterable = [float(x) for x in range(1, 1000)]
1755 self.assertEqual(prod(iterable), _naive_prod(iterable))
1756 iterable = [float(x) for x in range(-1000, -1)]
1757 self.assertEqual(prod(iterable), _naive_prod(iterable))
1758 iterable = [float(x) for x in range(-1000, 1000)]
1759 self.assertIsNaN(prod(iterable))
1760
1761 # Float tests
1762
1763 self.assertIsNaN(prod([1, 2, 3, float("nan"), 2, 3]))
1764 self.assertIsNaN(prod([1, 0, float("nan"), 2, 3]))
1765 self.assertIsNaN(prod([1, float("nan"), 0, 3]))
1766 self.assertIsNaN(prod([1, float("inf"), float("nan"),3]))
1767 self.assertIsNaN(prod([1, float("-inf"), float("nan"),3]))
1768 self.assertIsNaN(prod([1, float("nan"), float("inf"),3]))
1769 self.assertIsNaN(prod([1, float("nan"), float("-inf"),3]))
1770
1771 self.assertEqual(prod([1, 2, 3, float('inf'),-3,4]), float('-inf'))
1772 self.assertEqual(prod([1, 2, 3, float('-inf'),-3,4]), float('inf'))
1773
1774 self.assertIsNaN(prod([1,2,0,float('inf'), -3, 4]))
1775 self.assertIsNaN(prod([1,2,0,float('-inf'), -3, 4]))
1776 self.assertIsNaN(prod([1, 2, 3, float('inf'), -3, 0, 3]))
1777 self.assertIsNaN(prod([1, 2, 3, float('-inf'), -3, 0, 2]))
1778
1779 # Type preservation
1780
1781 self.assertEqual(type(prod([1, 2, 3, 4, 5, 6])), int)
1782 self.assertEqual(type(prod([1, 2.0, 3, 4, 5, 6])), float)
1783 self.assertEqual(type(prod(range(1, 10000))), int)
1784 self.assertEqual(type(prod(range(1, 10000), start=1.0)), float)
1785 self.assertEqual(type(prod([1, decimal.Decimal(2.0), 3, 4, 5, 6])),
1786 decimal.Decimal)
1787
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03001788 def testPerm(self):
1789 perm = math.perm
1790 factorial = math.factorial
Min ho Kim96e12d52019-07-22 06:12:33 +10001791 # Test if factorial definition is satisfied
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03001792 for n in range(100):
1793 for k in range(n + 1):
1794 self.assertEqual(perm(n, k),
1795 factorial(n) // factorial(n - k))
1796
1797 # Test for Pascal's identity
1798 for n in range(1, 100):
1799 for k in range(1, n):
1800 self.assertEqual(perm(n, k), perm(n - 1, k - 1) * k + perm(n - 1, k))
1801
1802 # Test corner cases
1803 for n in range(1, 100):
1804 self.assertEqual(perm(n, 0), 1)
1805 self.assertEqual(perm(n, 1), n)
1806 self.assertEqual(perm(n, n), factorial(n))
1807
Raymond Hettingere119b3d2019-06-08 08:58:11 -07001808 # Test one argument form
1809 for n in range(20):
1810 self.assertEqual(perm(n), factorial(n))
1811 self.assertEqual(perm(n, None), factorial(n))
1812
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03001813 # Raises TypeError if any argument is non-integer or argument count is
Raymond Hettingere119b3d2019-06-08 08:58:11 -07001814 # not 1 or 2
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03001815 self.assertRaises(TypeError, perm, 10, 1.0)
1816 self.assertRaises(TypeError, perm, 10, decimal.Decimal(1.0))
1817 self.assertRaises(TypeError, perm, 10, "1")
1818 self.assertRaises(TypeError, perm, 10.0, 1)
1819 self.assertRaises(TypeError, perm, decimal.Decimal(10.0), 1)
1820 self.assertRaises(TypeError, perm, "10", 1)
1821
Raymond Hettingere119b3d2019-06-08 08:58:11 -07001822 self.assertRaises(TypeError, perm)
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03001823 self.assertRaises(TypeError, perm, 10, 1, 3)
1824 self.assertRaises(TypeError, perm)
1825
1826 # Raises Value error if not k or n are negative numbers
1827 self.assertRaises(ValueError, perm, -1, 1)
1828 self.assertRaises(ValueError, perm, -2**1000, 1)
1829 self.assertRaises(ValueError, perm, 1, -1)
1830 self.assertRaises(ValueError, perm, 1, -2**1000)
1831
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07001832 # Returns zero if k is greater than n
1833 self.assertEqual(perm(1, 2), 0)
1834 self.assertEqual(perm(1, 2**1000), 0)
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03001835
1836 n = 2**1000
1837 self.assertEqual(perm(n, 0), 1)
1838 self.assertEqual(perm(n, 1), n)
1839 self.assertEqual(perm(n, 2), n * (n-1))
Serhiy Storchaka1b8a46d2019-06-17 16:58:32 +03001840 if support.check_impl_detail(cpython=True):
1841 self.assertRaises(OverflowError, perm, n, n)
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03001842
1843 for n, k in (True, True), (True, False), (False, False):
1844 self.assertEqual(perm(n, k), 1)
1845 self.assertIs(type(perm(n, k)), int)
1846 self.assertEqual(perm(IntSubclass(5), IntSubclass(2)), 20)
1847 self.assertEqual(perm(MyIndexable(5), MyIndexable(2)), 20)
1848 for k in range(3):
1849 self.assertIs(type(perm(IntSubclass(5), IntSubclass(k))), int)
1850 self.assertIs(type(perm(MyIndexable(5), MyIndexable(k))), int)
1851
Yash Aggarwal4a686502019-06-01 12:51:27 +05301852 def testComb(self):
1853 comb = math.comb
1854 factorial = math.factorial
Min ho Kim96e12d52019-07-22 06:12:33 +10001855 # Test if factorial definition is satisfied
Yash Aggarwal4a686502019-06-01 12:51:27 +05301856 for n in range(100):
1857 for k in range(n + 1):
1858 self.assertEqual(comb(n, k), factorial(n)
1859 // (factorial(k) * factorial(n - k)))
1860
1861 # Test for Pascal's identity
1862 for n in range(1, 100):
1863 for k in range(1, n):
1864 self.assertEqual(comb(n, k), comb(n - 1, k - 1) + comb(n - 1, k))
1865
1866 # Test corner cases
1867 for n in range(100):
1868 self.assertEqual(comb(n, 0), 1)
1869 self.assertEqual(comb(n, n), 1)
1870
1871 for n in range(1, 100):
1872 self.assertEqual(comb(n, 1), n)
1873 self.assertEqual(comb(n, n - 1), n)
1874
1875 # Test Symmetry
1876 for n in range(100):
1877 for k in range(n // 2):
1878 self.assertEqual(comb(n, k), comb(n, n - k))
1879
1880 # Raises TypeError if any argument is non-integer or argument count is
1881 # not 2
1882 self.assertRaises(TypeError, comb, 10, 1.0)
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03001883 self.assertRaises(TypeError, comb, 10, decimal.Decimal(1.0))
Yash Aggarwal4a686502019-06-01 12:51:27 +05301884 self.assertRaises(TypeError, comb, 10, "1")
Yash Aggarwal4a686502019-06-01 12:51:27 +05301885 self.assertRaises(TypeError, comb, 10.0, 1)
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03001886 self.assertRaises(TypeError, comb, decimal.Decimal(10.0), 1)
1887 self.assertRaises(TypeError, comb, "10", 1)
Yash Aggarwal4a686502019-06-01 12:51:27 +05301888
1889 self.assertRaises(TypeError, comb, 10)
1890 self.assertRaises(TypeError, comb, 10, 1, 3)
1891 self.assertRaises(TypeError, comb)
1892
1893 # Raises Value error if not k or n are negative numbers
1894 self.assertRaises(ValueError, comb, -1, 1)
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03001895 self.assertRaises(ValueError, comb, -2**1000, 1)
Yash Aggarwal4a686502019-06-01 12:51:27 +05301896 self.assertRaises(ValueError, comb, 1, -1)
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03001897 self.assertRaises(ValueError, comb, 1, -2**1000)
Yash Aggarwal4a686502019-06-01 12:51:27 +05301898
Raymond Hettinger963eb0f2019-06-04 01:23:06 -07001899 # Returns zero if k is greater than n
1900 self.assertEqual(comb(1, 2), 0)
1901 self.assertEqual(comb(1, 2**1000), 0)
Yash Aggarwal4a686502019-06-01 12:51:27 +05301902
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03001903 n = 2**1000
1904 self.assertEqual(comb(n, 0), 1)
1905 self.assertEqual(comb(n, 1), n)
1906 self.assertEqual(comb(n, 2), n * (n-1) // 2)
1907 self.assertEqual(comb(n, n), 1)
1908 self.assertEqual(comb(n, n-1), n)
1909 self.assertEqual(comb(n, n-2), n * (n-1) // 2)
Serhiy Storchaka1b8a46d2019-06-17 16:58:32 +03001910 if support.check_impl_detail(cpython=True):
1911 self.assertRaises(OverflowError, comb, n, n//2)
Yash Aggarwal4a686502019-06-01 12:51:27 +05301912
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03001913 for n, k in (True, True), (True, False), (False, False):
1914 self.assertEqual(comb(n, k), 1)
1915 self.assertIs(type(comb(n, k)), int)
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03001916 self.assertEqual(comb(IntSubclass(5), IntSubclass(2)), 10)
Serhiy Storchaka2b843ac2019-06-01 22:09:02 +03001917 self.assertEqual(comb(MyIndexable(5), MyIndexable(2)), 10)
Serhiy Storchaka5ae299a2019-06-02 11:16:49 +03001918 for k in range(3):
1919 self.assertIs(type(comb(IntSubclass(5), IntSubclass(k))), int)
1920 self.assertIs(type(comb(MyIndexable(5), MyIndexable(k))), int)
Yash Aggarwal4a686502019-06-01 12:51:27 +05301921
Victor Stinner59e2d262020-01-21 12:48:16 +01001922 @requires_IEEE_754
1923 def test_nextafter(self):
1924 # around 2^52 and 2^63
1925 self.assertEqual(math.nextafter(4503599627370496.0, -INF),
1926 4503599627370495.5)
1927 self.assertEqual(math.nextafter(4503599627370496.0, INF),
1928 4503599627370497.0)
1929 self.assertEqual(math.nextafter(9223372036854775808.0, 0.0),
1930 9223372036854774784.0)
1931 self.assertEqual(math.nextafter(-9223372036854775808.0, 0.0),
1932 -9223372036854774784.0)
1933
1934 # around 1.0
1935 self.assertEqual(math.nextafter(1.0, -INF),
1936 float.fromhex('0x1.fffffffffffffp-1'))
1937 self.assertEqual(math.nextafter(1.0, INF),
1938 float.fromhex('0x1.0000000000001p+0'))
1939
1940 # x == y: y is returned
1941 self.assertEqual(math.nextafter(2.0, 2.0), 2.0)
1942 self.assertEqualSign(math.nextafter(-0.0, +0.0), +0.0)
1943 self.assertEqualSign(math.nextafter(+0.0, -0.0), -0.0)
1944
1945 # around 0.0
1946 smallest_subnormal = sys.float_info.min * sys.float_info.epsilon
1947 self.assertEqual(math.nextafter(+0.0, INF), smallest_subnormal)
1948 self.assertEqual(math.nextafter(-0.0, INF), smallest_subnormal)
1949 self.assertEqual(math.nextafter(+0.0, -INF), -smallest_subnormal)
1950 self.assertEqual(math.nextafter(-0.0, -INF), -smallest_subnormal)
1951 self.assertEqualSign(math.nextafter(smallest_subnormal, +0.0), +0.0)
1952 self.assertEqualSign(math.nextafter(-smallest_subnormal, +0.0), -0.0)
1953 self.assertEqualSign(math.nextafter(smallest_subnormal, -0.0), +0.0)
1954 self.assertEqualSign(math.nextafter(-smallest_subnormal, -0.0), -0.0)
1955
1956 # around infinity
1957 largest_normal = sys.float_info.max
1958 self.assertEqual(math.nextafter(INF, 0.0), largest_normal)
1959 self.assertEqual(math.nextafter(-INF, 0.0), -largest_normal)
1960 self.assertEqual(math.nextafter(largest_normal, INF), INF)
1961 self.assertEqual(math.nextafter(-largest_normal, -INF), -INF)
1962
1963 # NaN
1964 self.assertIsNaN(math.nextafter(NAN, 1.0))
1965 self.assertIsNaN(math.nextafter(1.0, NAN))
1966 self.assertIsNaN(math.nextafter(NAN, NAN))
1967
1968 @requires_IEEE_754
1969 def test_ulp(self):
1970 self.assertEqual(math.ulp(1.0), sys.float_info.epsilon)
1971 # use int ** int rather than float ** int to not rely on pow() accuracy
1972 self.assertEqual(math.ulp(2 ** 52), 1.0)
1973 self.assertEqual(math.ulp(2 ** 53), 2.0)
1974 self.assertEqual(math.ulp(2 ** 64), 4096.0)
1975
1976 # min and max
1977 self.assertEqual(math.ulp(0.0),
1978 sys.float_info.min * sys.float_info.epsilon)
1979 self.assertEqual(math.ulp(FLOAT_MAX),
1980 FLOAT_MAX - math.nextafter(FLOAT_MAX, -INF))
1981
1982 # special cases
1983 self.assertEqual(math.ulp(INF), INF)
1984 self.assertIsNaN(math.ulp(math.nan))
1985
1986 # negative number: ulp(-x) == ulp(x)
1987 for x in (0.0, 1.0, 2 ** 52, 2 ** 64, INF):
1988 with self.subTest(x=x):
1989 self.assertEqual(math.ulp(-x), math.ulp(x))
1990
Zackery Spytz5208b4b2020-03-14 04:45:32 -06001991 def test_issue39871(self):
1992 # A SystemError should not be raised if the first arg to atan2(),
1993 # copysign(), or remainder() cannot be converted to a float.
1994 class F:
1995 def __float__(self):
1996 self.converted = True
1997 1/0
1998 for func in math.atan2, math.copysign, math.remainder:
1999 y = F()
2000 with self.assertRaises(TypeError):
2001 func("not a number", y)
2002
2003 # There should not have been any attempt to convert the second
2004 # argument to a float.
2005 self.assertFalse(getattr(y, "converted", False))
2006
Victor Stinner59e2d262020-01-21 12:48:16 +01002007 # Custom assertions.
2008
2009 def assertIsNaN(self, value):
2010 if not math.isnan(value):
2011 self.fail("Expected a NaN, got {!r}.".format(value))
2012
2013 def assertEqualSign(self, x, y):
2014 """Similar to assertEqual(), but compare also the sign with copysign().
2015
2016 Function useful to compare signed zeros.
2017 """
2018 self.assertEqual(x, y)
2019 self.assertEqual(math.copysign(1.0, x), math.copysign(1.0, y))
2020
2021
2022class IsCloseTests(unittest.TestCase):
2023 isclose = math.isclose # subclasses should override this
2024
2025 def assertIsClose(self, a, b, *args, **kwargs):
2026 self.assertTrue(self.isclose(a, b, *args, **kwargs),
2027 msg="%s and %s should be close!" % (a, b))
2028
2029 def assertIsNotClose(self, a, b, *args, **kwargs):
2030 self.assertFalse(self.isclose(a, b, *args, **kwargs),
2031 msg="%s and %s should not be close!" % (a, b))
2032
2033 def assertAllClose(self, examples, *args, **kwargs):
2034 for a, b in examples:
2035 self.assertIsClose(a, b, *args, **kwargs)
2036
2037 def assertAllNotClose(self, examples, *args, **kwargs):
2038 for a, b in examples:
2039 self.assertIsNotClose(a, b, *args, **kwargs)
2040
2041 def test_negative_tolerances(self):
2042 # ValueError should be raised if either tolerance is less than zero
2043 with self.assertRaises(ValueError):
2044 self.assertIsClose(1, 1, rel_tol=-1e-100)
2045 with self.assertRaises(ValueError):
2046 self.assertIsClose(1, 1, rel_tol=1e-100, abs_tol=-1e10)
2047
2048 def test_identical(self):
2049 # identical values must test as close
2050 identical_examples = [(2.0, 2.0),
2051 (0.1e200, 0.1e200),
2052 (1.123e-300, 1.123e-300),
2053 (12345, 12345.0),
2054 (0.0, -0.0),
2055 (345678, 345678)]
2056 self.assertAllClose(identical_examples, rel_tol=0.0, abs_tol=0.0)
2057
2058 def test_eight_decimal_places(self):
2059 # examples that are close to 1e-8, but not 1e-9
2060 eight_decimal_places_examples = [(1e8, 1e8 + 1),
2061 (-1e-8, -1.000000009e-8),
2062 (1.12345678, 1.12345679)]
2063 self.assertAllClose(eight_decimal_places_examples, rel_tol=1e-8)
2064 self.assertAllNotClose(eight_decimal_places_examples, rel_tol=1e-9)
2065
2066 def test_near_zero(self):
2067 # values close to zero
2068 near_zero_examples = [(1e-9, 0.0),
2069 (-1e-9, 0.0),
2070 (-1e-150, 0.0)]
2071 # these should not be close to any rel_tol
2072 self.assertAllNotClose(near_zero_examples, rel_tol=0.9)
2073 # these should be close to abs_tol=1e-8
2074 self.assertAllClose(near_zero_examples, abs_tol=1e-8)
2075
2076 def test_identical_infinite(self):
2077 # these are close regardless of tolerance -- i.e. they are equal
2078 self.assertIsClose(INF, INF)
2079 self.assertIsClose(INF, INF, abs_tol=0.0)
2080 self.assertIsClose(NINF, NINF)
2081 self.assertIsClose(NINF, NINF, abs_tol=0.0)
2082
2083 def test_inf_ninf_nan(self):
2084 # these should never be close (following IEEE 754 rules for equality)
2085 not_close_examples = [(NAN, NAN),
2086 (NAN, 1e-100),
2087 (1e-100, NAN),
2088 (INF, NAN),
2089 (NAN, INF),
2090 (INF, NINF),
2091 (INF, 1.0),
2092 (1.0, INF),
2093 (INF, 1e308),
2094 (1e308, INF)]
2095 # use largest reasonable tolerance
2096 self.assertAllNotClose(not_close_examples, abs_tol=0.999999999999999)
2097
2098 def test_zero_tolerance(self):
2099 # test with zero tolerance
2100 zero_tolerance_close_examples = [(1.0, 1.0),
2101 (-3.4, -3.4),
2102 (-1e-300, -1e-300)]
2103 self.assertAllClose(zero_tolerance_close_examples, rel_tol=0.0)
2104
2105 zero_tolerance_not_close_examples = [(1.0, 1.000000000000001),
2106 (0.99999999999999, 1.0),
2107 (1.0e200, .999999999999999e200)]
2108 self.assertAllNotClose(zero_tolerance_not_close_examples, rel_tol=0.0)
2109
2110 def test_asymmetry(self):
2111 # test the asymmetry example from PEP 485
2112 self.assertAllClose([(9, 10), (10, 9)], rel_tol=0.1)
2113
2114 def test_integers(self):
2115 # test with integer values
2116 integer_examples = [(100000001, 100000000),
2117 (123456789, 123456788)]
2118
2119 self.assertAllClose(integer_examples, rel_tol=1e-8)
2120 self.assertAllNotClose(integer_examples, rel_tol=1e-9)
2121
2122 def test_decimals(self):
2123 # test with Decimal values
2124 from decimal import Decimal
2125
2126 decimal_examples = [(Decimal('1.00000001'), Decimal('1.0')),
2127 (Decimal('1.00000001e-20'), Decimal('1.0e-20')),
2128 (Decimal('1.00000001e-100'), Decimal('1.0e-100')),
2129 (Decimal('1.00000001e20'), Decimal('1.0e20'))]
2130 self.assertAllClose(decimal_examples, rel_tol=1e-8)
2131 self.assertAllNotClose(decimal_examples, rel_tol=1e-9)
2132
2133 def test_fractions(self):
2134 # test with Fraction values
2135 from fractions import Fraction
2136
2137 fraction_examples = [
2138 (Fraction(1, 100000000) + 1, Fraction(1)),
2139 (Fraction(100000001), Fraction(100000000)),
2140 (Fraction(10**8 + 1, 10**28), Fraction(1, 10**20))]
2141 self.assertAllClose(fraction_examples, rel_tol=1e-8)
2142 self.assertAllNotClose(fraction_examples, rel_tol=1e-9)
2143
Pablo Galindo42079072019-02-10 19:56:58 +00002144
Thomas Wouters89f507f2006-12-13 04:49:30 +00002145def test_main():
Christian Heimes53876d92008-04-19 00:31:39 +00002146 from doctest import DocFileSuite
2147 suite = unittest.TestSuite()
2148 suite.addTest(unittest.makeSuite(MathTests))
Tal Einatd5519ed2015-05-31 22:05:00 +03002149 suite.addTest(unittest.makeSuite(IsCloseTests))
Christian Heimes53876d92008-04-19 00:31:39 +00002150 suite.addTest(DocFileSuite("ieee754.txt"))
2151 run_unittest(suite)
Thomas Wouters89f507f2006-12-13 04:49:30 +00002152
2153if __name__ == '__main__':
2154 test_main()