blob: 9b2f55e1f410f8f6aca247758f06760d38866612 [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 Stinnerbe3da382010-11-07 14:14:27 +000015import sysconfig
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 Dickinson96f774d2016-09-03 19:30:22 +010056def ulp(x):
57 """Return the value of the least significant bit of a
58 float x, such that the first float bigger than x is x+ulp(x).
59 Then, given an expected result x and a tolerance of n ulps,
60 the result y should be such that abs(y-x) <= n * ulp(x).
61 The results from this function will only make sense on platforms
62 where native doubles are represented in IEEE 754 binary64 format.
63 """
64 x = abs(float(x))
65 if math.isnan(x) or math.isinf(x):
66 return x
Mark Dickinson05d2e082009-12-11 20:17:17 +000067
Mark Dickinson96f774d2016-09-03 19:30:22 +010068 # Find next float up from x.
69 n = struct.unpack('<q', struct.pack('<d', x))[0]
70 x_next = struct.unpack('<d', struct.pack('<q', n + 1))[0]
71 if math.isinf(x_next):
72 # Corner case: x was the largest finite float. Then it's
73 # not an exact power of two, so we can take the difference
74 # between x and the previous float.
75 x_prev = struct.unpack('<d', struct.pack('<q', n - 1))[0]
76 return x - x_prev
77 else:
78 return x_next - x
Mark Dickinson05d2e082009-12-11 20:17:17 +000079
Mark Dickinson4c8a9a22010-05-15 17:02:38 +000080# Here's a pure Python version of the math.factorial algorithm, for
81# documentation and comparison purposes.
82#
83# Formula:
84#
85# factorial(n) = factorial_odd_part(n) << (n - count_set_bits(n))
86#
87# where
88#
89# factorial_odd_part(n) = product_{i >= 0} product_{0 < j <= n >> i; j odd} j
90#
91# The outer product above is an infinite product, but once i >= n.bit_length,
92# (n >> i) < 1 and the corresponding term of the product is empty. So only the
93# finitely many terms for 0 <= i < n.bit_length() contribute anything.
94#
95# We iterate downwards from i == n.bit_length() - 1 to i == 0. The inner
96# product in the formula above starts at 1 for i == n.bit_length(); for each i
97# < n.bit_length() we get the inner product for i from that for i + 1 by
98# multiplying by all j in {n >> i+1 < j <= n >> i; j odd}. In Python terms,
99# this set is range((n >> i+1) + 1 | 1, (n >> i) + 1 | 1, 2).
100
101def count_set_bits(n):
102 """Number of '1' bits in binary expansion of a nonnnegative integer."""
103 return 1 + count_set_bits(n & n - 1) if n else 0
104
105def partial_product(start, stop):
106 """Product of integers in range(start, stop, 2), computed recursively.
107 start and stop should both be odd, with start <= stop.
108
109 """
110 numfactors = (stop - start) >> 1
111 if not numfactors:
112 return 1
113 elif numfactors == 1:
114 return start
115 else:
116 mid = (start + numfactors) | 1
117 return partial_product(start, mid) * partial_product(mid, stop)
118
119def py_factorial(n):
120 """Factorial of nonnegative integer n, via "Binary Split Factorial Formula"
121 described at http://www.luschny.de/math/factorial/binarysplitfact.html
122
123 """
124 inner = outer = 1
125 for i in reversed(range(n.bit_length())):
126 inner *= partial_product((n >> i + 1) + 1 | 1, (n >> i) + 1 | 1)
127 outer *= inner
128 return outer << (n - count_set_bits(n))
129
Mark Dickinson96f774d2016-09-03 19:30:22 +0100130def ulp_abs_check(expected, got, ulp_tol, abs_tol):
131 """Given finite floats `expected` and `got`, check that they're
132 approximately equal to within the given number of ulps or the
133 given absolute tolerance, whichever is bigger.
Mark Dickinson05d2e082009-12-11 20:17:17 +0000134
Mark Dickinson96f774d2016-09-03 19:30:22 +0100135 Returns None on success and an error message on failure.
136 """
137 ulp_error = abs(to_ulps(expected) - to_ulps(got))
138 abs_error = abs(expected - got)
139
140 # Succeed if either abs_error <= abs_tol or ulp_error <= ulp_tol.
141 if abs_error <= abs_tol or ulp_error <= ulp_tol:
Mark Dickinson05d2e082009-12-11 20:17:17 +0000142 return None
Mark Dickinson96f774d2016-09-03 19:30:22 +0100143 else:
144 fmt = ("error = {:.3g} ({:d} ulps); "
145 "permitted error = {:.3g} or {:d} ulps")
146 return fmt.format(abs_error, ulp_error, abs_tol, ulp_tol)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000147
148def parse_mtestfile(fname):
149 """Parse a file with test values
150
151 -- starts a comment
152 blank lines, or lines containing only a comment, are ignored
153 other lines are expected to have the form
154 id fn arg -> expected [flag]*
155
156 """
157 with open(fname) as fp:
158 for line in fp:
159 # strip comments, and skip blank lines
160 if '--' in line:
161 line = line[:line.index('--')]
162 if not line.strip():
163 continue
164
165 lhs, rhs = line.split('->')
166 id, fn, arg = lhs.split()
167 rhs_pieces = rhs.split()
168 exp = rhs_pieces[0]
169 flags = rhs_pieces[1:]
170
171 yield (id, fn, float(arg), float(exp), flags)
172
Mark Dickinson96f774d2016-09-03 19:30:22 +0100173
Christian Heimes53876d92008-04-19 00:31:39 +0000174def parse_testfile(fname):
175 """Parse a file with test values
176
177 Empty lines or lines starting with -- are ignored
178 yields id, fn, arg_real, arg_imag, exp_real, exp_imag
179 """
180 with open(fname) as fp:
181 for line in fp:
182 # skip comment lines and blank lines
183 if line.startswith('--') or not line.strip():
184 continue
185
186 lhs, rhs = line.split('->')
187 id, fn, arg_real, arg_imag = lhs.split()
188 rhs_pieces = rhs.split()
189 exp_real, exp_imag = rhs_pieces[0], rhs_pieces[1]
190 flags = rhs_pieces[2:]
191
192 yield (id, fn,
193 float(arg_real), float(arg_imag),
194 float(exp_real), float(exp_imag),
Mark Dickinson96f774d2016-09-03 19:30:22 +0100195 flags)
196
197
198def result_check(expected, got, ulp_tol=5, abs_tol=0.0):
199 # Common logic of MathTests.(ftest, test_testcases, test_mtestcases)
200 """Compare arguments expected and got, as floats, if either
201 is a float, using a tolerance expressed in multiples of
202 ulp(expected) or absolutely (if given and greater).
203
204 As a convenience, when neither argument is a float, and for
205 non-finite floats, exact equality is demanded. Also, nan==nan
206 as far as this function is concerned.
207
208 Returns None on success and an error message on failure.
209 """
210
211 # Check exactly equal (applies also to strings representing exceptions)
212 if got == expected:
213 return None
214
215 failure = "not equal"
216
217 # Turn mixed float and int comparison (e.g. floor()) to all-float
218 if isinstance(expected, float) and isinstance(got, int):
219 got = float(got)
220 elif isinstance(got, float) and isinstance(expected, int):
221 expected = float(expected)
222
223 if isinstance(expected, float) and isinstance(got, float):
224 if math.isnan(expected) and math.isnan(got):
225 # Pass, since both nan
226 failure = None
227 elif math.isinf(expected) or math.isinf(got):
228 # We already know they're not equal, drop through to failure
229 pass
230 else:
231 # Both are finite floats (now). Are they close enough?
232 failure = ulp_abs_check(expected, got, ulp_tol, abs_tol)
233
234 # arguments are not equal, and if numeric, are too far apart
235 if failure is not None:
236 fail_fmt = "expected {!r}, got {!r}"
237 fail_msg = fail_fmt.format(expected, got)
238 fail_msg += ' ({})'.format(failure)
239 return fail_msg
240 else:
241 return None
Guido van Rossumfcce6301996-08-08 18:26:25 +0000242
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300243# Class providing an __index__ method.
244class MyIndexable(object):
245 def __init__(self, value):
246 self.value = value
247
248 def __index__(self):
249 return self.value
250
Thomas Wouters89f507f2006-12-13 04:49:30 +0000251class MathTests(unittest.TestCase):
Guido van Rossumfcce6301996-08-08 18:26:25 +0000252
Mark Dickinson96f774d2016-09-03 19:30:22 +0100253 def ftest(self, name, got, expected, ulp_tol=5, abs_tol=0.0):
254 """Compare arguments expected and got, as floats, if either
255 is a float, using a tolerance expressed in multiples of
256 ulp(expected) or absolutely, whichever is greater.
257
258 As a convenience, when neither argument is a float, and for
259 non-finite floats, exact equality is demanded. Also, nan==nan
260 in this function.
261 """
262 failure = result_check(expected, got, ulp_tol, abs_tol)
263 if failure is not None:
264 self.fail("{}: {}".format(name, failure))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000265
Thomas Wouters89f507f2006-12-13 04:49:30 +0000266 def testConstants(self):
Mark Dickinson96f774d2016-09-03 19:30:22 +0100267 # Ref: Abramowitz & Stegun (Dover, 1965)
268 self.ftest('pi', math.pi, 3.141592653589793238462643)
269 self.ftest('e', math.e, 2.718281828459045235360287)
Guido van Rossum0a891d72016-08-15 09:12:52 -0700270 self.assertEqual(math.tau, 2*math.pi)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000271
Thomas Wouters89f507f2006-12-13 04:49:30 +0000272 def testAcos(self):
273 self.assertRaises(TypeError, math.acos)
274 self.ftest('acos(-1)', math.acos(-1), math.pi)
275 self.ftest('acos(0)', math.acos(0), math.pi/2)
276 self.ftest('acos(1)', math.acos(1), 0)
Christian Heimes53876d92008-04-19 00:31:39 +0000277 self.assertRaises(ValueError, math.acos, INF)
278 self.assertRaises(ValueError, math.acos, NINF)
Mark Dickinson31ba1c32016-09-04 12:29:14 +0100279 self.assertRaises(ValueError, math.acos, 1 + eps)
280 self.assertRaises(ValueError, math.acos, -1 - eps)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000281 self.assertTrue(math.isnan(math.acos(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000282
283 def testAcosh(self):
284 self.assertRaises(TypeError, math.acosh)
285 self.ftest('acosh(1)', math.acosh(1), 0)
286 self.ftest('acosh(2)', math.acosh(2), 1.3169578969248168)
287 self.assertRaises(ValueError, math.acosh, 0)
288 self.assertRaises(ValueError, math.acosh, -1)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000289 self.assertEqual(math.acosh(INF), INF)
Christian Heimes53876d92008-04-19 00:31:39 +0000290 self.assertRaises(ValueError, math.acosh, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000291 self.assertTrue(math.isnan(math.acosh(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000292
Thomas Wouters89f507f2006-12-13 04:49:30 +0000293 def testAsin(self):
294 self.assertRaises(TypeError, math.asin)
295 self.ftest('asin(-1)', math.asin(-1), -math.pi/2)
296 self.ftest('asin(0)', math.asin(0), 0)
297 self.ftest('asin(1)', math.asin(1), math.pi/2)
Christian Heimes53876d92008-04-19 00:31:39 +0000298 self.assertRaises(ValueError, math.asin, INF)
299 self.assertRaises(ValueError, math.asin, NINF)
Mark Dickinson31ba1c32016-09-04 12:29:14 +0100300 self.assertRaises(ValueError, math.asin, 1 + eps)
301 self.assertRaises(ValueError, math.asin, -1 - eps)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000302 self.assertTrue(math.isnan(math.asin(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000303
304 def testAsinh(self):
305 self.assertRaises(TypeError, math.asinh)
306 self.ftest('asinh(0)', math.asinh(0), 0)
307 self.ftest('asinh(1)', math.asinh(1), 0.88137358701954305)
308 self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000309 self.assertEqual(math.asinh(INF), INF)
310 self.assertEqual(math.asinh(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000311 self.assertTrue(math.isnan(math.asinh(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000312
Thomas Wouters89f507f2006-12-13 04:49:30 +0000313 def testAtan(self):
314 self.assertRaises(TypeError, math.atan)
315 self.ftest('atan(-1)', math.atan(-1), -math.pi/4)
316 self.ftest('atan(0)', math.atan(0), 0)
317 self.ftest('atan(1)', math.atan(1), math.pi/4)
Christian Heimes53876d92008-04-19 00:31:39 +0000318 self.ftest('atan(inf)', math.atan(INF), math.pi/2)
Christian Heimesa342c012008-04-20 21:01:16 +0000319 self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000320 self.assertTrue(math.isnan(math.atan(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000321
322 def testAtanh(self):
323 self.assertRaises(TypeError, math.atan)
324 self.ftest('atanh(0)', math.atanh(0), 0)
325 self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489)
326 self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489)
327 self.assertRaises(ValueError, math.atanh, 1)
328 self.assertRaises(ValueError, math.atanh, -1)
329 self.assertRaises(ValueError, math.atanh, INF)
330 self.assertRaises(ValueError, math.atanh, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000331 self.assertTrue(math.isnan(math.atanh(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000332
Thomas Wouters89f507f2006-12-13 04:49:30 +0000333 def testAtan2(self):
334 self.assertRaises(TypeError, math.atan2)
335 self.ftest('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2)
336 self.ftest('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4)
337 self.ftest('atan2(0, 1)', math.atan2(0, 1), 0)
338 self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4)
339 self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000340
Christian Heimese57950f2008-04-21 13:08:03 +0000341 # math.atan2(0, x)
342 self.ftest('atan2(0., -inf)', math.atan2(0., NINF), math.pi)
343 self.ftest('atan2(0., -2.3)', math.atan2(0., -2.3), math.pi)
344 self.ftest('atan2(0., -0.)', math.atan2(0., -0.), math.pi)
345 self.assertEqual(math.atan2(0., 0.), 0.)
346 self.assertEqual(math.atan2(0., 2.3), 0.)
347 self.assertEqual(math.atan2(0., INF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000348 self.assertTrue(math.isnan(math.atan2(0., NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000349 # math.atan2(-0, x)
350 self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi)
351 self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi)
352 self.ftest('atan2(-0., -0.)', math.atan2(-0., -0.), -math.pi)
353 self.assertEqual(math.atan2(-0., 0.), -0.)
354 self.assertEqual(math.atan2(-0., 2.3), -0.)
355 self.assertEqual(math.atan2(-0., INF), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000356 self.assertTrue(math.isnan(math.atan2(-0., NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000357 # math.atan2(INF, x)
358 self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4)
359 self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2)
360 self.ftest('atan2(inf, -0.)', math.atan2(INF, -0.0), math.pi/2)
361 self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2)
362 self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2)
363 self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000364 self.assertTrue(math.isnan(math.atan2(INF, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000365 # math.atan2(NINF, x)
366 self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4)
367 self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2)
368 self.ftest('atan2(-inf, -0.)', math.atan2(NINF, -0.0), -math.pi/2)
369 self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2)
370 self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2)
371 self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000372 self.assertTrue(math.isnan(math.atan2(NINF, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000373 # math.atan2(+finite, x)
374 self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi)
375 self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2)
376 self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2)
377 self.assertEqual(math.atan2(2.3, INF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000378 self.assertTrue(math.isnan(math.atan2(2.3, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000379 # math.atan2(-finite, x)
380 self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi)
381 self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2)
382 self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2)
383 self.assertEqual(math.atan2(-2.3, INF), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000384 self.assertTrue(math.isnan(math.atan2(-2.3, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000385 # math.atan2(NAN, x)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000386 self.assertTrue(math.isnan(math.atan2(NAN, NINF)))
387 self.assertTrue(math.isnan(math.atan2(NAN, -2.3)))
388 self.assertTrue(math.isnan(math.atan2(NAN, -0.)))
389 self.assertTrue(math.isnan(math.atan2(NAN, 0.)))
390 self.assertTrue(math.isnan(math.atan2(NAN, 2.3)))
391 self.assertTrue(math.isnan(math.atan2(NAN, INF)))
392 self.assertTrue(math.isnan(math.atan2(NAN, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000393
Thomas Wouters89f507f2006-12-13 04:49:30 +0000394 def testCeil(self):
395 self.assertRaises(TypeError, math.ceil)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000396 self.assertEqual(int, type(math.ceil(0.5)))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000397 self.ftest('ceil(0.5)', math.ceil(0.5), 1)
398 self.ftest('ceil(1.0)', math.ceil(1.0), 1)
399 self.ftest('ceil(1.5)', math.ceil(1.5), 2)
400 self.ftest('ceil(-0.5)', math.ceil(-0.5), 0)
401 self.ftest('ceil(-1.0)', math.ceil(-1.0), -1)
402 self.ftest('ceil(-1.5)', math.ceil(-1.5), -1)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000403 #self.assertEqual(math.ceil(INF), INF)
404 #self.assertEqual(math.ceil(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000405 #self.assertTrue(math.isnan(math.ceil(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000406
Guido van Rossum13e05de2007-08-23 22:56:55 +0000407 class TestCeil:
408 def __ceil__(self):
409 return 42
410 class TestNoCeil:
411 pass
412 self.ftest('ceil(TestCeil())', math.ceil(TestCeil()), 42)
413 self.assertRaises(TypeError, math.ceil, TestNoCeil())
414
415 t = TestNoCeil()
416 t.__ceil__ = lambda *args: args
417 self.assertRaises(TypeError, math.ceil, t)
418 self.assertRaises(TypeError, math.ceil, t, 0)
419
Mark Dickinson63566232009-09-18 21:04:19 +0000420 @requires_IEEE_754
421 def testCopysign(self):
Mark Dickinson06b59e02010-02-06 23:16:50 +0000422 self.assertEqual(math.copysign(1, 42), 1.0)
423 self.assertEqual(math.copysign(0., 42), 0.0)
424 self.assertEqual(math.copysign(1., -42), -1.0)
425 self.assertEqual(math.copysign(3, 0.), 3.0)
426 self.assertEqual(math.copysign(4., -0.), -4.0)
427
Mark Dickinson63566232009-09-18 21:04:19 +0000428 self.assertRaises(TypeError, math.copysign)
429 # copysign should let us distinguish signs of zeros
Ezio Melottib3aedd42010-11-20 19:04:17 +0000430 self.assertEqual(math.copysign(1., 0.), 1.)
431 self.assertEqual(math.copysign(1., -0.), -1.)
432 self.assertEqual(math.copysign(INF, 0.), INF)
433 self.assertEqual(math.copysign(INF, -0.), NINF)
434 self.assertEqual(math.copysign(NINF, 0.), INF)
435 self.assertEqual(math.copysign(NINF, -0.), NINF)
Mark Dickinson63566232009-09-18 21:04:19 +0000436 # and of infinities
Ezio Melottib3aedd42010-11-20 19:04:17 +0000437 self.assertEqual(math.copysign(1., INF), 1.)
438 self.assertEqual(math.copysign(1., NINF), -1.)
439 self.assertEqual(math.copysign(INF, INF), INF)
440 self.assertEqual(math.copysign(INF, NINF), NINF)
441 self.assertEqual(math.copysign(NINF, INF), INF)
442 self.assertEqual(math.copysign(NINF, NINF), NINF)
Mark Dickinson06b59e02010-02-06 23:16:50 +0000443 self.assertTrue(math.isnan(math.copysign(NAN, 1.)))
444 self.assertTrue(math.isnan(math.copysign(NAN, INF)))
445 self.assertTrue(math.isnan(math.copysign(NAN, NINF)))
446 self.assertTrue(math.isnan(math.copysign(NAN, NAN)))
Mark Dickinson63566232009-09-18 21:04:19 +0000447 # copysign(INF, NAN) may be INF or it may be NINF, since
448 # we don't know whether the sign bit of NAN is set on any
449 # given platform.
Mark Dickinson06b59e02010-02-06 23:16:50 +0000450 self.assertTrue(math.isinf(math.copysign(INF, NAN)))
Mark Dickinson63566232009-09-18 21:04:19 +0000451 # similarly, copysign(2., NAN) could be 2. or -2.
Ezio Melottib3aedd42010-11-20 19:04:17 +0000452 self.assertEqual(abs(math.copysign(2., NAN)), 2.)
Christian Heimes53876d92008-04-19 00:31:39 +0000453
Thomas Wouters89f507f2006-12-13 04:49:30 +0000454 def testCos(self):
455 self.assertRaises(TypeError, math.cos)
Mark Dickinson96f774d2016-09-03 19:30:22 +0100456 self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0, abs_tol=ulp(1))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000457 self.ftest('cos(0)', math.cos(0), 1)
Mark Dickinson96f774d2016-09-03 19:30:22 +0100458 self.ftest('cos(pi/2)', math.cos(math.pi/2), 0, abs_tol=ulp(1))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000459 self.ftest('cos(pi)', math.cos(math.pi), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000460 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000461 self.assertTrue(math.isnan(math.cos(INF)))
462 self.assertTrue(math.isnan(math.cos(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +0000463 except ValueError:
464 self.assertRaises(ValueError, math.cos, INF)
465 self.assertRaises(ValueError, math.cos, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000466 self.assertTrue(math.isnan(math.cos(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000467
Thomas Wouters89f507f2006-12-13 04:49:30 +0000468 def testCosh(self):
469 self.assertRaises(TypeError, math.cosh)
470 self.ftest('cosh(0)', math.cosh(0), 1)
471 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 +0000472 self.assertEqual(math.cosh(INF), INF)
473 self.assertEqual(math.cosh(NINF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000474 self.assertTrue(math.isnan(math.cosh(NAN)))
Raymond Hettinger64108af2002-05-13 03:55:01 +0000475
Thomas Wouters89f507f2006-12-13 04:49:30 +0000476 def testDegrees(self):
477 self.assertRaises(TypeError, math.degrees)
478 self.ftest('degrees(pi)', math.degrees(math.pi), 180.0)
479 self.ftest('degrees(pi/2)', math.degrees(math.pi/2), 90.0)
480 self.ftest('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0)
Mark Dickinson31ba1c32016-09-04 12:29:14 +0100481 self.ftest('degrees(0)', math.degrees(0), 0)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000482
Thomas Wouters89f507f2006-12-13 04:49:30 +0000483 def testExp(self):
484 self.assertRaises(TypeError, math.exp)
485 self.ftest('exp(-1)', math.exp(-1), 1/math.e)
486 self.ftest('exp(0)', math.exp(0), 1)
487 self.ftest('exp(1)', math.exp(1), math.e)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000488 self.assertEqual(math.exp(INF), INF)
489 self.assertEqual(math.exp(NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000490 self.assertTrue(math.isnan(math.exp(NAN)))
Mark Dickinson31ba1c32016-09-04 12:29:14 +0100491 self.assertRaises(OverflowError, math.exp, 1000000)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000492
Thomas Wouters89f507f2006-12-13 04:49:30 +0000493 def testFabs(self):
494 self.assertRaises(TypeError, math.fabs)
495 self.ftest('fabs(-1)', math.fabs(-1), 1)
496 self.ftest('fabs(0)', math.fabs(0), 0)
497 self.ftest('fabs(1)', math.fabs(1), 1)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000498
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000499 def testFactorial(self):
Mark Dickinson4c8a9a22010-05-15 17:02:38 +0000500 self.assertEqual(math.factorial(0), 1)
501 self.assertEqual(math.factorial(0.0), 1)
502 total = 1
503 for i in range(1, 1000):
504 total *= i
505 self.assertEqual(math.factorial(i), total)
506 self.assertEqual(math.factorial(float(i)), total)
507 self.assertEqual(math.factorial(i), py_factorial(i))
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000508 self.assertRaises(ValueError, math.factorial, -1)
Mark Dickinson4c8a9a22010-05-15 17:02:38 +0000509 self.assertRaises(ValueError, math.factorial, -1.0)
Mark Dickinson5990d282014-04-10 09:29:39 -0400510 self.assertRaises(ValueError, math.factorial, -10**100)
511 self.assertRaises(ValueError, math.factorial, -1e100)
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000512 self.assertRaises(ValueError, math.factorial, math.pi)
Mark Dickinson5990d282014-04-10 09:29:39 -0400513
Pablo Galindoe9ba3702018-09-03 22:20:06 +0100514 def testFactorialNonIntegers(self):
515 self.assertRaises(TypeError, math.factorial, decimal.Decimal(5.2))
516 self.assertRaises(TypeError, math.factorial, "5")
517
Mark Dickinson5990d282014-04-10 09:29:39 -0400518 # Other implementations may place different upper bounds.
519 @support.cpython_only
520 def testFactorialHugeInputs(self):
521 # Currently raises ValueError for inputs that are too large
522 # to fit into a C long.
523 self.assertRaises(OverflowError, math.factorial, 10**100)
524 self.assertRaises(OverflowError, math.factorial, 1e100)
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000525
Thomas Wouters89f507f2006-12-13 04:49:30 +0000526 def testFloor(self):
527 self.assertRaises(TypeError, math.floor)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000528 self.assertEqual(int, type(math.floor(0.5)))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000529 self.ftest('floor(0.5)', math.floor(0.5), 0)
530 self.ftest('floor(1.0)', math.floor(1.0), 1)
531 self.ftest('floor(1.5)', math.floor(1.5), 1)
532 self.ftest('floor(-0.5)', math.floor(-0.5), -1)
533 self.ftest('floor(-1.0)', math.floor(-1.0), -1)
534 self.ftest('floor(-1.5)', math.floor(-1.5), -2)
Guido van Rossum806c2462007-08-06 23:33:07 +0000535 # pow() relies on floor() to check for integers
536 # This fails on some platforms - so check it here
537 self.ftest('floor(1.23e167)', math.floor(1.23e167), 1.23e167)
538 self.ftest('floor(-1.23e167)', math.floor(-1.23e167), -1.23e167)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000539 #self.assertEqual(math.ceil(INF), INF)
540 #self.assertEqual(math.ceil(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000541 #self.assertTrue(math.isnan(math.floor(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000542
Guido van Rossum13e05de2007-08-23 22:56:55 +0000543 class TestFloor:
544 def __floor__(self):
545 return 42
546 class TestNoFloor:
547 pass
548 self.ftest('floor(TestFloor())', math.floor(TestFloor()), 42)
549 self.assertRaises(TypeError, math.floor, TestNoFloor())
550
551 t = TestNoFloor()
552 t.__floor__ = lambda *args: args
553 self.assertRaises(TypeError, math.floor, t)
554 self.assertRaises(TypeError, math.floor, t, 0)
555
Thomas Wouters89f507f2006-12-13 04:49:30 +0000556 def testFmod(self):
557 self.assertRaises(TypeError, math.fmod)
Mark Dickinson5bc7a442011-05-03 21:13:40 +0100558 self.ftest('fmod(10, 1)', math.fmod(10, 1), 0.0)
559 self.ftest('fmod(10, 0.5)', math.fmod(10, 0.5), 0.0)
560 self.ftest('fmod(10, 1.5)', math.fmod(10, 1.5), 1.0)
561 self.ftest('fmod(-10, 1)', math.fmod(-10, 1), -0.0)
562 self.ftest('fmod(-10, 0.5)', math.fmod(-10, 0.5), -0.0)
563 self.ftest('fmod(-10, 1.5)', math.fmod(-10, 1.5), -1.0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000564 self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
565 self.assertTrue(math.isnan(math.fmod(1., NAN)))
566 self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000567 self.assertRaises(ValueError, math.fmod, 1., 0.)
568 self.assertRaises(ValueError, math.fmod, INF, 1.)
569 self.assertRaises(ValueError, math.fmod, NINF, 1.)
570 self.assertRaises(ValueError, math.fmod, INF, 0.)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000571 self.assertEqual(math.fmod(3.0, INF), 3.0)
572 self.assertEqual(math.fmod(-3.0, INF), -3.0)
573 self.assertEqual(math.fmod(3.0, NINF), 3.0)
574 self.assertEqual(math.fmod(-3.0, NINF), -3.0)
575 self.assertEqual(math.fmod(0.0, 3.0), 0.0)
576 self.assertEqual(math.fmod(0.0, NINF), 0.0)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000577
Thomas Wouters89f507f2006-12-13 04:49:30 +0000578 def testFrexp(self):
579 self.assertRaises(TypeError, math.frexp)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000580
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000581 def testfrexp(name, result, expected):
582 (mant, exp), (emant, eexp) = result, expected
Thomas Wouters89f507f2006-12-13 04:49:30 +0000583 if abs(mant-emant) > eps or exp != eexp:
584 self.fail('%s returned %r, expected %r'%\
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000585 (name, result, expected))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000586
Thomas Wouters89f507f2006-12-13 04:49:30 +0000587 testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
588 testfrexp('frexp(0)', math.frexp(0), (0, 0))
589 testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
590 testfrexp('frexp(2)', math.frexp(2), (0.5, 2))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000591
Ezio Melottib3aedd42010-11-20 19:04:17 +0000592 self.assertEqual(math.frexp(INF)[0], INF)
593 self.assertEqual(math.frexp(NINF)[0], NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000594 self.assertTrue(math.isnan(math.frexp(NAN)[0]))
Christian Heimes53876d92008-04-19 00:31:39 +0000595
Mark Dickinson63566232009-09-18 21:04:19 +0000596 @requires_IEEE_754
Mark Dickinson5c567082009-04-24 16:39:07 +0000597 @unittest.skipIf(HAVE_DOUBLE_ROUNDING,
598 "fsum is not exact on machines with double rounding")
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000599 def testFsum(self):
600 # math.fsum relies on exact rounding for correct operation.
601 # There's a known problem with IA32 floating-point that causes
602 # inexact rounding in some situations, and will cause the
603 # math.fsum tests below to fail; see issue #2937. On non IEEE
604 # 754 platforms, and on IEEE 754 platforms that exhibit the
605 # problem described in issue #2937, we simply skip the whole
606 # test.
607
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000608 # Python version of math.fsum, for comparison. Uses a
609 # different algorithm based on frexp, ldexp and integer
610 # arithmetic.
611 from sys import float_info
612 mant_dig = float_info.mant_dig
613 etiny = float_info.min_exp - mant_dig
614
615 def msum(iterable):
616 """Full precision summation. Compute sum(iterable) without any
617 intermediate accumulation of error. Based on the 'lsum' function
618 at http://code.activestate.com/recipes/393090/
619
620 """
621 tmant, texp = 0, 0
622 for x in iterable:
623 mant, exp = math.frexp(x)
624 mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig
625 if texp > exp:
626 tmant <<= texp-exp
627 texp = exp
628 else:
629 mant <<= exp-texp
630 tmant += mant
631 # Round tmant * 2**texp to a float. The original recipe
632 # used float(str(tmant)) * 2.0**texp for this, but that's
633 # a little unsafe because str -> float conversion can't be
634 # relied upon to do correct rounding on all platforms.
635 tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp)
636 if tail > 0:
637 h = 1 << (tail-1)
638 tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1)
639 texp += tail
640 return math.ldexp(tmant, texp)
641
642 test_values = [
643 ([], 0.0),
644 ([0.0], 0.0),
645 ([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100),
646 ([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0),
647 ([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0),
648 ([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0),
649 ([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0),
650 ([1./n for n in range(1, 1001)],
651 float.fromhex('0x1.df11f45f4e61ap+2')),
652 ([(-1.)**n/n for n in range(1, 1001)],
653 float.fromhex('-0x1.62a2af1bd3624p-1')),
654 ([1.7**(i+1)-1.7**i for i in range(1000)] + [-1.7**1000], -1.0),
655 ([1e16, 1., 1e-16], 10000000000000002.0),
656 ([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0),
657 # exercise code for resizing partials array
658 ([2.**n - 2.**(n+50) + 2.**(n+52) for n in range(-1074, 972, 2)] +
659 [-2.**1022],
660 float.fromhex('0x1.5555555555555p+970')),
661 ]
662
663 for i, (vals, expected) in enumerate(test_values):
664 try:
665 actual = math.fsum(vals)
666 except OverflowError:
667 self.fail("test %d failed: got OverflowError, expected %r "
668 "for math.fsum(%.100r)" % (i, expected, vals))
669 except ValueError:
670 self.fail("test %d failed: got ValueError, expected %r "
671 "for math.fsum(%.100r)" % (i, expected, vals))
672 self.assertEqual(actual, expected)
673
674 from random import random, gauss, shuffle
675 for j in range(1000):
676 vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10
677 s = 0
678 for i in range(200):
679 v = gauss(0, random()) ** 7 - s
680 s += v
681 vals.append(v)
682 shuffle(vals)
683
684 s = msum(vals)
685 self.assertEqual(msum(vals), math.fsum(vals))
686
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300687 def testGcd(self):
688 gcd = math.gcd
689 self.assertEqual(gcd(0, 0), 0)
690 self.assertEqual(gcd(1, 0), 1)
691 self.assertEqual(gcd(-1, 0), 1)
692 self.assertEqual(gcd(0, 1), 1)
693 self.assertEqual(gcd(0, -1), 1)
694 self.assertEqual(gcd(7, 1), 1)
695 self.assertEqual(gcd(7, -1), 1)
696 self.assertEqual(gcd(-23, 15), 1)
697 self.assertEqual(gcd(120, 84), 12)
698 self.assertEqual(gcd(84, -120), 12)
699 self.assertEqual(gcd(1216342683557601535506311712,
700 436522681849110124616458784), 32)
701 c = 652560
702 x = 434610456570399902378880679233098819019853229470286994367836600566
703 y = 1064502245825115327754847244914921553977
704 a = x * c
705 b = y * c
706 self.assertEqual(gcd(a, b), c)
707 self.assertEqual(gcd(b, a), c)
708 self.assertEqual(gcd(-a, b), c)
709 self.assertEqual(gcd(b, -a), 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 c = 576559230871654959816130551884856912003141446781646602790216406874
715 a = x * c
716 b = y * c
717 self.assertEqual(gcd(a, b), c)
718 self.assertEqual(gcd(b, a), c)
719 self.assertEqual(gcd(-a, b), c)
720 self.assertEqual(gcd(b, -a), c)
721 self.assertEqual(gcd(a, -b), c)
722 self.assertEqual(gcd(-b, a), c)
723 self.assertEqual(gcd(-a, -b), c)
724 self.assertEqual(gcd(-b, -a), c)
725
726 self.assertRaises(TypeError, gcd, 120.0, 84)
727 self.assertRaises(TypeError, gcd, 120, 84.0)
728 self.assertEqual(gcd(MyIndexable(120), MyIndexable(84)), 12)
729
Thomas Wouters89f507f2006-12-13 04:49:30 +0000730 def testHypot(self):
Raymond Hettingerc6dabe32018-07-28 07:48:04 -0700731 from decimal import Decimal
732 from fractions import Fraction
733
734 hypot = math.hypot
735
736 # Test different numbers of arguments (from zero to five)
737 # against a straightforward pure python implementation
738 args = math.e, math.pi, math.sqrt(2.0), math.gamma(3.5), math.sin(2.1)
739 for i in range(len(args)+1):
740 self.assertAlmostEqual(
741 hypot(*args[:i]),
742 math.sqrt(sum(s**2 for s in args[:i]))
743 )
744
745 # Test allowable types (those with __float__)
746 self.assertEqual(hypot(12.0, 5.0), 13.0)
747 self.assertEqual(hypot(12, 5), 13)
748 self.assertEqual(hypot(Decimal(12), Decimal(5)), 13)
749 self.assertEqual(hypot(Fraction(12, 32), Fraction(5, 32)), Fraction(13, 32))
750 self.assertEqual(hypot(bool(1), bool(0), bool(1), bool(1)), math.sqrt(3))
751
752 # Test corner cases
753 self.assertEqual(hypot(0.0, 0.0), 0.0) # Max input is zero
754 self.assertEqual(hypot(-10.5), 10.5) # Negative input
755 self.assertEqual(hypot(), 0.0) # Negative input
756 self.assertEqual(1.0,
757 math.copysign(1.0, hypot(-0.0)) # Convert negative zero to positive zero
758 )
Raymond Hettinger00414592018-08-12 12:15:23 -0700759 self.assertEqual( # Handling of moving max to the end
760 hypot(1.5, 1.5, 0.5),
761 hypot(1.5, 0.5, 1.5),
762 )
Raymond Hettingerc6dabe32018-07-28 07:48:04 -0700763
764 # Test handling of bad arguments
765 with self.assertRaises(TypeError): # Reject keyword args
766 hypot(x=1)
767 with self.assertRaises(TypeError): # Reject values without __float__
768 hypot(1.1, 'string', 2.2)
769
770 # Any infinity gives positive infinity.
771 self.assertEqual(hypot(INF), INF)
772 self.assertEqual(hypot(0, INF), INF)
773 self.assertEqual(hypot(10, INF), INF)
774 self.assertEqual(hypot(-10, INF), INF)
775 self.assertEqual(hypot(NAN, INF), INF)
776 self.assertEqual(hypot(INF, NAN), INF)
777 self.assertEqual(hypot(NINF, NAN), INF)
778 self.assertEqual(hypot(NAN, NINF), INF)
779 self.assertEqual(hypot(-INF, INF), INF)
780 self.assertEqual(hypot(-INF, -INF), INF)
781 self.assertEqual(hypot(10, -INF), INF)
782
Raymond Hettinger00414592018-08-12 12:15:23 -0700783 # If no infinity, any NaN gives a NaN.
Raymond Hettingerc6dabe32018-07-28 07:48:04 -0700784 self.assertTrue(math.isnan(hypot(NAN)))
785 self.assertTrue(math.isnan(hypot(0, NAN)))
786 self.assertTrue(math.isnan(hypot(NAN, 10)))
787 self.assertTrue(math.isnan(hypot(10, NAN)))
788 self.assertTrue(math.isnan(hypot(NAN, NAN)))
789 self.assertTrue(math.isnan(hypot(NAN)))
790
791 # Verify scaling for extremely large values
792 fourthmax = FLOAT_MAX / 4.0
793 for n in range(32):
794 self.assertEqual(hypot(*([fourthmax]*n)), fourthmax * math.sqrt(n))
795
796 # Verify scaling for extremely small values
797 for exp in range(32):
798 scale = FLOAT_MIN / 2.0 ** exp
799 self.assertEqual(math.hypot(4*scale, 3*scale), 5*scale)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000800
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700801 def testDist(self):
802 from decimal import Decimal as D
803 from fractions import Fraction as F
804
805 dist = math.dist
806 sqrt = math.sqrt
807
808 # Simple exact case
809 self.assertEqual(dist((1, 2, 3), (4, 2, -1)), 5.0)
810
811 # Test different numbers of arguments (from zero to nine)
812 # against a straightforward pure python implementation
813 for i in range(9):
814 for j in range(5):
815 p = tuple(random.uniform(-5, 5) for k in range(i))
816 q = tuple(random.uniform(-5, 5) for k in range(i))
817 self.assertAlmostEqual(
818 dist(p, q),
819 sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
820 )
821
822 # Test allowable types (those with __float__)
823 self.assertEqual(dist((14.0, 1.0), (2.0, -4.0)), 13.0)
824 self.assertEqual(dist((14, 1), (2, -4)), 13)
825 self.assertEqual(dist((D(14), D(1)), (D(2), D(-4))), D(13))
826 self.assertEqual(dist((F(14, 32), F(1, 32)), (F(2, 32), F(-4, 32))),
827 F(13, 32))
828 self.assertEqual(dist((True, True, False, True, False),
829 (True, False, True, True, False)),
830 sqrt(2.0))
831
832 # Test corner cases
833 self.assertEqual(dist((13.25, 12.5, -3.25),
834 (13.25, 12.5, -3.25)),
835 0.0) # Distance with self is zero
836 self.assertEqual(dist((), ()), 0.0) # Zero-dimensional case
837 self.assertEqual(1.0, # Convert negative zero to positive zero
838 math.copysign(1.0, dist((-0.0,), (0.0,)))
839 )
840 self.assertEqual(1.0, # Convert negative zero to positive zero
841 math.copysign(1.0, dist((0.0,), (-0.0,)))
842 )
Raymond Hettinger00414592018-08-12 12:15:23 -0700843 self.assertEqual( # Handling of moving max to the end
844 dist((1.5, 1.5, 0.5), (0, 0, 0)),
845 dist((1.5, 0.5, 1.5), (0, 0, 0))
846 )
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700847
848 # Verify tuple subclasses are allowed
Raymond Hettinger00414592018-08-12 12:15:23 -0700849 class T(tuple):
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700850 pass
851 self.assertEqual(dist(T((1, 2, 3)), ((4, 2, -1))), 5.0)
852
853 # Test handling of bad arguments
854 with self.assertRaises(TypeError): # Reject keyword args
855 dist(p=(1, 2, 3), q=(4, 5, 6))
856 with self.assertRaises(TypeError): # Too few args
857 dist((1, 2, 3))
858 with self.assertRaises(TypeError): # Too many args
859 dist((1, 2, 3), (4, 5, 6), (7, 8, 9))
860 with self.assertRaises(TypeError): # Scalars not allowed
861 dist(1, 2)
862 with self.assertRaises(TypeError): # Lists not allowed
863 dist([1, 2, 3], [4, 5, 6])
864 with self.assertRaises(TypeError): # Reject values without __float__
865 dist((1.1, 'string', 2.2), (1, 2, 3))
866 with self.assertRaises(ValueError): # Check dimension agree
867 dist((1, 2, 3, 4), (5, 6, 7))
868 with self.assertRaises(ValueError): # Check dimension agree
869 dist((1, 2, 3), (4, 5, 6, 7))
870
Raymond Hettinger00414592018-08-12 12:15:23 -0700871 # Verify that the one dimensional case is equivalent to abs()
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700872 for i in range(20):
873 p, q = random.random(), random.random()
874 self.assertEqual(dist((p,), (q,)), abs(p - q))
875
876 # Test special values
877 values = [NINF, -10.5, -0.0, 0.0, 10.5, INF, NAN]
878 for p in itertools.product(values, repeat=3):
879 for q in itertools.product(values, repeat=3):
880 diffs = [px - qx for px, qx in zip(p, q)]
881 if any(map(math.isinf, diffs)):
882 # Any infinite difference gives positive infinity.
883 self.assertEqual(dist(p, q), INF)
884 elif any(map(math.isnan, diffs)):
Raymond Hettinger00414592018-08-12 12:15:23 -0700885 # If no infinity, any NaN gives a NaN.
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700886 self.assertTrue(math.isnan(dist(p, q)))
887
888 # Verify scaling for extremely large values
889 fourthmax = FLOAT_MAX / 4.0
890 for n in range(32):
891 p = (fourthmax,) * n
892 q = (0.0,) * n
893 self.assertEqual(dist(p, q), fourthmax * math.sqrt(n))
894 self.assertEqual(dist(q, p), fourthmax * math.sqrt(n))
895
896 # Verify scaling for extremely small values
897 for exp in range(32):
898 scale = FLOAT_MIN / 2.0 ** exp
899 p = (4*scale, 3*scale)
900 q = (0.0, 0.0)
901 self.assertEqual(math.dist(p, q), 5*scale)
902 self.assertEqual(math.dist(q, p), 5*scale)
903
904
Thomas Wouters89f507f2006-12-13 04:49:30 +0000905 def testLdexp(self):
906 self.assertRaises(TypeError, math.ldexp)
907 self.ftest('ldexp(0,1)', math.ldexp(0,1), 0)
908 self.ftest('ldexp(1,1)', math.ldexp(1,1), 2)
909 self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5)
910 self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2)
Christian Heimes53876d92008-04-19 00:31:39 +0000911 self.assertRaises(OverflowError, math.ldexp, 1., 1000000)
912 self.assertRaises(OverflowError, math.ldexp, -1., 1000000)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000913 self.assertEqual(math.ldexp(1., -1000000), 0.)
914 self.assertEqual(math.ldexp(-1., -1000000), -0.)
915 self.assertEqual(math.ldexp(INF, 30), INF)
916 self.assertEqual(math.ldexp(NINF, -213), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000917 self.assertTrue(math.isnan(math.ldexp(NAN, 0)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000918
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000919 # large second argument
920 for n in [10**5, 10**10, 10**20, 10**40]:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000921 self.assertEqual(math.ldexp(INF, -n), INF)
922 self.assertEqual(math.ldexp(NINF, -n), NINF)
923 self.assertEqual(math.ldexp(1., -n), 0.)
924 self.assertEqual(math.ldexp(-1., -n), -0.)
925 self.assertEqual(math.ldexp(0., -n), 0.)
926 self.assertEqual(math.ldexp(-0., -n), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000927 self.assertTrue(math.isnan(math.ldexp(NAN, -n)))
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000928
929 self.assertRaises(OverflowError, math.ldexp, 1., n)
930 self.assertRaises(OverflowError, math.ldexp, -1., n)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000931 self.assertEqual(math.ldexp(0., n), 0.)
932 self.assertEqual(math.ldexp(-0., n), -0.)
933 self.assertEqual(math.ldexp(INF, n), INF)
934 self.assertEqual(math.ldexp(NINF, n), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000935 self.assertTrue(math.isnan(math.ldexp(NAN, n)))
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000936
Thomas Wouters89f507f2006-12-13 04:49:30 +0000937 def testLog(self):
938 self.assertRaises(TypeError, math.log)
939 self.ftest('log(1/e)', math.log(1/math.e), -1)
940 self.ftest('log(1)', math.log(1), 0)
941 self.ftest('log(e)', math.log(math.e), 1)
942 self.ftest('log(32,2)', math.log(32,2), 5)
943 self.ftest('log(10**40, 10)', math.log(10**40, 10), 40)
944 self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2)
Mark Dickinsonc6037172010-09-29 19:06:36 +0000945 self.ftest('log(10**1000)', math.log(10**1000),
946 2302.5850929940457)
947 self.assertRaises(ValueError, math.log, -1.5)
948 self.assertRaises(ValueError, math.log, -10**1000)
Christian Heimes53876d92008-04-19 00:31:39 +0000949 self.assertRaises(ValueError, math.log, NINF)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000950 self.assertEqual(math.log(INF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000951 self.assertTrue(math.isnan(math.log(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000952
953 def testLog1p(self):
954 self.assertRaises(TypeError, math.log1p)
Mark Dickinson31ba1c32016-09-04 12:29:14 +0100955 for n in [2, 2**90, 2**300]:
956 self.assertAlmostEqual(math.log1p(n), math.log1p(float(n)))
957 self.assertRaises(ValueError, math.log1p, -1)
958 self.assertEqual(math.log1p(INF), INF)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000959
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200960 @requires_IEEE_754
961 def testLog2(self):
962 self.assertRaises(TypeError, math.log2)
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200963
964 # Check some integer values
965 self.assertEqual(math.log2(1), 0.0)
966 self.assertEqual(math.log2(2), 1.0)
967 self.assertEqual(math.log2(4), 2.0)
968
969 # Large integer values
970 self.assertEqual(math.log2(2**1023), 1023.0)
971 self.assertEqual(math.log2(2**1024), 1024.0)
972 self.assertEqual(math.log2(2**2000), 2000.0)
973
974 self.assertRaises(ValueError, math.log2, -1.5)
975 self.assertRaises(ValueError, math.log2, NINF)
976 self.assertTrue(math.isnan(math.log2(NAN)))
977
Victor Stinnercd9dd372011-05-10 23:40:17 +0200978 @requires_IEEE_754
Victor Stinnerebbbdaf2011-06-01 13:19:07 +0200979 # log2() is not accurate enough on Mac OS X Tiger (10.4)
980 @support.requires_mac_ver(10, 5)
Victor Stinnercd9dd372011-05-10 23:40:17 +0200981 def testLog2Exact(self):
982 # Check that we get exact equality for log2 of powers of 2.
983 actual = [math.log2(math.ldexp(1.0, n)) for n in range(-1074, 1024)]
984 expected = [float(n) for n in range(-1074, 1024)]
985 self.assertEqual(actual, expected)
986
Thomas Wouters89f507f2006-12-13 04:49:30 +0000987 def testLog10(self):
988 self.assertRaises(TypeError, math.log10)
989 self.ftest('log10(0.1)', math.log10(0.1), -1)
990 self.ftest('log10(1)', math.log10(1), 0)
991 self.ftest('log10(10)', math.log10(10), 1)
Mark Dickinsonc6037172010-09-29 19:06:36 +0000992 self.ftest('log10(10**1000)', math.log10(10**1000), 1000.0)
993 self.assertRaises(ValueError, math.log10, -1.5)
994 self.assertRaises(ValueError, math.log10, -10**1000)
Christian Heimes53876d92008-04-19 00:31:39 +0000995 self.assertRaises(ValueError, math.log10, NINF)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000996 self.assertEqual(math.log(INF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000997 self.assertTrue(math.isnan(math.log10(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000998
Thomas Wouters89f507f2006-12-13 04:49:30 +0000999 def testModf(self):
1000 self.assertRaises(TypeError, math.modf)
Guido van Rossumfcce6301996-08-08 18:26:25 +00001001
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001002 def testmodf(name, result, expected):
1003 (v1, v2), (e1, e2) = result, expected
Thomas Wouters89f507f2006-12-13 04:49:30 +00001004 if abs(v1-e1) > eps or abs(v2-e2):
1005 self.fail('%s returned %r, expected %r'%\
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001006 (name, result, expected))
Raymond Hettinger64108af2002-05-13 03:55:01 +00001007
Thomas Wouters89f507f2006-12-13 04:49:30 +00001008 testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
1009 testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
Guido van Rossumfcce6301996-08-08 18:26:25 +00001010
Ezio Melottib3aedd42010-11-20 19:04:17 +00001011 self.assertEqual(math.modf(INF), (0.0, INF))
1012 self.assertEqual(math.modf(NINF), (-0.0, NINF))
Christian Heimes53876d92008-04-19 00:31:39 +00001013
1014 modf_nan = math.modf(NAN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001015 self.assertTrue(math.isnan(modf_nan[0]))
1016 self.assertTrue(math.isnan(modf_nan[1]))
Christian Heimes53876d92008-04-19 00:31:39 +00001017
Thomas Wouters89f507f2006-12-13 04:49:30 +00001018 def testPow(self):
1019 self.assertRaises(TypeError, math.pow)
1020 self.ftest('pow(0,1)', math.pow(0,1), 0)
1021 self.ftest('pow(1,0)', math.pow(1,0), 1)
1022 self.ftest('pow(2,1)', math.pow(2,1), 2)
1023 self.ftest('pow(2,-1)', math.pow(2,-1), 0.5)
Christian Heimes53876d92008-04-19 00:31:39 +00001024 self.assertEqual(math.pow(INF, 1), INF)
1025 self.assertEqual(math.pow(NINF, 1), NINF)
1026 self.assertEqual((math.pow(1, INF)), 1.)
1027 self.assertEqual((math.pow(1, NINF)), 1.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001028 self.assertTrue(math.isnan(math.pow(NAN, 1)))
1029 self.assertTrue(math.isnan(math.pow(2, NAN)))
1030 self.assertTrue(math.isnan(math.pow(0, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +00001031 self.assertEqual(math.pow(1, NAN), 1)
Christian Heimesa342c012008-04-20 21:01:16 +00001032
1033 # pow(0., x)
1034 self.assertEqual(math.pow(0., INF), 0.)
1035 self.assertEqual(math.pow(0., 3.), 0.)
1036 self.assertEqual(math.pow(0., 2.3), 0.)
1037 self.assertEqual(math.pow(0., 2.), 0.)
1038 self.assertEqual(math.pow(0., 0.), 1.)
1039 self.assertEqual(math.pow(0., -0.), 1.)
1040 self.assertRaises(ValueError, math.pow, 0., -2.)
1041 self.assertRaises(ValueError, math.pow, 0., -2.3)
1042 self.assertRaises(ValueError, math.pow, 0., -3.)
1043 self.assertRaises(ValueError, math.pow, 0., NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001044 self.assertTrue(math.isnan(math.pow(0., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +00001045
1046 # pow(INF, x)
1047 self.assertEqual(math.pow(INF, INF), INF)
1048 self.assertEqual(math.pow(INF, 3.), INF)
1049 self.assertEqual(math.pow(INF, 2.3), INF)
1050 self.assertEqual(math.pow(INF, 2.), INF)
1051 self.assertEqual(math.pow(INF, 0.), 1.)
1052 self.assertEqual(math.pow(INF, -0.), 1.)
1053 self.assertEqual(math.pow(INF, -2.), 0.)
1054 self.assertEqual(math.pow(INF, -2.3), 0.)
1055 self.assertEqual(math.pow(INF, -3.), 0.)
1056 self.assertEqual(math.pow(INF, NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001057 self.assertTrue(math.isnan(math.pow(INF, NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +00001058
1059 # pow(-0., x)
1060 self.assertEqual(math.pow(-0., INF), 0.)
1061 self.assertEqual(math.pow(-0., 3.), -0.)
1062 self.assertEqual(math.pow(-0., 2.3), 0.)
1063 self.assertEqual(math.pow(-0., 2.), 0.)
1064 self.assertEqual(math.pow(-0., 0.), 1.)
1065 self.assertEqual(math.pow(-0., -0.), 1.)
1066 self.assertRaises(ValueError, math.pow, -0., -2.)
1067 self.assertRaises(ValueError, math.pow, -0., -2.3)
1068 self.assertRaises(ValueError, math.pow, -0., -3.)
1069 self.assertRaises(ValueError, math.pow, -0., NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001070 self.assertTrue(math.isnan(math.pow(-0., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +00001071
1072 # pow(NINF, x)
1073 self.assertEqual(math.pow(NINF, INF), INF)
1074 self.assertEqual(math.pow(NINF, 3.), NINF)
1075 self.assertEqual(math.pow(NINF, 2.3), INF)
1076 self.assertEqual(math.pow(NINF, 2.), INF)
1077 self.assertEqual(math.pow(NINF, 0.), 1.)
1078 self.assertEqual(math.pow(NINF, -0.), 1.)
1079 self.assertEqual(math.pow(NINF, -2.), 0.)
1080 self.assertEqual(math.pow(NINF, -2.3), 0.)
1081 self.assertEqual(math.pow(NINF, -3.), -0.)
1082 self.assertEqual(math.pow(NINF, NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001083 self.assertTrue(math.isnan(math.pow(NINF, NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +00001084
1085 # pow(-1, x)
1086 self.assertEqual(math.pow(-1., INF), 1.)
1087 self.assertEqual(math.pow(-1., 3.), -1.)
1088 self.assertRaises(ValueError, math.pow, -1., 2.3)
1089 self.assertEqual(math.pow(-1., 2.), 1.)
1090 self.assertEqual(math.pow(-1., 0.), 1.)
1091 self.assertEqual(math.pow(-1., -0.), 1.)
1092 self.assertEqual(math.pow(-1., -2.), 1.)
1093 self.assertRaises(ValueError, math.pow, -1., -2.3)
1094 self.assertEqual(math.pow(-1., -3.), -1.)
1095 self.assertEqual(math.pow(-1., NINF), 1.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001096 self.assertTrue(math.isnan(math.pow(-1., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +00001097
1098 # pow(1, x)
1099 self.assertEqual(math.pow(1., INF), 1.)
1100 self.assertEqual(math.pow(1., 3.), 1.)
1101 self.assertEqual(math.pow(1., 2.3), 1.)
1102 self.assertEqual(math.pow(1., 2.), 1.)
1103 self.assertEqual(math.pow(1., 0.), 1.)
1104 self.assertEqual(math.pow(1., -0.), 1.)
1105 self.assertEqual(math.pow(1., -2.), 1.)
1106 self.assertEqual(math.pow(1., -2.3), 1.)
1107 self.assertEqual(math.pow(1., -3.), 1.)
1108 self.assertEqual(math.pow(1., NINF), 1.)
1109 self.assertEqual(math.pow(1., NAN), 1.)
1110
1111 # pow(x, 0) should be 1 for any x
1112 self.assertEqual(math.pow(2.3, 0.), 1.)
1113 self.assertEqual(math.pow(-2.3, 0.), 1.)
1114 self.assertEqual(math.pow(NAN, 0.), 1.)
1115 self.assertEqual(math.pow(2.3, -0.), 1.)
1116 self.assertEqual(math.pow(-2.3, -0.), 1.)
1117 self.assertEqual(math.pow(NAN, -0.), 1.)
1118
1119 # pow(x, y) is invalid if x is negative and y is not integral
1120 self.assertRaises(ValueError, math.pow, -1., 2.3)
1121 self.assertRaises(ValueError, math.pow, -15., -3.1)
1122
1123 # pow(x, NINF)
1124 self.assertEqual(math.pow(1.9, NINF), 0.)
1125 self.assertEqual(math.pow(1.1, NINF), 0.)
1126 self.assertEqual(math.pow(0.9, NINF), INF)
1127 self.assertEqual(math.pow(0.1, NINF), INF)
1128 self.assertEqual(math.pow(-0.1, NINF), INF)
1129 self.assertEqual(math.pow(-0.9, NINF), INF)
1130 self.assertEqual(math.pow(-1.1, NINF), 0.)
1131 self.assertEqual(math.pow(-1.9, NINF), 0.)
1132
1133 # pow(x, INF)
1134 self.assertEqual(math.pow(1.9, INF), INF)
1135 self.assertEqual(math.pow(1.1, INF), INF)
1136 self.assertEqual(math.pow(0.9, INF), 0.)
1137 self.assertEqual(math.pow(0.1, INF), 0.)
1138 self.assertEqual(math.pow(-0.1, INF), 0.)
1139 self.assertEqual(math.pow(-0.9, INF), 0.)
1140 self.assertEqual(math.pow(-1.1, INF), INF)
1141 self.assertEqual(math.pow(-1.9, INF), INF)
1142
1143 # pow(x, y) should work for x negative, y an integer
1144 self.ftest('(-2.)**3.', math.pow(-2.0, 3.0), -8.0)
1145 self.ftest('(-2.)**2.', math.pow(-2.0, 2.0), 4.0)
1146 self.ftest('(-2.)**1.', math.pow(-2.0, 1.0), -2.0)
1147 self.ftest('(-2.)**0.', math.pow(-2.0, 0.0), 1.0)
1148 self.ftest('(-2.)**-0.', math.pow(-2.0, -0.0), 1.0)
1149 self.ftest('(-2.)**-1.', math.pow(-2.0, -1.0), -0.5)
1150 self.ftest('(-2.)**-2.', math.pow(-2.0, -2.0), 0.25)
1151 self.ftest('(-2.)**-3.', math.pow(-2.0, -3.0), -0.125)
1152 self.assertRaises(ValueError, math.pow, -2.0, -0.5)
1153 self.assertRaises(ValueError, math.pow, -2.0, 0.5)
1154
1155 # the following tests have been commented out since they don't
1156 # really belong here: the implementation of ** for floats is
Ezio Melotti13925002011-03-16 11:05:33 +02001157 # independent of the implementation of math.pow
Christian Heimesa342c012008-04-20 21:01:16 +00001158 #self.assertEqual(1**NAN, 1)
1159 #self.assertEqual(1**INF, 1)
1160 #self.assertEqual(1**NINF, 1)
1161 #self.assertEqual(1**0, 1)
1162 #self.assertEqual(1.**NAN, 1)
1163 #self.assertEqual(1.**INF, 1)
1164 #self.assertEqual(1.**NINF, 1)
1165 #self.assertEqual(1.**0, 1)
Guido van Rossumfcce6301996-08-08 18:26:25 +00001166
Thomas Wouters89f507f2006-12-13 04:49:30 +00001167 def testRadians(self):
1168 self.assertRaises(TypeError, math.radians)
1169 self.ftest('radians(180)', math.radians(180), math.pi)
1170 self.ftest('radians(90)', math.radians(90), math.pi/2)
1171 self.ftest('radians(-45)', math.radians(-45), -math.pi/4)
Mark Dickinson31ba1c32016-09-04 12:29:14 +01001172 self.ftest('radians(0)', math.radians(0), 0)
Guido van Rossumfcce6301996-08-08 18:26:25 +00001173
Mark Dickinsona0ce3752017-04-05 18:34:27 +01001174 @requires_IEEE_754
1175 def testRemainder(self):
1176 from fractions import Fraction
1177
1178 def validate_spec(x, y, r):
1179 """
1180 Check that r matches remainder(x, y) according to the IEEE 754
1181 specification. Assumes that x, y and r are finite and y is nonzero.
1182 """
1183 fx, fy, fr = Fraction(x), Fraction(y), Fraction(r)
1184 # r should not exceed y/2 in absolute value
1185 self.assertLessEqual(abs(fr), abs(fy/2))
1186 # x - r should be an exact integer multiple of y
1187 n = (fx - fr) / fy
1188 self.assertEqual(n, int(n))
1189 if abs(fr) == abs(fy/2):
1190 # If |r| == |y/2|, n should be even.
1191 self.assertEqual(n/2, int(n/2))
1192
1193 # triples (x, y, remainder(x, y)) in hexadecimal form.
1194 testcases = [
1195 # Remainders modulo 1, showing the ties-to-even behaviour.
1196 '-4.0 1 -0.0',
1197 '-3.8 1 0.8',
1198 '-3.0 1 -0.0',
1199 '-2.8 1 -0.8',
1200 '-2.0 1 -0.0',
1201 '-1.8 1 0.8',
1202 '-1.0 1 -0.0',
1203 '-0.8 1 -0.8',
1204 '-0.0 1 -0.0',
1205 ' 0.0 1 0.0',
1206 ' 0.8 1 0.8',
1207 ' 1.0 1 0.0',
1208 ' 1.8 1 -0.8',
1209 ' 2.0 1 0.0',
1210 ' 2.8 1 0.8',
1211 ' 3.0 1 0.0',
1212 ' 3.8 1 -0.8',
1213 ' 4.0 1 0.0',
1214
1215 # Reductions modulo 2*pi
1216 '0x0.0p+0 0x1.921fb54442d18p+2 0x0.0p+0',
1217 '0x1.921fb54442d18p+0 0x1.921fb54442d18p+2 0x1.921fb54442d18p+0',
1218 '0x1.921fb54442d17p+1 0x1.921fb54442d18p+2 0x1.921fb54442d17p+1',
1219 '0x1.921fb54442d18p+1 0x1.921fb54442d18p+2 0x1.921fb54442d18p+1',
1220 '0x1.921fb54442d19p+1 0x1.921fb54442d18p+2 -0x1.921fb54442d17p+1',
1221 '0x1.921fb54442d17p+2 0x1.921fb54442d18p+2 -0x0.0000000000001p+2',
1222 '0x1.921fb54442d18p+2 0x1.921fb54442d18p+2 0x0p0',
1223 '0x1.921fb54442d19p+2 0x1.921fb54442d18p+2 0x0.0000000000001p+2',
1224 '0x1.2d97c7f3321d1p+3 0x1.921fb54442d18p+2 0x1.921fb54442d14p+1',
1225 '0x1.2d97c7f3321d2p+3 0x1.921fb54442d18p+2 -0x1.921fb54442d18p+1',
1226 '0x1.2d97c7f3321d3p+3 0x1.921fb54442d18p+2 -0x1.921fb54442d14p+1',
1227 '0x1.921fb54442d17p+3 0x1.921fb54442d18p+2 -0x0.0000000000001p+3',
1228 '0x1.921fb54442d18p+3 0x1.921fb54442d18p+2 0x0p0',
1229 '0x1.921fb54442d19p+3 0x1.921fb54442d18p+2 0x0.0000000000001p+3',
1230 '0x1.f6a7a2955385dp+3 0x1.921fb54442d18p+2 0x1.921fb54442d14p+1',
1231 '0x1.f6a7a2955385ep+3 0x1.921fb54442d18p+2 0x1.921fb54442d18p+1',
1232 '0x1.f6a7a2955385fp+3 0x1.921fb54442d18p+2 -0x1.921fb54442d14p+1',
1233 '0x1.1475cc9eedf00p+5 0x1.921fb54442d18p+2 0x1.921fb54442d10p+1',
1234 '0x1.1475cc9eedf01p+5 0x1.921fb54442d18p+2 -0x1.921fb54442d10p+1',
1235
1236 # Symmetry with respect to signs.
1237 ' 1 0.c 0.4',
1238 '-1 0.c -0.4',
1239 ' 1 -0.c 0.4',
1240 '-1 -0.c -0.4',
1241 ' 1.4 0.c -0.4',
1242 '-1.4 0.c 0.4',
1243 ' 1.4 -0.c -0.4',
1244 '-1.4 -0.c 0.4',
1245
1246 # Huge modulus, to check that the underlying algorithm doesn't
1247 # rely on 2.0 * modulus being representable.
1248 '0x1.dp+1023 0x1.4p+1023 0x0.9p+1023',
1249 '0x1.ep+1023 0x1.4p+1023 -0x0.ap+1023',
1250 '0x1.fp+1023 0x1.4p+1023 -0x0.9p+1023',
1251 ]
1252
1253 for case in testcases:
1254 with self.subTest(case=case):
1255 x_hex, y_hex, expected_hex = case.split()
1256 x = float.fromhex(x_hex)
1257 y = float.fromhex(y_hex)
1258 expected = float.fromhex(expected_hex)
1259 validate_spec(x, y, expected)
1260 actual = math.remainder(x, y)
1261 # Cheap way of checking that the floats are
1262 # as identical as we need them to be.
1263 self.assertEqual(actual.hex(), expected.hex())
1264
1265 # Test tiny subnormal modulus: there's potential for
1266 # getting the implementation wrong here (for example,
1267 # by assuming that modulus/2 is exactly representable).
1268 tiny = float.fromhex('1p-1074') # min +ve subnormal
1269 for n in range(-25, 25):
1270 if n == 0:
1271 continue
1272 y = n * tiny
1273 for m in range(100):
1274 x = m * tiny
1275 actual = math.remainder(x, y)
1276 validate_spec(x, y, actual)
1277 actual = math.remainder(-x, y)
1278 validate_spec(-x, y, actual)
1279
1280 # Special values.
1281 # NaNs should propagate as usual.
1282 for value in [NAN, 0.0, -0.0, 2.0, -2.3, NINF, INF]:
1283 self.assertIsNaN(math.remainder(NAN, value))
1284 self.assertIsNaN(math.remainder(value, NAN))
1285
1286 # remainder(x, inf) is x, for non-nan non-infinite x.
1287 for value in [-2.3, -0.0, 0.0, 2.3]:
1288 self.assertEqual(math.remainder(value, INF), value)
1289 self.assertEqual(math.remainder(value, NINF), value)
1290
1291 # remainder(x, 0) and remainder(infinity, x) for non-NaN x are invalid
1292 # operations according to IEEE 754-2008 7.2(f), and should raise.
1293 for value in [NINF, -2.3, -0.0, 0.0, 2.3, INF]:
1294 with self.assertRaises(ValueError):
1295 math.remainder(INF, value)
1296 with self.assertRaises(ValueError):
1297 math.remainder(NINF, value)
1298 with self.assertRaises(ValueError):
1299 math.remainder(value, 0.0)
1300 with self.assertRaises(ValueError):
1301 math.remainder(value, -0.0)
1302
Thomas Wouters89f507f2006-12-13 04:49:30 +00001303 def testSin(self):
1304 self.assertRaises(TypeError, math.sin)
1305 self.ftest('sin(0)', math.sin(0), 0)
1306 self.ftest('sin(pi/2)', math.sin(math.pi/2), 1)
1307 self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1)
Christian Heimes53876d92008-04-19 00:31:39 +00001308 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001309 self.assertTrue(math.isnan(math.sin(INF)))
1310 self.assertTrue(math.isnan(math.sin(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +00001311 except ValueError:
1312 self.assertRaises(ValueError, math.sin, INF)
1313 self.assertRaises(ValueError, math.sin, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001314 self.assertTrue(math.isnan(math.sin(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +00001315
Thomas Wouters89f507f2006-12-13 04:49:30 +00001316 def testSinh(self):
1317 self.assertRaises(TypeError, math.sinh)
1318 self.ftest('sinh(0)', math.sinh(0), 0)
1319 self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1)
1320 self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001321 self.assertEqual(math.sinh(INF), INF)
1322 self.assertEqual(math.sinh(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001323 self.assertTrue(math.isnan(math.sinh(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +00001324
Thomas Wouters89f507f2006-12-13 04:49:30 +00001325 def testSqrt(self):
1326 self.assertRaises(TypeError, math.sqrt)
1327 self.ftest('sqrt(0)', math.sqrt(0), 0)
1328 self.ftest('sqrt(1)', math.sqrt(1), 1)
1329 self.ftest('sqrt(4)', math.sqrt(4), 2)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001330 self.assertEqual(math.sqrt(INF), INF)
Mark Dickinson31ba1c32016-09-04 12:29:14 +01001331 self.assertRaises(ValueError, math.sqrt, -1)
Christian Heimes53876d92008-04-19 00:31:39 +00001332 self.assertRaises(ValueError, math.sqrt, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001333 self.assertTrue(math.isnan(math.sqrt(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +00001334
Thomas Wouters89f507f2006-12-13 04:49:30 +00001335 def testTan(self):
1336 self.assertRaises(TypeError, math.tan)
1337 self.ftest('tan(0)', math.tan(0), 0)
1338 self.ftest('tan(pi/4)', math.tan(math.pi/4), 1)
1339 self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1)
Christian Heimes53876d92008-04-19 00:31:39 +00001340 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001341 self.assertTrue(math.isnan(math.tan(INF)))
1342 self.assertTrue(math.isnan(math.tan(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +00001343 except:
1344 self.assertRaises(ValueError, math.tan, INF)
1345 self.assertRaises(ValueError, math.tan, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001346 self.assertTrue(math.isnan(math.tan(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +00001347
Thomas Wouters89f507f2006-12-13 04:49:30 +00001348 def testTanh(self):
1349 self.assertRaises(TypeError, math.tanh)
1350 self.ftest('tanh(0)', math.tanh(0), 0)
Mark Dickinson96f774d2016-09-03 19:30:22 +01001351 self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0,
1352 abs_tol=ulp(1))
Christian Heimes53876d92008-04-19 00:31:39 +00001353 self.ftest('tanh(inf)', math.tanh(INF), 1)
1354 self.ftest('tanh(-inf)', math.tanh(NINF), -1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001355 self.assertTrue(math.isnan(math.tanh(NAN)))
Victor Stinnerbe3da382010-11-07 14:14:27 +00001356
1357 @requires_IEEE_754
Victor Stinnerbe3da382010-11-07 14:14:27 +00001358 def testTanhSign(self):
Christian Heimese57950f2008-04-21 13:08:03 +00001359 # check that tanh(-0.) == -0. on IEEE 754 systems
Victor Stinnerbe3da382010-11-07 14:14:27 +00001360 self.assertEqual(math.tanh(-0.), -0.)
1361 self.assertEqual(math.copysign(1., math.tanh(-0.)),
1362 math.copysign(1., -0.))
Tim Peters1d120612000-10-12 06:10:25 +00001363
Christian Heimes400adb02008-02-01 08:12:03 +00001364 def test_trunc(self):
1365 self.assertEqual(math.trunc(1), 1)
1366 self.assertEqual(math.trunc(-1), -1)
1367 self.assertEqual(type(math.trunc(1)), int)
1368 self.assertEqual(type(math.trunc(1.5)), int)
1369 self.assertEqual(math.trunc(1.5), 1)
1370 self.assertEqual(math.trunc(-1.5), -1)
1371 self.assertEqual(math.trunc(1.999999), 1)
1372 self.assertEqual(math.trunc(-1.999999), -1)
1373 self.assertEqual(math.trunc(-0.999999), -0)
1374 self.assertEqual(math.trunc(-100.999), -100)
1375
1376 class TestTrunc(object):
1377 def __trunc__(self):
1378 return 23
1379
1380 class TestNoTrunc(object):
1381 pass
1382
1383 self.assertEqual(math.trunc(TestTrunc()), 23)
1384
1385 self.assertRaises(TypeError, math.trunc)
1386 self.assertRaises(TypeError, math.trunc, 1, 2)
1387 self.assertRaises(TypeError, math.trunc, TestNoTrunc())
1388
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001389 def testIsfinite(self):
1390 self.assertTrue(math.isfinite(0.0))
1391 self.assertTrue(math.isfinite(-0.0))
1392 self.assertTrue(math.isfinite(1.0))
1393 self.assertTrue(math.isfinite(-1.0))
1394 self.assertFalse(math.isfinite(float("nan")))
1395 self.assertFalse(math.isfinite(float("inf")))
1396 self.assertFalse(math.isfinite(float("-inf")))
1397
Christian Heimes072c0f12008-01-03 23:01:04 +00001398 def testIsnan(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001399 self.assertTrue(math.isnan(float("nan")))
Mark Dickinson31ba1c32016-09-04 12:29:14 +01001400 self.assertTrue(math.isnan(float("-nan")))
1401 self.assertTrue(math.isnan(float("inf") * 0.))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001402 self.assertFalse(math.isnan(float("inf")))
1403 self.assertFalse(math.isnan(0.))
1404 self.assertFalse(math.isnan(1.))
Christian Heimes072c0f12008-01-03 23:01:04 +00001405
1406 def testIsinf(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001407 self.assertTrue(math.isinf(float("inf")))
1408 self.assertTrue(math.isinf(float("-inf")))
1409 self.assertTrue(math.isinf(1E400))
1410 self.assertTrue(math.isinf(-1E400))
1411 self.assertFalse(math.isinf(float("nan")))
1412 self.assertFalse(math.isinf(0.))
1413 self.assertFalse(math.isinf(1.))
Christian Heimes072c0f12008-01-03 23:01:04 +00001414
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00001415 @requires_IEEE_754
1416 def test_nan_constant(self):
1417 self.assertTrue(math.isnan(math.nan))
1418
1419 @requires_IEEE_754
1420 def test_inf_constant(self):
1421 self.assertTrue(math.isinf(math.inf))
1422 self.assertGreater(math.inf, 0.0)
1423 self.assertEqual(math.inf, float("inf"))
1424 self.assertEqual(-math.inf, float("-inf"))
1425
Thomas Wouters89f507f2006-12-13 04:49:30 +00001426 # RED_FLAG 16-Oct-2000 Tim
1427 # While 2.0 is more consistent about exceptions than previous releases, it
1428 # still fails this part of the test on some platforms. For now, we only
1429 # *run* test_exceptions() in verbose mode, so that this isn't normally
1430 # tested.
Serhiy Storchaka43767632013-11-03 21:31:38 +02001431 @unittest.skipUnless(verbose, 'requires verbose mode')
1432 def test_exceptions(self):
1433 try:
1434 x = math.exp(-1000000000)
1435 except:
1436 # mathmodule.c is failing to weed out underflows from libm, or
1437 # we've got an fp format with huge dynamic range
1438 self.fail("underflowing exp() should not have raised "
1439 "an exception")
1440 if x != 0:
1441 self.fail("underflowing exp() should have returned 0")
Tim Peters98c81842000-10-16 17:35:13 +00001442
Serhiy Storchaka43767632013-11-03 21:31:38 +02001443 # If this fails, probably using a strict IEEE-754 conforming libm, and x
1444 # is +Inf afterwards. But Python wants overflows detected by default.
1445 try:
1446 x = math.exp(1000000000)
1447 except OverflowError:
1448 pass
1449 else:
1450 self.fail("overflowing exp() didn't trigger OverflowError")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001451
Serhiy Storchaka43767632013-11-03 21:31:38 +02001452 # If this fails, it could be a puzzle. One odd possibility is that
1453 # mathmodule.c's macros are getting confused while comparing
1454 # Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE
1455 # as a result (and so raising OverflowError instead).
1456 try:
1457 x = math.sqrt(-1.0)
1458 except ValueError:
1459 pass
1460 else:
1461 self.fail("sqrt(-1) didn't raise ValueError")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001462
Mark Dickinson63566232009-09-18 21:04:19 +00001463 @requires_IEEE_754
Christian Heimes53876d92008-04-19 00:31:39 +00001464 def test_testfile(self):
Mark Dickinson85746542016-09-04 09:58:51 +01001465 # Some tests need to be skipped on ancient OS X versions.
1466 # See issue #27953.
1467 SKIP_ON_TIGER = {'tan0064'}
1468
1469 osx_version = None
1470 if sys.platform == 'darwin':
1471 version_txt = platform.mac_ver()[0]
1472 try:
1473 osx_version = tuple(map(int, version_txt.split('.')))
1474 except ValueError:
1475 pass
1476
Mark Dickinson96f774d2016-09-03 19:30:22 +01001477 fail_fmt = "{}: {}({!r}): {}"
1478
1479 failures = []
Christian Heimes53876d92008-04-19 00:31:39 +00001480 for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file):
Mark Dickinson96f774d2016-09-03 19:30:22 +01001481 # Skip if either the input or result is complex
1482 if ai != 0.0 or ei != 0.0:
Christian Heimes53876d92008-04-19 00:31:39 +00001483 continue
1484 if fn in ['rect', 'polar']:
1485 # no real versions of rect, polar
1486 continue
Mark Dickinson85746542016-09-04 09:58:51 +01001487 # Skip certain tests on OS X 10.4.
1488 if osx_version is not None and osx_version < (10, 5):
1489 if id in SKIP_ON_TIGER:
1490 continue
Mark Dickinson96f774d2016-09-03 19:30:22 +01001491
Christian Heimes53876d92008-04-19 00:31:39 +00001492 func = getattr(math, fn)
Mark Dickinson96f774d2016-09-03 19:30:22 +01001493
1494 if 'invalid' in flags or 'divide-by-zero' in flags:
1495 er = 'ValueError'
1496 elif 'overflow' in flags:
1497 er = 'OverflowError'
1498
Christian Heimesa342c012008-04-20 21:01:16 +00001499 try:
1500 result = func(ar)
Mark Dickinson96f774d2016-09-03 19:30:22 +01001501 except ValueError:
1502 result = 'ValueError'
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001503 except OverflowError:
Mark Dickinson96f774d2016-09-03 19:30:22 +01001504 result = 'OverflowError'
1505
1506 # Default tolerances
1507 ulp_tol, abs_tol = 5, 0.0
1508
1509 failure = result_check(er, result, ulp_tol, abs_tol)
1510 if failure is None:
1511 continue
1512
1513 msg = fail_fmt.format(id, fn, ar, failure)
1514 failures.append(msg)
1515
1516 if failures:
1517 self.fail('Failures in test_testfile:\n ' +
1518 '\n '.join(failures))
Thomas Wouters89f507f2006-12-13 04:49:30 +00001519
Victor Stinnerbe3da382010-11-07 14:14:27 +00001520 @requires_IEEE_754
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001521 def test_mtestfile(self):
Mark Dickinson96f774d2016-09-03 19:30:22 +01001522 fail_fmt = "{}: {}({!r}): {}"
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001523
1524 failures = []
1525 for id, fn, arg, expected, flags in parse_mtestfile(math_testcases):
1526 func = getattr(math, fn)
1527
1528 if 'invalid' in flags or 'divide-by-zero' in flags:
1529 expected = 'ValueError'
1530 elif 'overflow' in flags:
1531 expected = 'OverflowError'
1532
1533 try:
1534 got = func(arg)
1535 except ValueError:
1536 got = 'ValueError'
1537 except OverflowError:
1538 got = 'OverflowError'
1539
Mark Dickinson96f774d2016-09-03 19:30:22 +01001540 # Default tolerances
1541 ulp_tol, abs_tol = 5, 0.0
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +00001542
Mark Dickinson96f774d2016-09-03 19:30:22 +01001543 # Exceptions to the defaults
1544 if fn == 'gamma':
1545 # Experimental results on one platform gave
1546 # an accuracy of <= 10 ulps across the entire float
1547 # domain. We weaken that to require 20 ulp accuracy.
1548 ulp_tol = 20
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001549
Mark Dickinson96f774d2016-09-03 19:30:22 +01001550 elif fn == 'lgamma':
1551 # we use a weaker accuracy test for lgamma;
1552 # lgamma only achieves an absolute error of
1553 # a few multiples of the machine accuracy, in
1554 # general.
1555 abs_tol = 1e-15
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001556
Mark Dickinson96f774d2016-09-03 19:30:22 +01001557 elif fn == 'erfc' and arg >= 0.0:
1558 # erfc has less-than-ideal accuracy for large
1559 # arguments (x ~ 25 or so), mainly due to the
1560 # error involved in computing exp(-x*x).
1561 #
1562 # Observed between CPython and mpmath at 25 dp:
1563 # x < 0 : err <= 2 ulp
1564 # 0 <= x < 1 : err <= 10 ulp
1565 # 1 <= x < 10 : err <= 100 ulp
1566 # 10 <= x < 20 : err <= 300 ulp
1567 # 20 <= x : < 600 ulp
1568 #
1569 if arg < 1.0:
1570 ulp_tol = 10
1571 elif arg < 10.0:
1572 ulp_tol = 100
1573 else:
1574 ulp_tol = 1000
1575
1576 failure = result_check(expected, got, ulp_tol, abs_tol)
1577 if failure is None:
1578 continue
1579
1580 msg = fail_fmt.format(id, fn, arg, failure)
1581 failures.append(msg)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001582
1583 if failures:
1584 self.fail('Failures in test_mtestfile:\n ' +
1585 '\n '.join(failures))
1586
Mark Dickinsona0ce3752017-04-05 18:34:27 +01001587 # Custom assertions.
1588
1589 def assertIsNaN(self, value):
1590 if not math.isnan(value):
1591 self.fail("Expected a NaN, got {!r}.".format(value))
1592
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001593
Tal Einatd5519ed2015-05-31 22:05:00 +03001594class IsCloseTests(unittest.TestCase):
Mike53f7a7c2017-12-14 14:04:53 +03001595 isclose = math.isclose # subclasses should override this
Tal Einatd5519ed2015-05-31 22:05:00 +03001596
1597 def assertIsClose(self, a, b, *args, **kwargs):
1598 self.assertTrue(self.isclose(a, b, *args, **kwargs),
1599 msg="%s and %s should be close!" % (a, b))
1600
1601 def assertIsNotClose(self, a, b, *args, **kwargs):
1602 self.assertFalse(self.isclose(a, b, *args, **kwargs),
1603 msg="%s and %s should not be close!" % (a, b))
1604
1605 def assertAllClose(self, examples, *args, **kwargs):
1606 for a, b in examples:
1607 self.assertIsClose(a, b, *args, **kwargs)
1608
1609 def assertAllNotClose(self, examples, *args, **kwargs):
1610 for a, b in examples:
1611 self.assertIsNotClose(a, b, *args, **kwargs)
1612
1613 def test_negative_tolerances(self):
1614 # ValueError should be raised if either tolerance is less than zero
1615 with self.assertRaises(ValueError):
1616 self.assertIsClose(1, 1, rel_tol=-1e-100)
1617 with self.assertRaises(ValueError):
1618 self.assertIsClose(1, 1, rel_tol=1e-100, abs_tol=-1e10)
1619
1620 def test_identical(self):
1621 # identical values must test as close
1622 identical_examples = [(2.0, 2.0),
1623 (0.1e200, 0.1e200),
1624 (1.123e-300, 1.123e-300),
1625 (12345, 12345.0),
1626 (0.0, -0.0),
1627 (345678, 345678)]
1628 self.assertAllClose(identical_examples, rel_tol=0.0, abs_tol=0.0)
1629
1630 def test_eight_decimal_places(self):
1631 # examples that are close to 1e-8, but not 1e-9
1632 eight_decimal_places_examples = [(1e8, 1e8 + 1),
1633 (-1e-8, -1.000000009e-8),
1634 (1.12345678, 1.12345679)]
1635 self.assertAllClose(eight_decimal_places_examples, rel_tol=1e-8)
1636 self.assertAllNotClose(eight_decimal_places_examples, rel_tol=1e-9)
1637
1638 def test_near_zero(self):
1639 # values close to zero
1640 near_zero_examples = [(1e-9, 0.0),
1641 (-1e-9, 0.0),
1642 (-1e-150, 0.0)]
1643 # these should not be close to any rel_tol
1644 self.assertAllNotClose(near_zero_examples, rel_tol=0.9)
1645 # these should be close to abs_tol=1e-8
1646 self.assertAllClose(near_zero_examples, abs_tol=1e-8)
1647
1648 def test_identical_infinite(self):
1649 # these are close regardless of tolerance -- i.e. they are equal
1650 self.assertIsClose(INF, INF)
1651 self.assertIsClose(INF, INF, abs_tol=0.0)
1652 self.assertIsClose(NINF, NINF)
1653 self.assertIsClose(NINF, NINF, abs_tol=0.0)
1654
1655 def test_inf_ninf_nan(self):
1656 # these should never be close (following IEEE 754 rules for equality)
1657 not_close_examples = [(NAN, NAN),
1658 (NAN, 1e-100),
1659 (1e-100, NAN),
1660 (INF, NAN),
1661 (NAN, INF),
1662 (INF, NINF),
1663 (INF, 1.0),
1664 (1.0, INF),
1665 (INF, 1e308),
1666 (1e308, INF)]
1667 # use largest reasonable tolerance
1668 self.assertAllNotClose(not_close_examples, abs_tol=0.999999999999999)
1669
1670 def test_zero_tolerance(self):
1671 # test with zero tolerance
1672 zero_tolerance_close_examples = [(1.0, 1.0),
1673 (-3.4, -3.4),
1674 (-1e-300, -1e-300)]
1675 self.assertAllClose(zero_tolerance_close_examples, rel_tol=0.0)
1676
1677 zero_tolerance_not_close_examples = [(1.0, 1.000000000000001),
1678 (0.99999999999999, 1.0),
1679 (1.0e200, .999999999999999e200)]
1680 self.assertAllNotClose(zero_tolerance_not_close_examples, rel_tol=0.0)
1681
Martin Pantereb995702016-07-28 01:11:04 +00001682 def test_asymmetry(self):
1683 # test the asymmetry example from PEP 485
Tal Einatd5519ed2015-05-31 22:05:00 +03001684 self.assertAllClose([(9, 10), (10, 9)], rel_tol=0.1)
1685
1686 def test_integers(self):
1687 # test with integer values
1688 integer_examples = [(100000001, 100000000),
1689 (123456789, 123456788)]
1690
1691 self.assertAllClose(integer_examples, rel_tol=1e-8)
1692 self.assertAllNotClose(integer_examples, rel_tol=1e-9)
1693
1694 def test_decimals(self):
1695 # test with Decimal values
1696 from decimal import Decimal
1697
1698 decimal_examples = [(Decimal('1.00000001'), Decimal('1.0')),
1699 (Decimal('1.00000001e-20'), Decimal('1.0e-20')),
Mark Dickinson31ba1c32016-09-04 12:29:14 +01001700 (Decimal('1.00000001e-100'), Decimal('1.0e-100')),
1701 (Decimal('1.00000001e20'), Decimal('1.0e20'))]
Tal Einatd5519ed2015-05-31 22:05:00 +03001702 self.assertAllClose(decimal_examples, rel_tol=1e-8)
1703 self.assertAllNotClose(decimal_examples, rel_tol=1e-9)
1704
1705 def test_fractions(self):
1706 # test with Fraction values
1707 from fractions import Fraction
1708
Mark Dickinson31ba1c32016-09-04 12:29:14 +01001709 fraction_examples = [
1710 (Fraction(1, 100000000) + 1, Fraction(1)),
1711 (Fraction(100000001), Fraction(100000000)),
1712 (Fraction(10**8 + 1, 10**28), Fraction(1, 10**20))]
Tal Einatd5519ed2015-05-31 22:05:00 +03001713 self.assertAllClose(fraction_examples, rel_tol=1e-8)
1714 self.assertAllNotClose(fraction_examples, rel_tol=1e-9)
1715
1716
Thomas Wouters89f507f2006-12-13 04:49:30 +00001717def test_main():
Christian Heimes53876d92008-04-19 00:31:39 +00001718 from doctest import DocFileSuite
1719 suite = unittest.TestSuite()
1720 suite.addTest(unittest.makeSuite(MathTests))
Tal Einatd5519ed2015-05-31 22:05:00 +03001721 suite.addTest(unittest.makeSuite(IsCloseTests))
Christian Heimes53876d92008-04-19 00:31:39 +00001722 suite.addTest(DocFileSuite("ieee754.txt"))
1723 run_unittest(suite)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001724
1725if __name__ == '__main__':
1726 test_main()