blob: cb05dee0e0fd3c1949aff02846a0c29bc558bf0a [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)
Raymond Hettinger808180c2019-01-28 13:59:56 -0800769 int_too_big_for_float = 10 ** (sys.float_info.max_10_exp + 5)
770 with self.assertRaises((ValueError, OverflowError)):
771 hypot(1, int_too_big_for_float)
Raymond Hettingerc6dabe32018-07-28 07:48:04 -0700772
773 # Any infinity gives positive infinity.
774 self.assertEqual(hypot(INF), INF)
775 self.assertEqual(hypot(0, INF), INF)
776 self.assertEqual(hypot(10, INF), INF)
777 self.assertEqual(hypot(-10, INF), INF)
778 self.assertEqual(hypot(NAN, INF), INF)
779 self.assertEqual(hypot(INF, NAN), INF)
780 self.assertEqual(hypot(NINF, NAN), INF)
781 self.assertEqual(hypot(NAN, NINF), INF)
782 self.assertEqual(hypot(-INF, INF), INF)
783 self.assertEqual(hypot(-INF, -INF), INF)
784 self.assertEqual(hypot(10, -INF), INF)
785
Raymond Hettinger00414592018-08-12 12:15:23 -0700786 # If no infinity, any NaN gives a NaN.
Raymond Hettingerc6dabe32018-07-28 07:48:04 -0700787 self.assertTrue(math.isnan(hypot(NAN)))
788 self.assertTrue(math.isnan(hypot(0, NAN)))
789 self.assertTrue(math.isnan(hypot(NAN, 10)))
790 self.assertTrue(math.isnan(hypot(10, NAN)))
791 self.assertTrue(math.isnan(hypot(NAN, NAN)))
792 self.assertTrue(math.isnan(hypot(NAN)))
793
794 # Verify scaling for extremely large values
795 fourthmax = FLOAT_MAX / 4.0
796 for n in range(32):
797 self.assertEqual(hypot(*([fourthmax]*n)), fourthmax * math.sqrt(n))
798
799 # Verify scaling for extremely small values
800 for exp in range(32):
801 scale = FLOAT_MIN / 2.0 ** exp
802 self.assertEqual(math.hypot(4*scale, 3*scale), 5*scale)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000803
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700804 def testDist(self):
805 from decimal import Decimal as D
806 from fractions import Fraction as F
807
808 dist = math.dist
809 sqrt = math.sqrt
810
Raymond Hettinger808180c2019-01-28 13:59:56 -0800811 # Simple exact cases
812 self.assertEqual(dist((1.0, 2.0, 3.0), (4.0, 2.0, -1.0)), 5.0)
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700813 self.assertEqual(dist((1, 2, 3), (4, 2, -1)), 5.0)
814
815 # Test different numbers of arguments (from zero to nine)
816 # against a straightforward pure python implementation
817 for i in range(9):
818 for j in range(5):
819 p = tuple(random.uniform(-5, 5) for k in range(i))
820 q = tuple(random.uniform(-5, 5) for k in range(i))
821 self.assertAlmostEqual(
822 dist(p, q),
823 sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
824 )
825
826 # Test allowable types (those with __float__)
827 self.assertEqual(dist((14.0, 1.0), (2.0, -4.0)), 13.0)
828 self.assertEqual(dist((14, 1), (2, -4)), 13)
829 self.assertEqual(dist((D(14), D(1)), (D(2), D(-4))), D(13))
830 self.assertEqual(dist((F(14, 32), F(1, 32)), (F(2, 32), F(-4, 32))),
831 F(13, 32))
832 self.assertEqual(dist((True, True, False, True, False),
833 (True, False, True, True, False)),
834 sqrt(2.0))
835
836 # Test corner cases
837 self.assertEqual(dist((13.25, 12.5, -3.25),
838 (13.25, 12.5, -3.25)),
839 0.0) # Distance with self is zero
840 self.assertEqual(dist((), ()), 0.0) # Zero-dimensional case
841 self.assertEqual(1.0, # Convert negative zero to positive zero
842 math.copysign(1.0, dist((-0.0,), (0.0,)))
843 )
844 self.assertEqual(1.0, # Convert negative zero to positive zero
845 math.copysign(1.0, dist((0.0,), (-0.0,)))
846 )
Raymond Hettinger00414592018-08-12 12:15:23 -0700847 self.assertEqual( # Handling of moving max to the end
848 dist((1.5, 1.5, 0.5), (0, 0, 0)),
849 dist((1.5, 0.5, 1.5), (0, 0, 0))
850 )
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700851
852 # Verify tuple subclasses are allowed
Raymond Hettinger00414592018-08-12 12:15:23 -0700853 class T(tuple):
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700854 pass
855 self.assertEqual(dist(T((1, 2, 3)), ((4, 2, -1))), 5.0)
856
857 # Test handling of bad arguments
858 with self.assertRaises(TypeError): # Reject keyword args
859 dist(p=(1, 2, 3), q=(4, 5, 6))
860 with self.assertRaises(TypeError): # Too few args
861 dist((1, 2, 3))
862 with self.assertRaises(TypeError): # Too many args
863 dist((1, 2, 3), (4, 5, 6), (7, 8, 9))
864 with self.assertRaises(TypeError): # Scalars not allowed
865 dist(1, 2)
866 with self.assertRaises(TypeError): # Lists not allowed
867 dist([1, 2, 3], [4, 5, 6])
868 with self.assertRaises(TypeError): # Reject values without __float__
869 dist((1.1, 'string', 2.2), (1, 2, 3))
870 with self.assertRaises(ValueError): # Check dimension agree
871 dist((1, 2, 3, 4), (5, 6, 7))
872 with self.assertRaises(ValueError): # Check dimension agree
873 dist((1, 2, 3), (4, 5, 6, 7))
Ammar Askarcb08a712019-01-12 01:23:41 -0500874 with self.assertRaises(TypeError): # Rejects invalid types
875 dist("abc", "xyz")
Raymond Hettinger808180c2019-01-28 13:59:56 -0800876 int_too_big_for_float = 10 ** (sys.float_info.max_10_exp + 5)
877 with self.assertRaises((ValueError, OverflowError)):
878 dist((1, int_too_big_for_float), (2, 3))
879 with self.assertRaises((ValueError, OverflowError)):
880 dist((2, 3), (1, int_too_big_for_float))
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700881
Raymond Hettinger00414592018-08-12 12:15:23 -0700882 # Verify that the one dimensional case is equivalent to abs()
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700883 for i in range(20):
884 p, q = random.random(), random.random()
885 self.assertEqual(dist((p,), (q,)), abs(p - q))
886
887 # Test special values
888 values = [NINF, -10.5, -0.0, 0.0, 10.5, INF, NAN]
889 for p in itertools.product(values, repeat=3):
890 for q in itertools.product(values, repeat=3):
891 diffs = [px - qx for px, qx in zip(p, q)]
892 if any(map(math.isinf, diffs)):
893 # Any infinite difference gives positive infinity.
894 self.assertEqual(dist(p, q), INF)
895 elif any(map(math.isnan, diffs)):
Raymond Hettinger00414592018-08-12 12:15:23 -0700896 # If no infinity, any NaN gives a NaN.
Raymond Hettinger9c18b1a2018-07-31 00:45:49 -0700897 self.assertTrue(math.isnan(dist(p, q)))
898
899 # Verify scaling for extremely large values
900 fourthmax = FLOAT_MAX / 4.0
901 for n in range(32):
902 p = (fourthmax,) * n
903 q = (0.0,) * n
904 self.assertEqual(dist(p, q), fourthmax * math.sqrt(n))
905 self.assertEqual(dist(q, p), fourthmax * math.sqrt(n))
906
907 # Verify scaling for extremely small values
908 for exp in range(32):
909 scale = FLOAT_MIN / 2.0 ** exp
910 p = (4*scale, 3*scale)
911 q = (0.0, 0.0)
912 self.assertEqual(math.dist(p, q), 5*scale)
913 self.assertEqual(math.dist(q, p), 5*scale)
914
915
Thomas Wouters89f507f2006-12-13 04:49:30 +0000916 def testLdexp(self):
917 self.assertRaises(TypeError, math.ldexp)
918 self.ftest('ldexp(0,1)', math.ldexp(0,1), 0)
919 self.ftest('ldexp(1,1)', math.ldexp(1,1), 2)
920 self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5)
921 self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2)
Christian Heimes53876d92008-04-19 00:31:39 +0000922 self.assertRaises(OverflowError, math.ldexp, 1., 1000000)
923 self.assertRaises(OverflowError, math.ldexp, -1., 1000000)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000924 self.assertEqual(math.ldexp(1., -1000000), 0.)
925 self.assertEqual(math.ldexp(-1., -1000000), -0.)
926 self.assertEqual(math.ldexp(INF, 30), INF)
927 self.assertEqual(math.ldexp(NINF, -213), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000928 self.assertTrue(math.isnan(math.ldexp(NAN, 0)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000929
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000930 # large second argument
931 for n in [10**5, 10**10, 10**20, 10**40]:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000932 self.assertEqual(math.ldexp(INF, -n), INF)
933 self.assertEqual(math.ldexp(NINF, -n), NINF)
934 self.assertEqual(math.ldexp(1., -n), 0.)
935 self.assertEqual(math.ldexp(-1., -n), -0.)
936 self.assertEqual(math.ldexp(0., -n), 0.)
937 self.assertEqual(math.ldexp(-0., -n), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000938 self.assertTrue(math.isnan(math.ldexp(NAN, -n)))
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000939
940 self.assertRaises(OverflowError, math.ldexp, 1., n)
941 self.assertRaises(OverflowError, math.ldexp, -1., n)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000942 self.assertEqual(math.ldexp(0., n), 0.)
943 self.assertEqual(math.ldexp(-0., n), -0.)
944 self.assertEqual(math.ldexp(INF, n), INF)
945 self.assertEqual(math.ldexp(NINF, n), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000946 self.assertTrue(math.isnan(math.ldexp(NAN, n)))
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000947
Thomas Wouters89f507f2006-12-13 04:49:30 +0000948 def testLog(self):
949 self.assertRaises(TypeError, math.log)
950 self.ftest('log(1/e)', math.log(1/math.e), -1)
951 self.ftest('log(1)', math.log(1), 0)
952 self.ftest('log(e)', math.log(math.e), 1)
953 self.ftest('log(32,2)', math.log(32,2), 5)
954 self.ftest('log(10**40, 10)', math.log(10**40, 10), 40)
955 self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2)
Mark Dickinsonc6037172010-09-29 19:06:36 +0000956 self.ftest('log(10**1000)', math.log(10**1000),
957 2302.5850929940457)
958 self.assertRaises(ValueError, math.log, -1.5)
959 self.assertRaises(ValueError, math.log, -10**1000)
Christian Heimes53876d92008-04-19 00:31:39 +0000960 self.assertRaises(ValueError, math.log, NINF)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000961 self.assertEqual(math.log(INF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000962 self.assertTrue(math.isnan(math.log(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000963
964 def testLog1p(self):
965 self.assertRaises(TypeError, math.log1p)
Mark Dickinson31ba1c32016-09-04 12:29:14 +0100966 for n in [2, 2**90, 2**300]:
967 self.assertAlmostEqual(math.log1p(n), math.log1p(float(n)))
968 self.assertRaises(ValueError, math.log1p, -1)
969 self.assertEqual(math.log1p(INF), INF)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000970
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200971 @requires_IEEE_754
972 def testLog2(self):
973 self.assertRaises(TypeError, math.log2)
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200974
975 # Check some integer values
976 self.assertEqual(math.log2(1), 0.0)
977 self.assertEqual(math.log2(2), 1.0)
978 self.assertEqual(math.log2(4), 2.0)
979
980 # Large integer values
981 self.assertEqual(math.log2(2**1023), 1023.0)
982 self.assertEqual(math.log2(2**1024), 1024.0)
983 self.assertEqual(math.log2(2**2000), 2000.0)
984
985 self.assertRaises(ValueError, math.log2, -1.5)
986 self.assertRaises(ValueError, math.log2, NINF)
987 self.assertTrue(math.isnan(math.log2(NAN)))
988
Victor Stinnercd9dd372011-05-10 23:40:17 +0200989 @requires_IEEE_754
Victor Stinnerebbbdaf2011-06-01 13:19:07 +0200990 # log2() is not accurate enough on Mac OS X Tiger (10.4)
991 @support.requires_mac_ver(10, 5)
Victor Stinnercd9dd372011-05-10 23:40:17 +0200992 def testLog2Exact(self):
993 # Check that we get exact equality for log2 of powers of 2.
994 actual = [math.log2(math.ldexp(1.0, n)) for n in range(-1074, 1024)]
995 expected = [float(n) for n in range(-1074, 1024)]
996 self.assertEqual(actual, expected)
997
Thomas Wouters89f507f2006-12-13 04:49:30 +0000998 def testLog10(self):
999 self.assertRaises(TypeError, math.log10)
1000 self.ftest('log10(0.1)', math.log10(0.1), -1)
1001 self.ftest('log10(1)', math.log10(1), 0)
1002 self.ftest('log10(10)', math.log10(10), 1)
Mark Dickinsonc6037172010-09-29 19:06:36 +00001003 self.ftest('log10(10**1000)', math.log10(10**1000), 1000.0)
1004 self.assertRaises(ValueError, math.log10, -1.5)
1005 self.assertRaises(ValueError, math.log10, -10**1000)
Christian Heimes53876d92008-04-19 00:31:39 +00001006 self.assertRaises(ValueError, math.log10, NINF)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001007 self.assertEqual(math.log(INF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001008 self.assertTrue(math.isnan(math.log10(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +00001009
Thomas Wouters89f507f2006-12-13 04:49:30 +00001010 def testModf(self):
1011 self.assertRaises(TypeError, math.modf)
Guido van Rossumfcce6301996-08-08 18:26:25 +00001012
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001013 def testmodf(name, result, expected):
1014 (v1, v2), (e1, e2) = result, expected
Thomas Wouters89f507f2006-12-13 04:49:30 +00001015 if abs(v1-e1) > eps or abs(v2-e2):
1016 self.fail('%s returned %r, expected %r'%\
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001017 (name, result, expected))
Raymond Hettinger64108af2002-05-13 03:55:01 +00001018
Thomas Wouters89f507f2006-12-13 04:49:30 +00001019 testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
1020 testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
Guido van Rossumfcce6301996-08-08 18:26:25 +00001021
Ezio Melottib3aedd42010-11-20 19:04:17 +00001022 self.assertEqual(math.modf(INF), (0.0, INF))
1023 self.assertEqual(math.modf(NINF), (-0.0, NINF))
Christian Heimes53876d92008-04-19 00:31:39 +00001024
1025 modf_nan = math.modf(NAN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001026 self.assertTrue(math.isnan(modf_nan[0]))
1027 self.assertTrue(math.isnan(modf_nan[1]))
Christian Heimes53876d92008-04-19 00:31:39 +00001028
Thomas Wouters89f507f2006-12-13 04:49:30 +00001029 def testPow(self):
1030 self.assertRaises(TypeError, math.pow)
1031 self.ftest('pow(0,1)', math.pow(0,1), 0)
1032 self.ftest('pow(1,0)', math.pow(1,0), 1)
1033 self.ftest('pow(2,1)', math.pow(2,1), 2)
1034 self.ftest('pow(2,-1)', math.pow(2,-1), 0.5)
Christian Heimes53876d92008-04-19 00:31:39 +00001035 self.assertEqual(math.pow(INF, 1), INF)
1036 self.assertEqual(math.pow(NINF, 1), NINF)
1037 self.assertEqual((math.pow(1, INF)), 1.)
1038 self.assertEqual((math.pow(1, NINF)), 1.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001039 self.assertTrue(math.isnan(math.pow(NAN, 1)))
1040 self.assertTrue(math.isnan(math.pow(2, NAN)))
1041 self.assertTrue(math.isnan(math.pow(0, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +00001042 self.assertEqual(math.pow(1, NAN), 1)
Christian Heimesa342c012008-04-20 21:01:16 +00001043
1044 # pow(0., x)
1045 self.assertEqual(math.pow(0., INF), 0.)
1046 self.assertEqual(math.pow(0., 3.), 0.)
1047 self.assertEqual(math.pow(0., 2.3), 0.)
1048 self.assertEqual(math.pow(0., 2.), 0.)
1049 self.assertEqual(math.pow(0., 0.), 1.)
1050 self.assertEqual(math.pow(0., -0.), 1.)
1051 self.assertRaises(ValueError, math.pow, 0., -2.)
1052 self.assertRaises(ValueError, math.pow, 0., -2.3)
1053 self.assertRaises(ValueError, math.pow, 0., -3.)
1054 self.assertRaises(ValueError, math.pow, 0., NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001055 self.assertTrue(math.isnan(math.pow(0., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +00001056
1057 # pow(INF, x)
1058 self.assertEqual(math.pow(INF, INF), INF)
1059 self.assertEqual(math.pow(INF, 3.), INF)
1060 self.assertEqual(math.pow(INF, 2.3), INF)
1061 self.assertEqual(math.pow(INF, 2.), INF)
1062 self.assertEqual(math.pow(INF, 0.), 1.)
1063 self.assertEqual(math.pow(INF, -0.), 1.)
1064 self.assertEqual(math.pow(INF, -2.), 0.)
1065 self.assertEqual(math.pow(INF, -2.3), 0.)
1066 self.assertEqual(math.pow(INF, -3.), 0.)
1067 self.assertEqual(math.pow(INF, NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001068 self.assertTrue(math.isnan(math.pow(INF, NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +00001069
1070 # pow(-0., x)
1071 self.assertEqual(math.pow(-0., INF), 0.)
1072 self.assertEqual(math.pow(-0., 3.), -0.)
1073 self.assertEqual(math.pow(-0., 2.3), 0.)
1074 self.assertEqual(math.pow(-0., 2.), 0.)
1075 self.assertEqual(math.pow(-0., 0.), 1.)
1076 self.assertEqual(math.pow(-0., -0.), 1.)
1077 self.assertRaises(ValueError, math.pow, -0., -2.)
1078 self.assertRaises(ValueError, math.pow, -0., -2.3)
1079 self.assertRaises(ValueError, math.pow, -0., -3.)
1080 self.assertRaises(ValueError, math.pow, -0., NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001081 self.assertTrue(math.isnan(math.pow(-0., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +00001082
1083 # pow(NINF, x)
1084 self.assertEqual(math.pow(NINF, INF), INF)
1085 self.assertEqual(math.pow(NINF, 3.), NINF)
1086 self.assertEqual(math.pow(NINF, 2.3), INF)
1087 self.assertEqual(math.pow(NINF, 2.), INF)
1088 self.assertEqual(math.pow(NINF, 0.), 1.)
1089 self.assertEqual(math.pow(NINF, -0.), 1.)
1090 self.assertEqual(math.pow(NINF, -2.), 0.)
1091 self.assertEqual(math.pow(NINF, -2.3), 0.)
1092 self.assertEqual(math.pow(NINF, -3.), -0.)
1093 self.assertEqual(math.pow(NINF, NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001094 self.assertTrue(math.isnan(math.pow(NINF, NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +00001095
1096 # pow(-1, x)
1097 self.assertEqual(math.pow(-1., INF), 1.)
1098 self.assertEqual(math.pow(-1., 3.), -1.)
1099 self.assertRaises(ValueError, math.pow, -1., 2.3)
1100 self.assertEqual(math.pow(-1., 2.), 1.)
1101 self.assertEqual(math.pow(-1., 0.), 1.)
1102 self.assertEqual(math.pow(-1., -0.), 1.)
1103 self.assertEqual(math.pow(-1., -2.), 1.)
1104 self.assertRaises(ValueError, math.pow, -1., -2.3)
1105 self.assertEqual(math.pow(-1., -3.), -1.)
1106 self.assertEqual(math.pow(-1., NINF), 1.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001107 self.assertTrue(math.isnan(math.pow(-1., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +00001108
1109 # pow(1, x)
1110 self.assertEqual(math.pow(1., INF), 1.)
1111 self.assertEqual(math.pow(1., 3.), 1.)
1112 self.assertEqual(math.pow(1., 2.3), 1.)
1113 self.assertEqual(math.pow(1., 2.), 1.)
1114 self.assertEqual(math.pow(1., 0.), 1.)
1115 self.assertEqual(math.pow(1., -0.), 1.)
1116 self.assertEqual(math.pow(1., -2.), 1.)
1117 self.assertEqual(math.pow(1., -2.3), 1.)
1118 self.assertEqual(math.pow(1., -3.), 1.)
1119 self.assertEqual(math.pow(1., NINF), 1.)
1120 self.assertEqual(math.pow(1., NAN), 1.)
1121
1122 # pow(x, 0) should be 1 for any x
1123 self.assertEqual(math.pow(2.3, 0.), 1.)
1124 self.assertEqual(math.pow(-2.3, 0.), 1.)
1125 self.assertEqual(math.pow(NAN, 0.), 1.)
1126 self.assertEqual(math.pow(2.3, -0.), 1.)
1127 self.assertEqual(math.pow(-2.3, -0.), 1.)
1128 self.assertEqual(math.pow(NAN, -0.), 1.)
1129
1130 # pow(x, y) is invalid if x is negative and y is not integral
1131 self.assertRaises(ValueError, math.pow, -1., 2.3)
1132 self.assertRaises(ValueError, math.pow, -15., -3.1)
1133
1134 # pow(x, NINF)
1135 self.assertEqual(math.pow(1.9, NINF), 0.)
1136 self.assertEqual(math.pow(1.1, NINF), 0.)
1137 self.assertEqual(math.pow(0.9, NINF), INF)
1138 self.assertEqual(math.pow(0.1, NINF), INF)
1139 self.assertEqual(math.pow(-0.1, NINF), INF)
1140 self.assertEqual(math.pow(-0.9, NINF), INF)
1141 self.assertEqual(math.pow(-1.1, NINF), 0.)
1142 self.assertEqual(math.pow(-1.9, NINF), 0.)
1143
1144 # pow(x, INF)
1145 self.assertEqual(math.pow(1.9, INF), INF)
1146 self.assertEqual(math.pow(1.1, INF), INF)
1147 self.assertEqual(math.pow(0.9, INF), 0.)
1148 self.assertEqual(math.pow(0.1, INF), 0.)
1149 self.assertEqual(math.pow(-0.1, INF), 0.)
1150 self.assertEqual(math.pow(-0.9, INF), 0.)
1151 self.assertEqual(math.pow(-1.1, INF), INF)
1152 self.assertEqual(math.pow(-1.9, INF), INF)
1153
1154 # pow(x, y) should work for x negative, y an integer
1155 self.ftest('(-2.)**3.', math.pow(-2.0, 3.0), -8.0)
1156 self.ftest('(-2.)**2.', math.pow(-2.0, 2.0), 4.0)
1157 self.ftest('(-2.)**1.', math.pow(-2.0, 1.0), -2.0)
1158 self.ftest('(-2.)**0.', math.pow(-2.0, 0.0), 1.0)
1159 self.ftest('(-2.)**-0.', math.pow(-2.0, -0.0), 1.0)
1160 self.ftest('(-2.)**-1.', math.pow(-2.0, -1.0), -0.5)
1161 self.ftest('(-2.)**-2.', math.pow(-2.0, -2.0), 0.25)
1162 self.ftest('(-2.)**-3.', math.pow(-2.0, -3.0), -0.125)
1163 self.assertRaises(ValueError, math.pow, -2.0, -0.5)
1164 self.assertRaises(ValueError, math.pow, -2.0, 0.5)
1165
1166 # the following tests have been commented out since they don't
1167 # really belong here: the implementation of ** for floats is
Ezio Melotti13925002011-03-16 11:05:33 +02001168 # independent of the implementation of math.pow
Christian Heimesa342c012008-04-20 21:01:16 +00001169 #self.assertEqual(1**NAN, 1)
1170 #self.assertEqual(1**INF, 1)
1171 #self.assertEqual(1**NINF, 1)
1172 #self.assertEqual(1**0, 1)
1173 #self.assertEqual(1.**NAN, 1)
1174 #self.assertEqual(1.**INF, 1)
1175 #self.assertEqual(1.**NINF, 1)
1176 #self.assertEqual(1.**0, 1)
Guido van Rossumfcce6301996-08-08 18:26:25 +00001177
Thomas Wouters89f507f2006-12-13 04:49:30 +00001178 def testRadians(self):
1179 self.assertRaises(TypeError, math.radians)
1180 self.ftest('radians(180)', math.radians(180), math.pi)
1181 self.ftest('radians(90)', math.radians(90), math.pi/2)
1182 self.ftest('radians(-45)', math.radians(-45), -math.pi/4)
Mark Dickinson31ba1c32016-09-04 12:29:14 +01001183 self.ftest('radians(0)', math.radians(0), 0)
Guido van Rossumfcce6301996-08-08 18:26:25 +00001184
Mark Dickinsona0ce3752017-04-05 18:34:27 +01001185 @requires_IEEE_754
1186 def testRemainder(self):
1187 from fractions import Fraction
1188
1189 def validate_spec(x, y, r):
1190 """
1191 Check that r matches remainder(x, y) according to the IEEE 754
1192 specification. Assumes that x, y and r are finite and y is nonzero.
1193 """
1194 fx, fy, fr = Fraction(x), Fraction(y), Fraction(r)
1195 # r should not exceed y/2 in absolute value
1196 self.assertLessEqual(abs(fr), abs(fy/2))
1197 # x - r should be an exact integer multiple of y
1198 n = (fx - fr) / fy
1199 self.assertEqual(n, int(n))
1200 if abs(fr) == abs(fy/2):
1201 # If |r| == |y/2|, n should be even.
1202 self.assertEqual(n/2, int(n/2))
1203
1204 # triples (x, y, remainder(x, y)) in hexadecimal form.
1205 testcases = [
1206 # Remainders modulo 1, showing the ties-to-even behaviour.
1207 '-4.0 1 -0.0',
1208 '-3.8 1 0.8',
1209 '-3.0 1 -0.0',
1210 '-2.8 1 -0.8',
1211 '-2.0 1 -0.0',
1212 '-1.8 1 0.8',
1213 '-1.0 1 -0.0',
1214 '-0.8 1 -0.8',
1215 '-0.0 1 -0.0',
1216 ' 0.0 1 0.0',
1217 ' 0.8 1 0.8',
1218 ' 1.0 1 0.0',
1219 ' 1.8 1 -0.8',
1220 ' 2.0 1 0.0',
1221 ' 2.8 1 0.8',
1222 ' 3.0 1 0.0',
1223 ' 3.8 1 -0.8',
1224 ' 4.0 1 0.0',
1225
1226 # Reductions modulo 2*pi
1227 '0x0.0p+0 0x1.921fb54442d18p+2 0x0.0p+0',
1228 '0x1.921fb54442d18p+0 0x1.921fb54442d18p+2 0x1.921fb54442d18p+0',
1229 '0x1.921fb54442d17p+1 0x1.921fb54442d18p+2 0x1.921fb54442d17p+1',
1230 '0x1.921fb54442d18p+1 0x1.921fb54442d18p+2 0x1.921fb54442d18p+1',
1231 '0x1.921fb54442d19p+1 0x1.921fb54442d18p+2 -0x1.921fb54442d17p+1',
1232 '0x1.921fb54442d17p+2 0x1.921fb54442d18p+2 -0x0.0000000000001p+2',
1233 '0x1.921fb54442d18p+2 0x1.921fb54442d18p+2 0x0p0',
1234 '0x1.921fb54442d19p+2 0x1.921fb54442d18p+2 0x0.0000000000001p+2',
1235 '0x1.2d97c7f3321d1p+3 0x1.921fb54442d18p+2 0x1.921fb54442d14p+1',
1236 '0x1.2d97c7f3321d2p+3 0x1.921fb54442d18p+2 -0x1.921fb54442d18p+1',
1237 '0x1.2d97c7f3321d3p+3 0x1.921fb54442d18p+2 -0x1.921fb54442d14p+1',
1238 '0x1.921fb54442d17p+3 0x1.921fb54442d18p+2 -0x0.0000000000001p+3',
1239 '0x1.921fb54442d18p+3 0x1.921fb54442d18p+2 0x0p0',
1240 '0x1.921fb54442d19p+3 0x1.921fb54442d18p+2 0x0.0000000000001p+3',
1241 '0x1.f6a7a2955385dp+3 0x1.921fb54442d18p+2 0x1.921fb54442d14p+1',
1242 '0x1.f6a7a2955385ep+3 0x1.921fb54442d18p+2 0x1.921fb54442d18p+1',
1243 '0x1.f6a7a2955385fp+3 0x1.921fb54442d18p+2 -0x1.921fb54442d14p+1',
1244 '0x1.1475cc9eedf00p+5 0x1.921fb54442d18p+2 0x1.921fb54442d10p+1',
1245 '0x1.1475cc9eedf01p+5 0x1.921fb54442d18p+2 -0x1.921fb54442d10p+1',
1246
1247 # Symmetry with respect to signs.
1248 ' 1 0.c 0.4',
1249 '-1 0.c -0.4',
1250 ' 1 -0.c 0.4',
1251 '-1 -0.c -0.4',
1252 ' 1.4 0.c -0.4',
1253 '-1.4 0.c 0.4',
1254 ' 1.4 -0.c -0.4',
1255 '-1.4 -0.c 0.4',
1256
1257 # Huge modulus, to check that the underlying algorithm doesn't
1258 # rely on 2.0 * modulus being representable.
1259 '0x1.dp+1023 0x1.4p+1023 0x0.9p+1023',
1260 '0x1.ep+1023 0x1.4p+1023 -0x0.ap+1023',
1261 '0x1.fp+1023 0x1.4p+1023 -0x0.9p+1023',
1262 ]
1263
1264 for case in testcases:
1265 with self.subTest(case=case):
1266 x_hex, y_hex, expected_hex = case.split()
1267 x = float.fromhex(x_hex)
1268 y = float.fromhex(y_hex)
1269 expected = float.fromhex(expected_hex)
1270 validate_spec(x, y, expected)
1271 actual = math.remainder(x, y)
1272 # Cheap way of checking that the floats are
1273 # as identical as we need them to be.
1274 self.assertEqual(actual.hex(), expected.hex())
1275
1276 # Test tiny subnormal modulus: there's potential for
1277 # getting the implementation wrong here (for example,
1278 # by assuming that modulus/2 is exactly representable).
1279 tiny = float.fromhex('1p-1074') # min +ve subnormal
1280 for n in range(-25, 25):
1281 if n == 0:
1282 continue
1283 y = n * tiny
1284 for m in range(100):
1285 x = m * tiny
1286 actual = math.remainder(x, y)
1287 validate_spec(x, y, actual)
1288 actual = math.remainder(-x, y)
1289 validate_spec(-x, y, actual)
1290
1291 # Special values.
1292 # NaNs should propagate as usual.
1293 for value in [NAN, 0.0, -0.0, 2.0, -2.3, NINF, INF]:
1294 self.assertIsNaN(math.remainder(NAN, value))
1295 self.assertIsNaN(math.remainder(value, NAN))
1296
1297 # remainder(x, inf) is x, for non-nan non-infinite x.
1298 for value in [-2.3, -0.0, 0.0, 2.3]:
1299 self.assertEqual(math.remainder(value, INF), value)
1300 self.assertEqual(math.remainder(value, NINF), value)
1301
1302 # remainder(x, 0) and remainder(infinity, x) for non-NaN x are invalid
1303 # operations according to IEEE 754-2008 7.2(f), and should raise.
1304 for value in [NINF, -2.3, -0.0, 0.0, 2.3, INF]:
1305 with self.assertRaises(ValueError):
1306 math.remainder(INF, value)
1307 with self.assertRaises(ValueError):
1308 math.remainder(NINF, value)
1309 with self.assertRaises(ValueError):
1310 math.remainder(value, 0.0)
1311 with self.assertRaises(ValueError):
1312 math.remainder(value, -0.0)
1313
Thomas Wouters89f507f2006-12-13 04:49:30 +00001314 def testSin(self):
1315 self.assertRaises(TypeError, math.sin)
1316 self.ftest('sin(0)', math.sin(0), 0)
1317 self.ftest('sin(pi/2)', math.sin(math.pi/2), 1)
1318 self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1)
Christian Heimes53876d92008-04-19 00:31:39 +00001319 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001320 self.assertTrue(math.isnan(math.sin(INF)))
1321 self.assertTrue(math.isnan(math.sin(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +00001322 except ValueError:
1323 self.assertRaises(ValueError, math.sin, INF)
1324 self.assertRaises(ValueError, math.sin, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001325 self.assertTrue(math.isnan(math.sin(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +00001326
Thomas Wouters89f507f2006-12-13 04:49:30 +00001327 def testSinh(self):
1328 self.assertRaises(TypeError, math.sinh)
1329 self.ftest('sinh(0)', math.sinh(0), 0)
1330 self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1)
1331 self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001332 self.assertEqual(math.sinh(INF), INF)
1333 self.assertEqual(math.sinh(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001334 self.assertTrue(math.isnan(math.sinh(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +00001335
Thomas Wouters89f507f2006-12-13 04:49:30 +00001336 def testSqrt(self):
1337 self.assertRaises(TypeError, math.sqrt)
1338 self.ftest('sqrt(0)', math.sqrt(0), 0)
1339 self.ftest('sqrt(1)', math.sqrt(1), 1)
1340 self.ftest('sqrt(4)', math.sqrt(4), 2)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001341 self.assertEqual(math.sqrt(INF), INF)
Mark Dickinson31ba1c32016-09-04 12:29:14 +01001342 self.assertRaises(ValueError, math.sqrt, -1)
Christian Heimes53876d92008-04-19 00:31:39 +00001343 self.assertRaises(ValueError, math.sqrt, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001344 self.assertTrue(math.isnan(math.sqrt(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +00001345
Thomas Wouters89f507f2006-12-13 04:49:30 +00001346 def testTan(self):
1347 self.assertRaises(TypeError, math.tan)
1348 self.ftest('tan(0)', math.tan(0), 0)
1349 self.ftest('tan(pi/4)', math.tan(math.pi/4), 1)
1350 self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1)
Christian Heimes53876d92008-04-19 00:31:39 +00001351 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001352 self.assertTrue(math.isnan(math.tan(INF)))
1353 self.assertTrue(math.isnan(math.tan(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +00001354 except:
1355 self.assertRaises(ValueError, math.tan, INF)
1356 self.assertRaises(ValueError, math.tan, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001357 self.assertTrue(math.isnan(math.tan(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +00001358
Thomas Wouters89f507f2006-12-13 04:49:30 +00001359 def testTanh(self):
1360 self.assertRaises(TypeError, math.tanh)
1361 self.ftest('tanh(0)', math.tanh(0), 0)
Mark Dickinson96f774d2016-09-03 19:30:22 +01001362 self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0,
1363 abs_tol=ulp(1))
Christian Heimes53876d92008-04-19 00:31:39 +00001364 self.ftest('tanh(inf)', math.tanh(INF), 1)
1365 self.ftest('tanh(-inf)', math.tanh(NINF), -1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001366 self.assertTrue(math.isnan(math.tanh(NAN)))
Victor Stinnerbe3da382010-11-07 14:14:27 +00001367
1368 @requires_IEEE_754
Victor Stinnerbe3da382010-11-07 14:14:27 +00001369 def testTanhSign(self):
Christian Heimese57950f2008-04-21 13:08:03 +00001370 # check that tanh(-0.) == -0. on IEEE 754 systems
Victor Stinnerbe3da382010-11-07 14:14:27 +00001371 self.assertEqual(math.tanh(-0.), -0.)
1372 self.assertEqual(math.copysign(1., math.tanh(-0.)),
1373 math.copysign(1., -0.))
Tim Peters1d120612000-10-12 06:10:25 +00001374
Christian Heimes400adb02008-02-01 08:12:03 +00001375 def test_trunc(self):
1376 self.assertEqual(math.trunc(1), 1)
1377 self.assertEqual(math.trunc(-1), -1)
1378 self.assertEqual(type(math.trunc(1)), int)
1379 self.assertEqual(type(math.trunc(1.5)), int)
1380 self.assertEqual(math.trunc(1.5), 1)
1381 self.assertEqual(math.trunc(-1.5), -1)
1382 self.assertEqual(math.trunc(1.999999), 1)
1383 self.assertEqual(math.trunc(-1.999999), -1)
1384 self.assertEqual(math.trunc(-0.999999), -0)
1385 self.assertEqual(math.trunc(-100.999), -100)
1386
1387 class TestTrunc(object):
1388 def __trunc__(self):
1389 return 23
1390
1391 class TestNoTrunc(object):
1392 pass
1393
1394 self.assertEqual(math.trunc(TestTrunc()), 23)
1395
1396 self.assertRaises(TypeError, math.trunc)
1397 self.assertRaises(TypeError, math.trunc, 1, 2)
1398 self.assertRaises(TypeError, math.trunc, TestNoTrunc())
1399
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001400 def testIsfinite(self):
1401 self.assertTrue(math.isfinite(0.0))
1402 self.assertTrue(math.isfinite(-0.0))
1403 self.assertTrue(math.isfinite(1.0))
1404 self.assertTrue(math.isfinite(-1.0))
1405 self.assertFalse(math.isfinite(float("nan")))
1406 self.assertFalse(math.isfinite(float("inf")))
1407 self.assertFalse(math.isfinite(float("-inf")))
1408
Christian Heimes072c0f12008-01-03 23:01:04 +00001409 def testIsnan(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001410 self.assertTrue(math.isnan(float("nan")))
Mark Dickinson31ba1c32016-09-04 12:29:14 +01001411 self.assertTrue(math.isnan(float("-nan")))
1412 self.assertTrue(math.isnan(float("inf") * 0.))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001413 self.assertFalse(math.isnan(float("inf")))
1414 self.assertFalse(math.isnan(0.))
1415 self.assertFalse(math.isnan(1.))
Christian Heimes072c0f12008-01-03 23:01:04 +00001416
1417 def testIsinf(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001418 self.assertTrue(math.isinf(float("inf")))
1419 self.assertTrue(math.isinf(float("-inf")))
1420 self.assertTrue(math.isinf(1E400))
1421 self.assertTrue(math.isinf(-1E400))
1422 self.assertFalse(math.isinf(float("nan")))
1423 self.assertFalse(math.isinf(0.))
1424 self.assertFalse(math.isinf(1.))
Christian Heimes072c0f12008-01-03 23:01:04 +00001425
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00001426 @requires_IEEE_754
1427 def test_nan_constant(self):
1428 self.assertTrue(math.isnan(math.nan))
1429
1430 @requires_IEEE_754
1431 def test_inf_constant(self):
1432 self.assertTrue(math.isinf(math.inf))
1433 self.assertGreater(math.inf, 0.0)
1434 self.assertEqual(math.inf, float("inf"))
1435 self.assertEqual(-math.inf, float("-inf"))
1436
Thomas Wouters89f507f2006-12-13 04:49:30 +00001437 # RED_FLAG 16-Oct-2000 Tim
1438 # While 2.0 is more consistent about exceptions than previous releases, it
1439 # still fails this part of the test on some platforms. For now, we only
1440 # *run* test_exceptions() in verbose mode, so that this isn't normally
1441 # tested.
Serhiy Storchaka43767632013-11-03 21:31:38 +02001442 @unittest.skipUnless(verbose, 'requires verbose mode')
1443 def test_exceptions(self):
1444 try:
1445 x = math.exp(-1000000000)
1446 except:
1447 # mathmodule.c is failing to weed out underflows from libm, or
1448 # we've got an fp format with huge dynamic range
1449 self.fail("underflowing exp() should not have raised "
1450 "an exception")
1451 if x != 0:
1452 self.fail("underflowing exp() should have returned 0")
Tim Peters98c81842000-10-16 17:35:13 +00001453
Serhiy Storchaka43767632013-11-03 21:31:38 +02001454 # If this fails, probably using a strict IEEE-754 conforming libm, and x
1455 # is +Inf afterwards. But Python wants overflows detected by default.
1456 try:
1457 x = math.exp(1000000000)
1458 except OverflowError:
1459 pass
1460 else:
1461 self.fail("overflowing exp() didn't trigger OverflowError")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001462
Serhiy Storchaka43767632013-11-03 21:31:38 +02001463 # If this fails, it could be a puzzle. One odd possibility is that
1464 # mathmodule.c's macros are getting confused while comparing
1465 # Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE
1466 # as a result (and so raising OverflowError instead).
1467 try:
1468 x = math.sqrt(-1.0)
1469 except ValueError:
1470 pass
1471 else:
1472 self.fail("sqrt(-1) didn't raise ValueError")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001473
Mark Dickinson63566232009-09-18 21:04:19 +00001474 @requires_IEEE_754
Christian Heimes53876d92008-04-19 00:31:39 +00001475 def test_testfile(self):
Mark Dickinson85746542016-09-04 09:58:51 +01001476 # Some tests need to be skipped on ancient OS X versions.
1477 # See issue #27953.
1478 SKIP_ON_TIGER = {'tan0064'}
1479
1480 osx_version = None
1481 if sys.platform == 'darwin':
1482 version_txt = platform.mac_ver()[0]
1483 try:
1484 osx_version = tuple(map(int, version_txt.split('.')))
1485 except ValueError:
1486 pass
1487
Mark Dickinson96f774d2016-09-03 19:30:22 +01001488 fail_fmt = "{}: {}({!r}): {}"
1489
1490 failures = []
Christian Heimes53876d92008-04-19 00:31:39 +00001491 for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file):
Mark Dickinson96f774d2016-09-03 19:30:22 +01001492 # Skip if either the input or result is complex
1493 if ai != 0.0 or ei != 0.0:
Christian Heimes53876d92008-04-19 00:31:39 +00001494 continue
1495 if fn in ['rect', 'polar']:
1496 # no real versions of rect, polar
1497 continue
Mark Dickinson85746542016-09-04 09:58:51 +01001498 # Skip certain tests on OS X 10.4.
1499 if osx_version is not None and osx_version < (10, 5):
1500 if id in SKIP_ON_TIGER:
1501 continue
Mark Dickinson96f774d2016-09-03 19:30:22 +01001502
Christian Heimes53876d92008-04-19 00:31:39 +00001503 func = getattr(math, fn)
Mark Dickinson96f774d2016-09-03 19:30:22 +01001504
1505 if 'invalid' in flags or 'divide-by-zero' in flags:
1506 er = 'ValueError'
1507 elif 'overflow' in flags:
1508 er = 'OverflowError'
1509
Christian Heimesa342c012008-04-20 21:01:16 +00001510 try:
1511 result = func(ar)
Mark Dickinson96f774d2016-09-03 19:30:22 +01001512 except ValueError:
1513 result = 'ValueError'
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001514 except OverflowError:
Mark Dickinson96f774d2016-09-03 19:30:22 +01001515 result = 'OverflowError'
1516
1517 # Default tolerances
1518 ulp_tol, abs_tol = 5, 0.0
1519
1520 failure = result_check(er, result, ulp_tol, abs_tol)
1521 if failure is None:
1522 continue
1523
1524 msg = fail_fmt.format(id, fn, ar, failure)
1525 failures.append(msg)
1526
1527 if failures:
1528 self.fail('Failures in test_testfile:\n ' +
1529 '\n '.join(failures))
Thomas Wouters89f507f2006-12-13 04:49:30 +00001530
Victor Stinnerbe3da382010-11-07 14:14:27 +00001531 @requires_IEEE_754
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001532 def test_mtestfile(self):
Mark Dickinson96f774d2016-09-03 19:30:22 +01001533 fail_fmt = "{}: {}({!r}): {}"
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001534
1535 failures = []
1536 for id, fn, arg, expected, flags in parse_mtestfile(math_testcases):
1537 func = getattr(math, fn)
1538
1539 if 'invalid' in flags or 'divide-by-zero' in flags:
1540 expected = 'ValueError'
1541 elif 'overflow' in flags:
1542 expected = 'OverflowError'
1543
1544 try:
1545 got = func(arg)
1546 except ValueError:
1547 got = 'ValueError'
1548 except OverflowError:
1549 got = 'OverflowError'
1550
Mark Dickinson96f774d2016-09-03 19:30:22 +01001551 # Default tolerances
1552 ulp_tol, abs_tol = 5, 0.0
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +00001553
Mark Dickinson96f774d2016-09-03 19:30:22 +01001554 # Exceptions to the defaults
1555 if fn == 'gamma':
1556 # Experimental results on one platform gave
1557 # an accuracy of <= 10 ulps across the entire float
1558 # domain. We weaken that to require 20 ulp accuracy.
1559 ulp_tol = 20
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001560
Mark Dickinson96f774d2016-09-03 19:30:22 +01001561 elif fn == 'lgamma':
1562 # we use a weaker accuracy test for lgamma;
1563 # lgamma only achieves an absolute error of
1564 # a few multiples of the machine accuracy, in
1565 # general.
1566 abs_tol = 1e-15
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001567
Mark Dickinson96f774d2016-09-03 19:30:22 +01001568 elif fn == 'erfc' and arg >= 0.0:
1569 # erfc has less-than-ideal accuracy for large
1570 # arguments (x ~ 25 or so), mainly due to the
1571 # error involved in computing exp(-x*x).
1572 #
1573 # Observed between CPython and mpmath at 25 dp:
1574 # x < 0 : err <= 2 ulp
1575 # 0 <= x < 1 : err <= 10 ulp
1576 # 1 <= x < 10 : err <= 100 ulp
1577 # 10 <= x < 20 : err <= 300 ulp
1578 # 20 <= x : < 600 ulp
1579 #
1580 if arg < 1.0:
1581 ulp_tol = 10
1582 elif arg < 10.0:
1583 ulp_tol = 100
1584 else:
1585 ulp_tol = 1000
1586
1587 failure = result_check(expected, got, ulp_tol, abs_tol)
1588 if failure is None:
1589 continue
1590
1591 msg = fail_fmt.format(id, fn, arg, failure)
1592 failures.append(msg)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001593
1594 if failures:
1595 self.fail('Failures in test_mtestfile:\n ' +
1596 '\n '.join(failures))
1597
Pablo Galindo04114112019-03-09 19:18:08 +00001598 def test_prod(self):
1599 prod = math.prod
1600 self.assertEqual(prod([]), 1)
1601 self.assertEqual(prod([], start=5), 5)
1602 self.assertEqual(prod(list(range(2,8))), 5040)
1603 self.assertEqual(prod(iter(list(range(2,8)))), 5040)
1604 self.assertEqual(prod(range(1, 10), start=10), 3628800)
1605
1606 self.assertEqual(prod([1, 2, 3, 4, 5]), 120)
1607 self.assertEqual(prod([1.0, 2.0, 3.0, 4.0, 5.0]), 120.0)
1608 self.assertEqual(prod([1, 2, 3, 4.0, 5.0]), 120.0)
1609 self.assertEqual(prod([1.0, 2.0, 3.0, 4, 5]), 120.0)
1610
1611 # Test overflow in fast-path for integers
1612 self.assertEqual(prod([1, 1, 2**32, 1, 1]), 2**32)
1613 # Test overflow in fast-path for floats
1614 self.assertEqual(prod([1.0, 1.0, 2**32, 1, 1]), float(2**32))
1615
1616 self.assertRaises(TypeError, prod)
1617 self.assertRaises(TypeError, prod, 42)
1618 self.assertRaises(TypeError, prod, ['a', 'b', 'c'])
1619 self.assertRaises(TypeError, prod, ['a', 'b', 'c'], '')
1620 self.assertRaises(TypeError, prod, [b'a', b'c'], b'')
1621 values = [bytearray(b'a'), bytearray(b'b')]
1622 self.assertRaises(TypeError, prod, values, bytearray(b''))
1623 self.assertRaises(TypeError, prod, [[1], [2], [3]])
1624 self.assertRaises(TypeError, prod, [{2:3}])
1625 self.assertRaises(TypeError, prod, [{2:3}]*2, {2:3})
1626 self.assertRaises(TypeError, prod, [[1], [2], [3]], [])
1627 with self.assertRaises(TypeError):
1628 prod([10, 20], [30, 40]) # start is a keyword-only argument
1629
1630 self.assertEqual(prod([0, 1, 2, 3]), 0)
1631 self.assertEqual(prod([1, 0, 2, 3]), 0)
1632 self.assertEqual(prod([1, 2, 3, 0]), 0)
1633
1634 def _naive_prod(iterable, start=1):
1635 for elem in iterable:
1636 start *= elem
1637 return start
1638
1639 # Big integers
1640
1641 iterable = range(1, 10000)
1642 self.assertEqual(prod(iterable), _naive_prod(iterable))
1643 iterable = range(-10000, -1)
1644 self.assertEqual(prod(iterable), _naive_prod(iterable))
1645 iterable = range(-1000, 1000)
1646 self.assertEqual(prod(iterable), 0)
1647
1648 # Big floats
1649
1650 iterable = [float(x) for x in range(1, 1000)]
1651 self.assertEqual(prod(iterable), _naive_prod(iterable))
1652 iterable = [float(x) for x in range(-1000, -1)]
1653 self.assertEqual(prod(iterable), _naive_prod(iterable))
1654 iterable = [float(x) for x in range(-1000, 1000)]
1655 self.assertIsNaN(prod(iterable))
1656
1657 # Float tests
1658
1659 self.assertIsNaN(prod([1, 2, 3, float("nan"), 2, 3]))
1660 self.assertIsNaN(prod([1, 0, float("nan"), 2, 3]))
1661 self.assertIsNaN(prod([1, float("nan"), 0, 3]))
1662 self.assertIsNaN(prod([1, float("inf"), float("nan"),3]))
1663 self.assertIsNaN(prod([1, float("-inf"), float("nan"),3]))
1664 self.assertIsNaN(prod([1, float("nan"), float("inf"),3]))
1665 self.assertIsNaN(prod([1, float("nan"), float("-inf"),3]))
1666
1667 self.assertEqual(prod([1, 2, 3, float('inf'),-3,4]), float('-inf'))
1668 self.assertEqual(prod([1, 2, 3, float('-inf'),-3,4]), float('inf'))
1669
1670 self.assertIsNaN(prod([1,2,0,float('inf'), -3, 4]))
1671 self.assertIsNaN(prod([1,2,0,float('-inf'), -3, 4]))
1672 self.assertIsNaN(prod([1, 2, 3, float('inf'), -3, 0, 3]))
1673 self.assertIsNaN(prod([1, 2, 3, float('-inf'), -3, 0, 2]))
1674
1675 # Type preservation
1676
1677 self.assertEqual(type(prod([1, 2, 3, 4, 5, 6])), int)
1678 self.assertEqual(type(prod([1, 2.0, 3, 4, 5, 6])), float)
1679 self.assertEqual(type(prod(range(1, 10000))), int)
1680 self.assertEqual(type(prod(range(1, 10000), start=1.0)), float)
1681 self.assertEqual(type(prod([1, decimal.Decimal(2.0), 3, 4, 5, 6])),
1682 decimal.Decimal)
1683
Mark Dickinsona0ce3752017-04-05 18:34:27 +01001684 # Custom assertions.
1685
1686 def assertIsNaN(self, value):
1687 if not math.isnan(value):
1688 self.fail("Expected a NaN, got {!r}.".format(value))
1689
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001690
Tal Einatd5519ed2015-05-31 22:05:00 +03001691class IsCloseTests(unittest.TestCase):
Mike53f7a7c2017-12-14 14:04:53 +03001692 isclose = math.isclose # subclasses should override this
Tal Einatd5519ed2015-05-31 22:05:00 +03001693
1694 def assertIsClose(self, a, b, *args, **kwargs):
1695 self.assertTrue(self.isclose(a, b, *args, **kwargs),
1696 msg="%s and %s should be close!" % (a, b))
1697
1698 def assertIsNotClose(self, a, b, *args, **kwargs):
1699 self.assertFalse(self.isclose(a, b, *args, **kwargs),
1700 msg="%s and %s should not be close!" % (a, b))
1701
1702 def assertAllClose(self, examples, *args, **kwargs):
1703 for a, b in examples:
1704 self.assertIsClose(a, b, *args, **kwargs)
1705
1706 def assertAllNotClose(self, examples, *args, **kwargs):
1707 for a, b in examples:
1708 self.assertIsNotClose(a, b, *args, **kwargs)
1709
1710 def test_negative_tolerances(self):
1711 # ValueError should be raised if either tolerance is less than zero
1712 with self.assertRaises(ValueError):
1713 self.assertIsClose(1, 1, rel_tol=-1e-100)
1714 with self.assertRaises(ValueError):
1715 self.assertIsClose(1, 1, rel_tol=1e-100, abs_tol=-1e10)
1716
1717 def test_identical(self):
1718 # identical values must test as close
1719 identical_examples = [(2.0, 2.0),
1720 (0.1e200, 0.1e200),
1721 (1.123e-300, 1.123e-300),
1722 (12345, 12345.0),
1723 (0.0, -0.0),
1724 (345678, 345678)]
1725 self.assertAllClose(identical_examples, rel_tol=0.0, abs_tol=0.0)
1726
1727 def test_eight_decimal_places(self):
1728 # examples that are close to 1e-8, but not 1e-9
1729 eight_decimal_places_examples = [(1e8, 1e8 + 1),
1730 (-1e-8, -1.000000009e-8),
1731 (1.12345678, 1.12345679)]
1732 self.assertAllClose(eight_decimal_places_examples, rel_tol=1e-8)
1733 self.assertAllNotClose(eight_decimal_places_examples, rel_tol=1e-9)
1734
1735 def test_near_zero(self):
1736 # values close to zero
1737 near_zero_examples = [(1e-9, 0.0),
1738 (-1e-9, 0.0),
1739 (-1e-150, 0.0)]
1740 # these should not be close to any rel_tol
1741 self.assertAllNotClose(near_zero_examples, rel_tol=0.9)
1742 # these should be close to abs_tol=1e-8
1743 self.assertAllClose(near_zero_examples, abs_tol=1e-8)
1744
1745 def test_identical_infinite(self):
1746 # these are close regardless of tolerance -- i.e. they are equal
1747 self.assertIsClose(INF, INF)
1748 self.assertIsClose(INF, INF, abs_tol=0.0)
1749 self.assertIsClose(NINF, NINF)
1750 self.assertIsClose(NINF, NINF, abs_tol=0.0)
1751
1752 def test_inf_ninf_nan(self):
1753 # these should never be close (following IEEE 754 rules for equality)
1754 not_close_examples = [(NAN, NAN),
1755 (NAN, 1e-100),
1756 (1e-100, NAN),
1757 (INF, NAN),
1758 (NAN, INF),
1759 (INF, NINF),
1760 (INF, 1.0),
1761 (1.0, INF),
1762 (INF, 1e308),
1763 (1e308, INF)]
1764 # use largest reasonable tolerance
1765 self.assertAllNotClose(not_close_examples, abs_tol=0.999999999999999)
1766
1767 def test_zero_tolerance(self):
1768 # test with zero tolerance
1769 zero_tolerance_close_examples = [(1.0, 1.0),
1770 (-3.4, -3.4),
1771 (-1e-300, -1e-300)]
1772 self.assertAllClose(zero_tolerance_close_examples, rel_tol=0.0)
1773
1774 zero_tolerance_not_close_examples = [(1.0, 1.000000000000001),
1775 (0.99999999999999, 1.0),
1776 (1.0e200, .999999999999999e200)]
1777 self.assertAllNotClose(zero_tolerance_not_close_examples, rel_tol=0.0)
1778
Martin Pantereb995702016-07-28 01:11:04 +00001779 def test_asymmetry(self):
1780 # test the asymmetry example from PEP 485
Tal Einatd5519ed2015-05-31 22:05:00 +03001781 self.assertAllClose([(9, 10), (10, 9)], rel_tol=0.1)
1782
1783 def test_integers(self):
1784 # test with integer values
1785 integer_examples = [(100000001, 100000000),
1786 (123456789, 123456788)]
1787
1788 self.assertAllClose(integer_examples, rel_tol=1e-8)
1789 self.assertAllNotClose(integer_examples, rel_tol=1e-9)
1790
1791 def test_decimals(self):
1792 # test with Decimal values
1793 from decimal import Decimal
1794
1795 decimal_examples = [(Decimal('1.00000001'), Decimal('1.0')),
1796 (Decimal('1.00000001e-20'), Decimal('1.0e-20')),
Mark Dickinson31ba1c32016-09-04 12:29:14 +01001797 (Decimal('1.00000001e-100'), Decimal('1.0e-100')),
1798 (Decimal('1.00000001e20'), Decimal('1.0e20'))]
Tal Einatd5519ed2015-05-31 22:05:00 +03001799 self.assertAllClose(decimal_examples, rel_tol=1e-8)
1800 self.assertAllNotClose(decimal_examples, rel_tol=1e-9)
1801
1802 def test_fractions(self):
1803 # test with Fraction values
1804 from fractions import Fraction
1805
Mark Dickinson31ba1c32016-09-04 12:29:14 +01001806 fraction_examples = [
1807 (Fraction(1, 100000000) + 1, Fraction(1)),
1808 (Fraction(100000001), Fraction(100000000)),
1809 (Fraction(10**8 + 1, 10**28), Fraction(1, 10**20))]
Tal Einatd5519ed2015-05-31 22:05:00 +03001810 self.assertAllClose(fraction_examples, rel_tol=1e-8)
1811 self.assertAllNotClose(fraction_examples, rel_tol=1e-9)
1812
Pablo Galindo42079072019-02-10 19:56:58 +00001813
Thomas Wouters89f507f2006-12-13 04:49:30 +00001814def test_main():
Christian Heimes53876d92008-04-19 00:31:39 +00001815 from doctest import DocFileSuite
1816 suite = unittest.TestSuite()
1817 suite.addTest(unittest.makeSuite(MathTests))
Tal Einatd5519ed2015-05-31 22:05:00 +03001818 suite.addTest(unittest.makeSuite(IsCloseTests))
Christian Heimes53876d92008-04-19 00:31:39 +00001819 suite.addTest(DocFileSuite("ieee754.txt"))
1820 run_unittest(suite)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001821
1822if __name__ == '__main__':
1823 test_main()