blob: d0bc79065f118e86b817b0fed77af4020915c0d2 [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
7import math
Christian Heimes53876d92008-04-19 00:31:39 +00008import os
9import sys
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000010import struct
Victor Stinnerbe3da382010-11-07 14:14:27 +000011import sysconfig
Guido van Rossumfcce6301996-08-08 18:26:25 +000012
Christian Heimes53876d92008-04-19 00:31:39 +000013eps = 1E-05
14NAN = float('nan')
15INF = float('inf')
16NINF = float('-inf')
17
Mark Dickinson5c567082009-04-24 16:39:07 +000018# detect evidence of double-rounding: fsum is not always correctly
19# rounded on machines that suffer from double rounding.
20x, y = 1e16, 2.9999 # use temporary values to defeat peephole optimizer
21HAVE_DOUBLE_ROUNDING = (x + y == 1e16 + 4)
22
Christian Heimes53876d92008-04-19 00:31:39 +000023# locate file with test values
24if __name__ == '__main__':
25 file = sys.argv[0]
26else:
27 file = __file__
28test_dir = os.path.dirname(file) or os.curdir
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000029math_testcases = os.path.join(test_dir, 'math_testcases.txt')
Christian Heimes53876d92008-04-19 00:31:39 +000030test_file = os.path.join(test_dir, 'cmath_testcases.txt')
31
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000032def to_ulps(x):
33 """Convert a non-NaN float x to an integer, in such a way that
34 adjacent floats are converted to adjacent integers. Then
35 abs(ulps(x) - ulps(y)) gives the difference in ulps between two
36 floats.
37
38 The results from this function will only make sense on platforms
39 where C doubles are represented in IEEE 754 binary64 format.
40
41 """
Mark Dickinsond412ab52009-10-17 07:10:00 +000042 n = struct.unpack('<q', struct.pack('<d', x))[0]
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000043 if n < 0:
44 n = ~(n+2**63)
45 return n
46
Mark Dickinson05d2e082009-12-11 20:17:17 +000047def ulps_check(expected, got, ulps=20):
48 """Given non-NaN floats `expected` and `got`,
49 check that they're equal to within the given number of ulps.
50
51 Returns None on success and an error message on failure."""
52
53 ulps_error = to_ulps(got) - to_ulps(expected)
54 if abs(ulps_error) <= ulps:
55 return None
56 return "error = {} ulps; permitted error = {} ulps".format(ulps_error,
57 ulps)
58
Mark Dickinson4c8a9a22010-05-15 17:02:38 +000059# Here's a pure Python version of the math.factorial algorithm, for
60# documentation and comparison purposes.
61#
62# Formula:
63#
64# factorial(n) = factorial_odd_part(n) << (n - count_set_bits(n))
65#
66# where
67#
68# factorial_odd_part(n) = product_{i >= 0} product_{0 < j <= n >> i; j odd} j
69#
70# The outer product above is an infinite product, but once i >= n.bit_length,
71# (n >> i) < 1 and the corresponding term of the product is empty. So only the
72# finitely many terms for 0 <= i < n.bit_length() contribute anything.
73#
74# We iterate downwards from i == n.bit_length() - 1 to i == 0. The inner
75# product in the formula above starts at 1 for i == n.bit_length(); for each i
76# < n.bit_length() we get the inner product for i from that for i + 1 by
77# multiplying by all j in {n >> i+1 < j <= n >> i; j odd}. In Python terms,
78# this set is range((n >> i+1) + 1 | 1, (n >> i) + 1 | 1, 2).
79
80def count_set_bits(n):
81 """Number of '1' bits in binary expansion of a nonnnegative integer."""
82 return 1 + count_set_bits(n & n - 1) if n else 0
83
84def partial_product(start, stop):
85 """Product of integers in range(start, stop, 2), computed recursively.
86 start and stop should both be odd, with start <= stop.
87
88 """
89 numfactors = (stop - start) >> 1
90 if not numfactors:
91 return 1
92 elif numfactors == 1:
93 return start
94 else:
95 mid = (start + numfactors) | 1
96 return partial_product(start, mid) * partial_product(mid, stop)
97
98def py_factorial(n):
99 """Factorial of nonnegative integer n, via "Binary Split Factorial Formula"
100 described at http://www.luschny.de/math/factorial/binarysplitfact.html
101
102 """
103 inner = outer = 1
104 for i in reversed(range(n.bit_length())):
105 inner *= partial_product((n >> i + 1) + 1 | 1, (n >> i) + 1 | 1)
106 outer *= inner
107 return outer << (n - count_set_bits(n))
108
Mark Dickinson05d2e082009-12-11 20:17:17 +0000109def acc_check(expected, got, rel_err=2e-15, abs_err = 5e-323):
110 """Determine whether non-NaN floats a and b are equal to within a
111 (small) rounding error. The default values for rel_err and
112 abs_err are chosen to be suitable for platforms where a float is
113 represented by an IEEE 754 double. They allow an error of between
114 9 and 19 ulps."""
115
116 # need to special case infinities, since inf - inf gives nan
117 if math.isinf(expected) and got == expected:
118 return None
119
120 error = got - expected
121
122 permitted_error = max(abs_err, rel_err * abs(expected))
123 if abs(error) < permitted_error:
124 return None
125 return "error = {}; permitted error = {}".format(error,
126 permitted_error)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000127
128def parse_mtestfile(fname):
129 """Parse a file with test values
130
131 -- starts a comment
132 blank lines, or lines containing only a comment, are ignored
133 other lines are expected to have the form
134 id fn arg -> expected [flag]*
135
136 """
137 with open(fname) as fp:
138 for line in fp:
139 # strip comments, and skip blank lines
140 if '--' in line:
141 line = line[:line.index('--')]
142 if not line.strip():
143 continue
144
145 lhs, rhs = line.split('->')
146 id, fn, arg = lhs.split()
147 rhs_pieces = rhs.split()
148 exp = rhs_pieces[0]
149 flags = rhs_pieces[1:]
150
151 yield (id, fn, float(arg), float(exp), flags)
152
Christian Heimes53876d92008-04-19 00:31:39 +0000153def parse_testfile(fname):
154 """Parse a file with test values
155
156 Empty lines or lines starting with -- are ignored
157 yields id, fn, arg_real, arg_imag, exp_real, exp_imag
158 """
159 with open(fname) as fp:
160 for line in fp:
161 # skip comment lines and blank lines
162 if line.startswith('--') or not line.strip():
163 continue
164
165 lhs, rhs = line.split('->')
166 id, fn, arg_real, arg_imag = lhs.split()
167 rhs_pieces = rhs.split()
168 exp_real, exp_imag = rhs_pieces[0], rhs_pieces[1]
169 flags = rhs_pieces[2:]
170
171 yield (id, fn,
172 float(arg_real), float(arg_imag),
173 float(exp_real), float(exp_imag),
174 flags
175 )
Guido van Rossumfcce6301996-08-08 18:26:25 +0000176
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300177# Class providing an __index__ method.
178class MyIndexable(object):
179 def __init__(self, value):
180 self.value = value
181
182 def __index__(self):
183 return self.value
184
Thomas Wouters89f507f2006-12-13 04:49:30 +0000185class MathTests(unittest.TestCase):
Guido van Rossumfcce6301996-08-08 18:26:25 +0000186
Thomas Wouters89f507f2006-12-13 04:49:30 +0000187 def ftest(self, name, value, expected):
188 if abs(value-expected) > eps:
Guido van Rossum806c2462007-08-06 23:33:07 +0000189 # Use %r instead of %f so the error message
190 # displays full precision. Otherwise discrepancies
191 # in the last few bits will lead to very confusing
192 # error messages
193 self.fail('%s returned %r, expected %r' %
Thomas Wouters89f507f2006-12-13 04:49:30 +0000194 (name, value, expected))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000195
Thomas Wouters89f507f2006-12-13 04:49:30 +0000196 def testConstants(self):
197 self.ftest('pi', math.pi, 3.1415926)
198 self.ftest('e', math.e, 2.7182818)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000199
Thomas Wouters89f507f2006-12-13 04:49:30 +0000200 def testAcos(self):
201 self.assertRaises(TypeError, math.acos)
202 self.ftest('acos(-1)', math.acos(-1), math.pi)
203 self.ftest('acos(0)', math.acos(0), math.pi/2)
204 self.ftest('acos(1)', math.acos(1), 0)
Christian Heimes53876d92008-04-19 00:31:39 +0000205 self.assertRaises(ValueError, math.acos, INF)
206 self.assertRaises(ValueError, math.acos, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000207 self.assertTrue(math.isnan(math.acos(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000208
209 def testAcosh(self):
210 self.assertRaises(TypeError, math.acosh)
211 self.ftest('acosh(1)', math.acosh(1), 0)
212 self.ftest('acosh(2)', math.acosh(2), 1.3169578969248168)
213 self.assertRaises(ValueError, math.acosh, 0)
214 self.assertRaises(ValueError, math.acosh, -1)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000215 self.assertEqual(math.acosh(INF), INF)
Christian Heimes53876d92008-04-19 00:31:39 +0000216 self.assertRaises(ValueError, math.acosh, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000217 self.assertTrue(math.isnan(math.acosh(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000218
Thomas Wouters89f507f2006-12-13 04:49:30 +0000219 def testAsin(self):
220 self.assertRaises(TypeError, math.asin)
221 self.ftest('asin(-1)', math.asin(-1), -math.pi/2)
222 self.ftest('asin(0)', math.asin(0), 0)
223 self.ftest('asin(1)', math.asin(1), math.pi/2)
Christian Heimes53876d92008-04-19 00:31:39 +0000224 self.assertRaises(ValueError, math.asin, INF)
225 self.assertRaises(ValueError, math.asin, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000226 self.assertTrue(math.isnan(math.asin(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000227
228 def testAsinh(self):
229 self.assertRaises(TypeError, math.asinh)
230 self.ftest('asinh(0)', math.asinh(0), 0)
231 self.ftest('asinh(1)', math.asinh(1), 0.88137358701954305)
232 self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000233 self.assertEqual(math.asinh(INF), INF)
234 self.assertEqual(math.asinh(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000235 self.assertTrue(math.isnan(math.asinh(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000236
Thomas Wouters89f507f2006-12-13 04:49:30 +0000237 def testAtan(self):
238 self.assertRaises(TypeError, math.atan)
239 self.ftest('atan(-1)', math.atan(-1), -math.pi/4)
240 self.ftest('atan(0)', math.atan(0), 0)
241 self.ftest('atan(1)', math.atan(1), math.pi/4)
Christian Heimes53876d92008-04-19 00:31:39 +0000242 self.ftest('atan(inf)', math.atan(INF), math.pi/2)
Christian Heimesa342c012008-04-20 21:01:16 +0000243 self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000244 self.assertTrue(math.isnan(math.atan(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000245
246 def testAtanh(self):
247 self.assertRaises(TypeError, math.atan)
248 self.ftest('atanh(0)', math.atanh(0), 0)
249 self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489)
250 self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489)
251 self.assertRaises(ValueError, math.atanh, 1)
252 self.assertRaises(ValueError, math.atanh, -1)
253 self.assertRaises(ValueError, math.atanh, INF)
254 self.assertRaises(ValueError, math.atanh, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000255 self.assertTrue(math.isnan(math.atanh(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000256
Thomas Wouters89f507f2006-12-13 04:49:30 +0000257 def testAtan2(self):
258 self.assertRaises(TypeError, math.atan2)
259 self.ftest('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2)
260 self.ftest('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4)
261 self.ftest('atan2(0, 1)', math.atan2(0, 1), 0)
262 self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4)
263 self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000264
Christian Heimese57950f2008-04-21 13:08:03 +0000265 # math.atan2(0, x)
266 self.ftest('atan2(0., -inf)', math.atan2(0., NINF), math.pi)
267 self.ftest('atan2(0., -2.3)', math.atan2(0., -2.3), math.pi)
268 self.ftest('atan2(0., -0.)', math.atan2(0., -0.), math.pi)
269 self.assertEqual(math.atan2(0., 0.), 0.)
270 self.assertEqual(math.atan2(0., 2.3), 0.)
271 self.assertEqual(math.atan2(0., INF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000272 self.assertTrue(math.isnan(math.atan2(0., NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000273 # math.atan2(-0, x)
274 self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi)
275 self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi)
276 self.ftest('atan2(-0., -0.)', math.atan2(-0., -0.), -math.pi)
277 self.assertEqual(math.atan2(-0., 0.), -0.)
278 self.assertEqual(math.atan2(-0., 2.3), -0.)
279 self.assertEqual(math.atan2(-0., INF), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000280 self.assertTrue(math.isnan(math.atan2(-0., NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000281 # math.atan2(INF, x)
282 self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4)
283 self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2)
284 self.ftest('atan2(inf, -0.)', math.atan2(INF, -0.0), math.pi/2)
285 self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2)
286 self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2)
287 self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000288 self.assertTrue(math.isnan(math.atan2(INF, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000289 # math.atan2(NINF, x)
290 self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4)
291 self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2)
292 self.ftest('atan2(-inf, -0.)', math.atan2(NINF, -0.0), -math.pi/2)
293 self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2)
294 self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2)
295 self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000296 self.assertTrue(math.isnan(math.atan2(NINF, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000297 # math.atan2(+finite, x)
298 self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi)
299 self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2)
300 self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2)
301 self.assertEqual(math.atan2(2.3, INF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000302 self.assertTrue(math.isnan(math.atan2(2.3, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000303 # math.atan2(-finite, x)
304 self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi)
305 self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2)
306 self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2)
307 self.assertEqual(math.atan2(-2.3, INF), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000308 self.assertTrue(math.isnan(math.atan2(-2.3, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000309 # math.atan2(NAN, x)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000310 self.assertTrue(math.isnan(math.atan2(NAN, NINF)))
311 self.assertTrue(math.isnan(math.atan2(NAN, -2.3)))
312 self.assertTrue(math.isnan(math.atan2(NAN, -0.)))
313 self.assertTrue(math.isnan(math.atan2(NAN, 0.)))
314 self.assertTrue(math.isnan(math.atan2(NAN, 2.3)))
315 self.assertTrue(math.isnan(math.atan2(NAN, INF)))
316 self.assertTrue(math.isnan(math.atan2(NAN, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000317
Thomas Wouters89f507f2006-12-13 04:49:30 +0000318 def testCeil(self):
319 self.assertRaises(TypeError, math.ceil)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000320 self.assertEqual(int, type(math.ceil(0.5)))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000321 self.ftest('ceil(0.5)', math.ceil(0.5), 1)
322 self.ftest('ceil(1.0)', math.ceil(1.0), 1)
323 self.ftest('ceil(1.5)', math.ceil(1.5), 2)
324 self.ftest('ceil(-0.5)', math.ceil(-0.5), 0)
325 self.ftest('ceil(-1.0)', math.ceil(-1.0), -1)
326 self.ftest('ceil(-1.5)', math.ceil(-1.5), -1)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000327 #self.assertEqual(math.ceil(INF), INF)
328 #self.assertEqual(math.ceil(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000329 #self.assertTrue(math.isnan(math.ceil(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000330
Guido van Rossum13e05de2007-08-23 22:56:55 +0000331 class TestCeil:
332 def __ceil__(self):
333 return 42
334 class TestNoCeil:
335 pass
336 self.ftest('ceil(TestCeil())', math.ceil(TestCeil()), 42)
337 self.assertRaises(TypeError, math.ceil, TestNoCeil())
338
339 t = TestNoCeil()
340 t.__ceil__ = lambda *args: args
341 self.assertRaises(TypeError, math.ceil, t)
342 self.assertRaises(TypeError, math.ceil, t, 0)
343
Mark Dickinson63566232009-09-18 21:04:19 +0000344 @requires_IEEE_754
345 def testCopysign(self):
Mark Dickinson06b59e02010-02-06 23:16:50 +0000346 self.assertEqual(math.copysign(1, 42), 1.0)
347 self.assertEqual(math.copysign(0., 42), 0.0)
348 self.assertEqual(math.copysign(1., -42), -1.0)
349 self.assertEqual(math.copysign(3, 0.), 3.0)
350 self.assertEqual(math.copysign(4., -0.), -4.0)
351
Mark Dickinson63566232009-09-18 21:04:19 +0000352 self.assertRaises(TypeError, math.copysign)
353 # copysign should let us distinguish signs of zeros
Ezio Melottib3aedd42010-11-20 19:04:17 +0000354 self.assertEqual(math.copysign(1., 0.), 1.)
355 self.assertEqual(math.copysign(1., -0.), -1.)
356 self.assertEqual(math.copysign(INF, 0.), INF)
357 self.assertEqual(math.copysign(INF, -0.), NINF)
358 self.assertEqual(math.copysign(NINF, 0.), INF)
359 self.assertEqual(math.copysign(NINF, -0.), NINF)
Mark Dickinson63566232009-09-18 21:04:19 +0000360 # and of infinities
Ezio Melottib3aedd42010-11-20 19:04:17 +0000361 self.assertEqual(math.copysign(1., INF), 1.)
362 self.assertEqual(math.copysign(1., NINF), -1.)
363 self.assertEqual(math.copysign(INF, INF), INF)
364 self.assertEqual(math.copysign(INF, NINF), NINF)
365 self.assertEqual(math.copysign(NINF, INF), INF)
366 self.assertEqual(math.copysign(NINF, NINF), NINF)
Mark Dickinson06b59e02010-02-06 23:16:50 +0000367 self.assertTrue(math.isnan(math.copysign(NAN, 1.)))
368 self.assertTrue(math.isnan(math.copysign(NAN, INF)))
369 self.assertTrue(math.isnan(math.copysign(NAN, NINF)))
370 self.assertTrue(math.isnan(math.copysign(NAN, NAN)))
Mark Dickinson63566232009-09-18 21:04:19 +0000371 # copysign(INF, NAN) may be INF or it may be NINF, since
372 # we don't know whether the sign bit of NAN is set on any
373 # given platform.
Mark Dickinson06b59e02010-02-06 23:16:50 +0000374 self.assertTrue(math.isinf(math.copysign(INF, NAN)))
Mark Dickinson63566232009-09-18 21:04:19 +0000375 # similarly, copysign(2., NAN) could be 2. or -2.
Ezio Melottib3aedd42010-11-20 19:04:17 +0000376 self.assertEqual(abs(math.copysign(2., NAN)), 2.)
Christian Heimes53876d92008-04-19 00:31:39 +0000377
Thomas Wouters89f507f2006-12-13 04:49:30 +0000378 def testCos(self):
379 self.assertRaises(TypeError, math.cos)
380 self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0)
381 self.ftest('cos(0)', math.cos(0), 1)
382 self.ftest('cos(pi/2)', math.cos(math.pi/2), 0)
383 self.ftest('cos(pi)', math.cos(math.pi), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000384 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000385 self.assertTrue(math.isnan(math.cos(INF)))
386 self.assertTrue(math.isnan(math.cos(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +0000387 except ValueError:
388 self.assertRaises(ValueError, math.cos, INF)
389 self.assertRaises(ValueError, math.cos, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000390 self.assertTrue(math.isnan(math.cos(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000391
Thomas Wouters89f507f2006-12-13 04:49:30 +0000392 def testCosh(self):
393 self.assertRaises(TypeError, math.cosh)
394 self.ftest('cosh(0)', math.cosh(0), 1)
395 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 +0000396 self.assertEqual(math.cosh(INF), INF)
397 self.assertEqual(math.cosh(NINF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000398 self.assertTrue(math.isnan(math.cosh(NAN)))
Raymond Hettinger64108af2002-05-13 03:55:01 +0000399
Thomas Wouters89f507f2006-12-13 04:49:30 +0000400 def testDegrees(self):
401 self.assertRaises(TypeError, math.degrees)
402 self.ftest('degrees(pi)', math.degrees(math.pi), 180.0)
403 self.ftest('degrees(pi/2)', math.degrees(math.pi/2), 90.0)
404 self.ftest('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000405
Thomas Wouters89f507f2006-12-13 04:49:30 +0000406 def testExp(self):
407 self.assertRaises(TypeError, math.exp)
408 self.ftest('exp(-1)', math.exp(-1), 1/math.e)
409 self.ftest('exp(0)', math.exp(0), 1)
410 self.ftest('exp(1)', math.exp(1), math.e)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000411 self.assertEqual(math.exp(INF), INF)
412 self.assertEqual(math.exp(NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000413 self.assertTrue(math.isnan(math.exp(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000414
Thomas Wouters89f507f2006-12-13 04:49:30 +0000415 def testFabs(self):
416 self.assertRaises(TypeError, math.fabs)
417 self.ftest('fabs(-1)', math.fabs(-1), 1)
418 self.ftest('fabs(0)', math.fabs(0), 0)
419 self.ftest('fabs(1)', math.fabs(1), 1)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000420
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000421 def testFactorial(self):
Mark Dickinson4c8a9a22010-05-15 17:02:38 +0000422 self.assertEqual(math.factorial(0), 1)
423 self.assertEqual(math.factorial(0.0), 1)
424 total = 1
425 for i in range(1, 1000):
426 total *= i
427 self.assertEqual(math.factorial(i), total)
428 self.assertEqual(math.factorial(float(i)), total)
429 self.assertEqual(math.factorial(i), py_factorial(i))
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000430 self.assertRaises(ValueError, math.factorial, -1)
Mark Dickinson4c8a9a22010-05-15 17:02:38 +0000431 self.assertRaises(ValueError, math.factorial, -1.0)
Mark Dickinson5990d282014-04-10 09:29:39 -0400432 self.assertRaises(ValueError, math.factorial, -10**100)
433 self.assertRaises(ValueError, math.factorial, -1e100)
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000434 self.assertRaises(ValueError, math.factorial, math.pi)
Mark Dickinson5990d282014-04-10 09:29:39 -0400435
436 # Other implementations may place different upper bounds.
437 @support.cpython_only
438 def testFactorialHugeInputs(self):
439 # Currently raises ValueError for inputs that are too large
440 # to fit into a C long.
441 self.assertRaises(OverflowError, math.factorial, 10**100)
442 self.assertRaises(OverflowError, math.factorial, 1e100)
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000443
Thomas Wouters89f507f2006-12-13 04:49:30 +0000444 def testFloor(self):
445 self.assertRaises(TypeError, math.floor)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000446 self.assertEqual(int, type(math.floor(0.5)))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000447 self.ftest('floor(0.5)', math.floor(0.5), 0)
448 self.ftest('floor(1.0)', math.floor(1.0), 1)
449 self.ftest('floor(1.5)', math.floor(1.5), 1)
450 self.ftest('floor(-0.5)', math.floor(-0.5), -1)
451 self.ftest('floor(-1.0)', math.floor(-1.0), -1)
452 self.ftest('floor(-1.5)', math.floor(-1.5), -2)
Guido van Rossum806c2462007-08-06 23:33:07 +0000453 # pow() relies on floor() to check for integers
454 # This fails on some platforms - so check it here
455 self.ftest('floor(1.23e167)', math.floor(1.23e167), 1.23e167)
456 self.ftest('floor(-1.23e167)', math.floor(-1.23e167), -1.23e167)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000457 #self.assertEqual(math.ceil(INF), INF)
458 #self.assertEqual(math.ceil(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000459 #self.assertTrue(math.isnan(math.floor(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000460
Guido van Rossum13e05de2007-08-23 22:56:55 +0000461 class TestFloor:
462 def __floor__(self):
463 return 42
464 class TestNoFloor:
465 pass
466 self.ftest('floor(TestFloor())', math.floor(TestFloor()), 42)
467 self.assertRaises(TypeError, math.floor, TestNoFloor())
468
469 t = TestNoFloor()
470 t.__floor__ = lambda *args: args
471 self.assertRaises(TypeError, math.floor, t)
472 self.assertRaises(TypeError, math.floor, t, 0)
473
Thomas Wouters89f507f2006-12-13 04:49:30 +0000474 def testFmod(self):
475 self.assertRaises(TypeError, math.fmod)
Mark Dickinson5bc7a442011-05-03 21:13:40 +0100476 self.ftest('fmod(10, 1)', math.fmod(10, 1), 0.0)
477 self.ftest('fmod(10, 0.5)', math.fmod(10, 0.5), 0.0)
478 self.ftest('fmod(10, 1.5)', math.fmod(10, 1.5), 1.0)
479 self.ftest('fmod(-10, 1)', math.fmod(-10, 1), -0.0)
480 self.ftest('fmod(-10, 0.5)', math.fmod(-10, 0.5), -0.0)
481 self.ftest('fmod(-10, 1.5)', math.fmod(-10, 1.5), -1.0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000482 self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
483 self.assertTrue(math.isnan(math.fmod(1., NAN)))
484 self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000485 self.assertRaises(ValueError, math.fmod, 1., 0.)
486 self.assertRaises(ValueError, math.fmod, INF, 1.)
487 self.assertRaises(ValueError, math.fmod, NINF, 1.)
488 self.assertRaises(ValueError, math.fmod, INF, 0.)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000489 self.assertEqual(math.fmod(3.0, INF), 3.0)
490 self.assertEqual(math.fmod(-3.0, INF), -3.0)
491 self.assertEqual(math.fmod(3.0, NINF), 3.0)
492 self.assertEqual(math.fmod(-3.0, NINF), -3.0)
493 self.assertEqual(math.fmod(0.0, 3.0), 0.0)
494 self.assertEqual(math.fmod(0.0, NINF), 0.0)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000495
Thomas Wouters89f507f2006-12-13 04:49:30 +0000496 def testFrexp(self):
497 self.assertRaises(TypeError, math.frexp)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000498
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000499 def testfrexp(name, result, expected):
500 (mant, exp), (emant, eexp) = result, expected
Thomas Wouters89f507f2006-12-13 04:49:30 +0000501 if abs(mant-emant) > eps or exp != eexp:
502 self.fail('%s returned %r, expected %r'%\
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000503 (name, result, expected))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000504
Thomas Wouters89f507f2006-12-13 04:49:30 +0000505 testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
506 testfrexp('frexp(0)', math.frexp(0), (0, 0))
507 testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
508 testfrexp('frexp(2)', math.frexp(2), (0.5, 2))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000509
Ezio Melottib3aedd42010-11-20 19:04:17 +0000510 self.assertEqual(math.frexp(INF)[0], INF)
511 self.assertEqual(math.frexp(NINF)[0], NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000512 self.assertTrue(math.isnan(math.frexp(NAN)[0]))
Christian Heimes53876d92008-04-19 00:31:39 +0000513
Mark Dickinson63566232009-09-18 21:04:19 +0000514 @requires_IEEE_754
Mark Dickinson5c567082009-04-24 16:39:07 +0000515 @unittest.skipIf(HAVE_DOUBLE_ROUNDING,
516 "fsum is not exact on machines with double rounding")
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000517 def testFsum(self):
518 # math.fsum relies on exact rounding for correct operation.
519 # There's a known problem with IA32 floating-point that causes
520 # inexact rounding in some situations, and will cause the
521 # math.fsum tests below to fail; see issue #2937. On non IEEE
522 # 754 platforms, and on IEEE 754 platforms that exhibit the
523 # problem described in issue #2937, we simply skip the whole
524 # test.
525
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000526 # Python version of math.fsum, for comparison. Uses a
527 # different algorithm based on frexp, ldexp and integer
528 # arithmetic.
529 from sys import float_info
530 mant_dig = float_info.mant_dig
531 etiny = float_info.min_exp - mant_dig
532
533 def msum(iterable):
534 """Full precision summation. Compute sum(iterable) without any
535 intermediate accumulation of error. Based on the 'lsum' function
536 at http://code.activestate.com/recipes/393090/
537
538 """
539 tmant, texp = 0, 0
540 for x in iterable:
541 mant, exp = math.frexp(x)
542 mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig
543 if texp > exp:
544 tmant <<= texp-exp
545 texp = exp
546 else:
547 mant <<= exp-texp
548 tmant += mant
549 # Round tmant * 2**texp to a float. The original recipe
550 # used float(str(tmant)) * 2.0**texp for this, but that's
551 # a little unsafe because str -> float conversion can't be
552 # relied upon to do correct rounding on all platforms.
553 tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp)
554 if tail > 0:
555 h = 1 << (tail-1)
556 tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1)
557 texp += tail
558 return math.ldexp(tmant, texp)
559
560 test_values = [
561 ([], 0.0),
562 ([0.0], 0.0),
563 ([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100),
564 ([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0),
565 ([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0),
566 ([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0),
567 ([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0),
568 ([1./n for n in range(1, 1001)],
569 float.fromhex('0x1.df11f45f4e61ap+2')),
570 ([(-1.)**n/n for n in range(1, 1001)],
571 float.fromhex('-0x1.62a2af1bd3624p-1')),
572 ([1.7**(i+1)-1.7**i for i in range(1000)] + [-1.7**1000], -1.0),
573 ([1e16, 1., 1e-16], 10000000000000002.0),
574 ([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0),
575 # exercise code for resizing partials array
576 ([2.**n - 2.**(n+50) + 2.**(n+52) for n in range(-1074, 972, 2)] +
577 [-2.**1022],
578 float.fromhex('0x1.5555555555555p+970')),
579 ]
580
581 for i, (vals, expected) in enumerate(test_values):
582 try:
583 actual = math.fsum(vals)
584 except OverflowError:
585 self.fail("test %d failed: got OverflowError, expected %r "
586 "for math.fsum(%.100r)" % (i, expected, vals))
587 except ValueError:
588 self.fail("test %d failed: got ValueError, expected %r "
589 "for math.fsum(%.100r)" % (i, expected, vals))
590 self.assertEqual(actual, expected)
591
592 from random import random, gauss, shuffle
593 for j in range(1000):
594 vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10
595 s = 0
596 for i in range(200):
597 v = gauss(0, random()) ** 7 - s
598 s += v
599 vals.append(v)
600 shuffle(vals)
601
602 s = msum(vals)
603 self.assertEqual(msum(vals), math.fsum(vals))
604
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300605 def testGcd(self):
606 gcd = math.gcd
607 self.assertEqual(gcd(0, 0), 0)
608 self.assertEqual(gcd(1, 0), 1)
609 self.assertEqual(gcd(-1, 0), 1)
610 self.assertEqual(gcd(0, 1), 1)
611 self.assertEqual(gcd(0, -1), 1)
612 self.assertEqual(gcd(7, 1), 1)
613 self.assertEqual(gcd(7, -1), 1)
614 self.assertEqual(gcd(-23, 15), 1)
615 self.assertEqual(gcd(120, 84), 12)
616 self.assertEqual(gcd(84, -120), 12)
617 self.assertEqual(gcd(1216342683557601535506311712,
618 436522681849110124616458784), 32)
619 c = 652560
620 x = 434610456570399902378880679233098819019853229470286994367836600566
621 y = 1064502245825115327754847244914921553977
622 a = x * c
623 b = y * c
624 self.assertEqual(gcd(a, b), c)
625 self.assertEqual(gcd(b, a), c)
626 self.assertEqual(gcd(-a, b), c)
627 self.assertEqual(gcd(b, -a), c)
628 self.assertEqual(gcd(a, -b), c)
629 self.assertEqual(gcd(-b, a), c)
630 self.assertEqual(gcd(-a, -b), c)
631 self.assertEqual(gcd(-b, -a), c)
632 c = 576559230871654959816130551884856912003141446781646602790216406874
633 a = x * c
634 b = y * c
635 self.assertEqual(gcd(a, b), c)
636 self.assertEqual(gcd(b, a), c)
637 self.assertEqual(gcd(-a, b), c)
638 self.assertEqual(gcd(b, -a), c)
639 self.assertEqual(gcd(a, -b), c)
640 self.assertEqual(gcd(-b, a), c)
641 self.assertEqual(gcd(-a, -b), c)
642 self.assertEqual(gcd(-b, -a), c)
643
644 self.assertRaises(TypeError, gcd, 120.0, 84)
645 self.assertRaises(TypeError, gcd, 120, 84.0)
646 self.assertEqual(gcd(MyIndexable(120), MyIndexable(84)), 12)
647
Thomas Wouters89f507f2006-12-13 04:49:30 +0000648 def testHypot(self):
649 self.assertRaises(TypeError, math.hypot)
650 self.ftest('hypot(0,0)', math.hypot(0,0), 0)
651 self.ftest('hypot(3,4)', math.hypot(3,4), 5)
Christian Heimes53876d92008-04-19 00:31:39 +0000652 self.assertEqual(math.hypot(NAN, INF), INF)
653 self.assertEqual(math.hypot(INF, NAN), INF)
654 self.assertEqual(math.hypot(NAN, NINF), INF)
655 self.assertEqual(math.hypot(NINF, NAN), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000656 self.assertTrue(math.isnan(math.hypot(1.0, NAN)))
657 self.assertTrue(math.isnan(math.hypot(NAN, -2.0)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000658
Thomas Wouters89f507f2006-12-13 04:49:30 +0000659 def testLdexp(self):
660 self.assertRaises(TypeError, math.ldexp)
661 self.ftest('ldexp(0,1)', math.ldexp(0,1), 0)
662 self.ftest('ldexp(1,1)', math.ldexp(1,1), 2)
663 self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5)
664 self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2)
Christian Heimes53876d92008-04-19 00:31:39 +0000665 self.assertRaises(OverflowError, math.ldexp, 1., 1000000)
666 self.assertRaises(OverflowError, math.ldexp, -1., 1000000)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000667 self.assertEqual(math.ldexp(1., -1000000), 0.)
668 self.assertEqual(math.ldexp(-1., -1000000), -0.)
669 self.assertEqual(math.ldexp(INF, 30), INF)
670 self.assertEqual(math.ldexp(NINF, -213), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000671 self.assertTrue(math.isnan(math.ldexp(NAN, 0)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000672
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000673 # large second argument
674 for n in [10**5, 10**10, 10**20, 10**40]:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000675 self.assertEqual(math.ldexp(INF, -n), INF)
676 self.assertEqual(math.ldexp(NINF, -n), NINF)
677 self.assertEqual(math.ldexp(1., -n), 0.)
678 self.assertEqual(math.ldexp(-1., -n), -0.)
679 self.assertEqual(math.ldexp(0., -n), 0.)
680 self.assertEqual(math.ldexp(-0., -n), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000681 self.assertTrue(math.isnan(math.ldexp(NAN, -n)))
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000682
683 self.assertRaises(OverflowError, math.ldexp, 1., n)
684 self.assertRaises(OverflowError, math.ldexp, -1., n)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000685 self.assertEqual(math.ldexp(0., n), 0.)
686 self.assertEqual(math.ldexp(-0., n), -0.)
687 self.assertEqual(math.ldexp(INF, n), INF)
688 self.assertEqual(math.ldexp(NINF, n), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000689 self.assertTrue(math.isnan(math.ldexp(NAN, n)))
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000690
Thomas Wouters89f507f2006-12-13 04:49:30 +0000691 def testLog(self):
692 self.assertRaises(TypeError, math.log)
693 self.ftest('log(1/e)', math.log(1/math.e), -1)
694 self.ftest('log(1)', math.log(1), 0)
695 self.ftest('log(e)', math.log(math.e), 1)
696 self.ftest('log(32,2)', math.log(32,2), 5)
697 self.ftest('log(10**40, 10)', math.log(10**40, 10), 40)
698 self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2)
Mark Dickinsonc6037172010-09-29 19:06:36 +0000699 self.ftest('log(10**1000)', math.log(10**1000),
700 2302.5850929940457)
701 self.assertRaises(ValueError, math.log, -1.5)
702 self.assertRaises(ValueError, math.log, -10**1000)
Christian Heimes53876d92008-04-19 00:31:39 +0000703 self.assertRaises(ValueError, math.log, NINF)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000704 self.assertEqual(math.log(INF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000705 self.assertTrue(math.isnan(math.log(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000706
707 def testLog1p(self):
708 self.assertRaises(TypeError, math.log1p)
Christian Heimes53876d92008-04-19 00:31:39 +0000709 n= 2**90
Ezio Melottib3aedd42010-11-20 19:04:17 +0000710 self.assertAlmostEqual(math.log1p(n), math.log1p(float(n)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000711
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200712 @requires_IEEE_754
713 def testLog2(self):
714 self.assertRaises(TypeError, math.log2)
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200715
716 # Check some integer values
717 self.assertEqual(math.log2(1), 0.0)
718 self.assertEqual(math.log2(2), 1.0)
719 self.assertEqual(math.log2(4), 2.0)
720
721 # Large integer values
722 self.assertEqual(math.log2(2**1023), 1023.0)
723 self.assertEqual(math.log2(2**1024), 1024.0)
724 self.assertEqual(math.log2(2**2000), 2000.0)
725
726 self.assertRaises(ValueError, math.log2, -1.5)
727 self.assertRaises(ValueError, math.log2, NINF)
728 self.assertTrue(math.isnan(math.log2(NAN)))
729
Victor Stinnercd9dd372011-05-10 23:40:17 +0200730 @requires_IEEE_754
Victor Stinnerebbbdaf2011-06-01 13:19:07 +0200731 # log2() is not accurate enough on Mac OS X Tiger (10.4)
732 @support.requires_mac_ver(10, 5)
Victor Stinnercd9dd372011-05-10 23:40:17 +0200733 def testLog2Exact(self):
734 # Check that we get exact equality for log2 of powers of 2.
735 actual = [math.log2(math.ldexp(1.0, n)) for n in range(-1074, 1024)]
736 expected = [float(n) for n in range(-1074, 1024)]
737 self.assertEqual(actual, expected)
738
Thomas Wouters89f507f2006-12-13 04:49:30 +0000739 def testLog10(self):
740 self.assertRaises(TypeError, math.log10)
741 self.ftest('log10(0.1)', math.log10(0.1), -1)
742 self.ftest('log10(1)', math.log10(1), 0)
743 self.ftest('log10(10)', math.log10(10), 1)
Mark Dickinsonc6037172010-09-29 19:06:36 +0000744 self.ftest('log10(10**1000)', math.log10(10**1000), 1000.0)
745 self.assertRaises(ValueError, math.log10, -1.5)
746 self.assertRaises(ValueError, math.log10, -10**1000)
Christian Heimes53876d92008-04-19 00:31:39 +0000747 self.assertRaises(ValueError, math.log10, NINF)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000748 self.assertEqual(math.log(INF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000749 self.assertTrue(math.isnan(math.log10(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000750
Thomas Wouters89f507f2006-12-13 04:49:30 +0000751 def testModf(self):
752 self.assertRaises(TypeError, math.modf)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000753
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000754 def testmodf(name, result, expected):
755 (v1, v2), (e1, e2) = result, expected
Thomas Wouters89f507f2006-12-13 04:49:30 +0000756 if abs(v1-e1) > eps or abs(v2-e2):
757 self.fail('%s returned %r, expected %r'%\
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000758 (name, result, expected))
Raymond Hettinger64108af2002-05-13 03:55:01 +0000759
Thomas Wouters89f507f2006-12-13 04:49:30 +0000760 testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
761 testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000762
Ezio Melottib3aedd42010-11-20 19:04:17 +0000763 self.assertEqual(math.modf(INF), (0.0, INF))
764 self.assertEqual(math.modf(NINF), (-0.0, NINF))
Christian Heimes53876d92008-04-19 00:31:39 +0000765
766 modf_nan = math.modf(NAN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000767 self.assertTrue(math.isnan(modf_nan[0]))
768 self.assertTrue(math.isnan(modf_nan[1]))
Christian Heimes53876d92008-04-19 00:31:39 +0000769
Thomas Wouters89f507f2006-12-13 04:49:30 +0000770 def testPow(self):
771 self.assertRaises(TypeError, math.pow)
772 self.ftest('pow(0,1)', math.pow(0,1), 0)
773 self.ftest('pow(1,0)', math.pow(1,0), 1)
774 self.ftest('pow(2,1)', math.pow(2,1), 2)
775 self.ftest('pow(2,-1)', math.pow(2,-1), 0.5)
Christian Heimes53876d92008-04-19 00:31:39 +0000776 self.assertEqual(math.pow(INF, 1), INF)
777 self.assertEqual(math.pow(NINF, 1), NINF)
778 self.assertEqual((math.pow(1, INF)), 1.)
779 self.assertEqual((math.pow(1, NINF)), 1.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000780 self.assertTrue(math.isnan(math.pow(NAN, 1)))
781 self.assertTrue(math.isnan(math.pow(2, NAN)))
782 self.assertTrue(math.isnan(math.pow(0, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000783 self.assertEqual(math.pow(1, NAN), 1)
Christian Heimesa342c012008-04-20 21:01:16 +0000784
785 # pow(0., x)
786 self.assertEqual(math.pow(0., INF), 0.)
787 self.assertEqual(math.pow(0., 3.), 0.)
788 self.assertEqual(math.pow(0., 2.3), 0.)
789 self.assertEqual(math.pow(0., 2.), 0.)
790 self.assertEqual(math.pow(0., 0.), 1.)
791 self.assertEqual(math.pow(0., -0.), 1.)
792 self.assertRaises(ValueError, math.pow, 0., -2.)
793 self.assertRaises(ValueError, math.pow, 0., -2.3)
794 self.assertRaises(ValueError, math.pow, 0., -3.)
795 self.assertRaises(ValueError, math.pow, 0., NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000796 self.assertTrue(math.isnan(math.pow(0., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000797
798 # pow(INF, x)
799 self.assertEqual(math.pow(INF, INF), INF)
800 self.assertEqual(math.pow(INF, 3.), INF)
801 self.assertEqual(math.pow(INF, 2.3), INF)
802 self.assertEqual(math.pow(INF, 2.), INF)
803 self.assertEqual(math.pow(INF, 0.), 1.)
804 self.assertEqual(math.pow(INF, -0.), 1.)
805 self.assertEqual(math.pow(INF, -2.), 0.)
806 self.assertEqual(math.pow(INF, -2.3), 0.)
807 self.assertEqual(math.pow(INF, -3.), 0.)
808 self.assertEqual(math.pow(INF, NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000809 self.assertTrue(math.isnan(math.pow(INF, NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000810
811 # pow(-0., x)
812 self.assertEqual(math.pow(-0., INF), 0.)
813 self.assertEqual(math.pow(-0., 3.), -0.)
814 self.assertEqual(math.pow(-0., 2.3), 0.)
815 self.assertEqual(math.pow(-0., 2.), 0.)
816 self.assertEqual(math.pow(-0., 0.), 1.)
817 self.assertEqual(math.pow(-0., -0.), 1.)
818 self.assertRaises(ValueError, math.pow, -0., -2.)
819 self.assertRaises(ValueError, math.pow, -0., -2.3)
820 self.assertRaises(ValueError, math.pow, -0., -3.)
821 self.assertRaises(ValueError, math.pow, -0., NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000822 self.assertTrue(math.isnan(math.pow(-0., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000823
824 # pow(NINF, x)
825 self.assertEqual(math.pow(NINF, INF), INF)
826 self.assertEqual(math.pow(NINF, 3.), NINF)
827 self.assertEqual(math.pow(NINF, 2.3), INF)
828 self.assertEqual(math.pow(NINF, 2.), INF)
829 self.assertEqual(math.pow(NINF, 0.), 1.)
830 self.assertEqual(math.pow(NINF, -0.), 1.)
831 self.assertEqual(math.pow(NINF, -2.), 0.)
832 self.assertEqual(math.pow(NINF, -2.3), 0.)
833 self.assertEqual(math.pow(NINF, -3.), -0.)
834 self.assertEqual(math.pow(NINF, NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000835 self.assertTrue(math.isnan(math.pow(NINF, NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000836
837 # pow(-1, x)
838 self.assertEqual(math.pow(-1., INF), 1.)
839 self.assertEqual(math.pow(-1., 3.), -1.)
840 self.assertRaises(ValueError, math.pow, -1., 2.3)
841 self.assertEqual(math.pow(-1., 2.), 1.)
842 self.assertEqual(math.pow(-1., 0.), 1.)
843 self.assertEqual(math.pow(-1., -0.), 1.)
844 self.assertEqual(math.pow(-1., -2.), 1.)
845 self.assertRaises(ValueError, math.pow, -1., -2.3)
846 self.assertEqual(math.pow(-1., -3.), -1.)
847 self.assertEqual(math.pow(-1., NINF), 1.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000848 self.assertTrue(math.isnan(math.pow(-1., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000849
850 # pow(1, x)
851 self.assertEqual(math.pow(1., INF), 1.)
852 self.assertEqual(math.pow(1., 3.), 1.)
853 self.assertEqual(math.pow(1., 2.3), 1.)
854 self.assertEqual(math.pow(1., 2.), 1.)
855 self.assertEqual(math.pow(1., 0.), 1.)
856 self.assertEqual(math.pow(1., -0.), 1.)
857 self.assertEqual(math.pow(1., -2.), 1.)
858 self.assertEqual(math.pow(1., -2.3), 1.)
859 self.assertEqual(math.pow(1., -3.), 1.)
860 self.assertEqual(math.pow(1., NINF), 1.)
861 self.assertEqual(math.pow(1., NAN), 1.)
862
863 # pow(x, 0) should be 1 for any x
864 self.assertEqual(math.pow(2.3, 0.), 1.)
865 self.assertEqual(math.pow(-2.3, 0.), 1.)
866 self.assertEqual(math.pow(NAN, 0.), 1.)
867 self.assertEqual(math.pow(2.3, -0.), 1.)
868 self.assertEqual(math.pow(-2.3, -0.), 1.)
869 self.assertEqual(math.pow(NAN, -0.), 1.)
870
871 # pow(x, y) is invalid if x is negative and y is not integral
872 self.assertRaises(ValueError, math.pow, -1., 2.3)
873 self.assertRaises(ValueError, math.pow, -15., -3.1)
874
875 # pow(x, NINF)
876 self.assertEqual(math.pow(1.9, NINF), 0.)
877 self.assertEqual(math.pow(1.1, NINF), 0.)
878 self.assertEqual(math.pow(0.9, NINF), INF)
879 self.assertEqual(math.pow(0.1, NINF), INF)
880 self.assertEqual(math.pow(-0.1, NINF), INF)
881 self.assertEqual(math.pow(-0.9, NINF), INF)
882 self.assertEqual(math.pow(-1.1, NINF), 0.)
883 self.assertEqual(math.pow(-1.9, NINF), 0.)
884
885 # pow(x, INF)
886 self.assertEqual(math.pow(1.9, INF), INF)
887 self.assertEqual(math.pow(1.1, INF), INF)
888 self.assertEqual(math.pow(0.9, INF), 0.)
889 self.assertEqual(math.pow(0.1, INF), 0.)
890 self.assertEqual(math.pow(-0.1, INF), 0.)
891 self.assertEqual(math.pow(-0.9, INF), 0.)
892 self.assertEqual(math.pow(-1.1, INF), INF)
893 self.assertEqual(math.pow(-1.9, INF), INF)
894
895 # pow(x, y) should work for x negative, y an integer
896 self.ftest('(-2.)**3.', math.pow(-2.0, 3.0), -8.0)
897 self.ftest('(-2.)**2.', math.pow(-2.0, 2.0), 4.0)
898 self.ftest('(-2.)**1.', math.pow(-2.0, 1.0), -2.0)
899 self.ftest('(-2.)**0.', math.pow(-2.0, 0.0), 1.0)
900 self.ftest('(-2.)**-0.', math.pow(-2.0, -0.0), 1.0)
901 self.ftest('(-2.)**-1.', math.pow(-2.0, -1.0), -0.5)
902 self.ftest('(-2.)**-2.', math.pow(-2.0, -2.0), 0.25)
903 self.ftest('(-2.)**-3.', math.pow(-2.0, -3.0), -0.125)
904 self.assertRaises(ValueError, math.pow, -2.0, -0.5)
905 self.assertRaises(ValueError, math.pow, -2.0, 0.5)
906
907 # the following tests have been commented out since they don't
908 # really belong here: the implementation of ** for floats is
Ezio Melotti13925002011-03-16 11:05:33 +0200909 # independent of the implementation of math.pow
Christian Heimesa342c012008-04-20 21:01:16 +0000910 #self.assertEqual(1**NAN, 1)
911 #self.assertEqual(1**INF, 1)
912 #self.assertEqual(1**NINF, 1)
913 #self.assertEqual(1**0, 1)
914 #self.assertEqual(1.**NAN, 1)
915 #self.assertEqual(1.**INF, 1)
916 #self.assertEqual(1.**NINF, 1)
917 #self.assertEqual(1.**0, 1)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000918
Thomas Wouters89f507f2006-12-13 04:49:30 +0000919 def testRadians(self):
920 self.assertRaises(TypeError, math.radians)
921 self.ftest('radians(180)', math.radians(180), math.pi)
922 self.ftest('radians(90)', math.radians(90), math.pi/2)
923 self.ftest('radians(-45)', math.radians(-45), -math.pi/4)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000924
Thomas Wouters89f507f2006-12-13 04:49:30 +0000925 def testSin(self):
926 self.assertRaises(TypeError, math.sin)
927 self.ftest('sin(0)', math.sin(0), 0)
928 self.ftest('sin(pi/2)', math.sin(math.pi/2), 1)
929 self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000930 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000931 self.assertTrue(math.isnan(math.sin(INF)))
932 self.assertTrue(math.isnan(math.sin(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +0000933 except ValueError:
934 self.assertRaises(ValueError, math.sin, INF)
935 self.assertRaises(ValueError, math.sin, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000936 self.assertTrue(math.isnan(math.sin(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000937
Thomas Wouters89f507f2006-12-13 04:49:30 +0000938 def testSinh(self):
939 self.assertRaises(TypeError, math.sinh)
940 self.ftest('sinh(0)', math.sinh(0), 0)
941 self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1)
942 self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000943 self.assertEqual(math.sinh(INF), INF)
944 self.assertEqual(math.sinh(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000945 self.assertTrue(math.isnan(math.sinh(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +0000946
Thomas Wouters89f507f2006-12-13 04:49:30 +0000947 def testSqrt(self):
948 self.assertRaises(TypeError, math.sqrt)
949 self.ftest('sqrt(0)', math.sqrt(0), 0)
950 self.ftest('sqrt(1)', math.sqrt(1), 1)
951 self.ftest('sqrt(4)', math.sqrt(4), 2)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000952 self.assertEqual(math.sqrt(INF), INF)
Christian Heimes53876d92008-04-19 00:31:39 +0000953 self.assertRaises(ValueError, math.sqrt, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000954 self.assertTrue(math.isnan(math.sqrt(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +0000955
Thomas Wouters89f507f2006-12-13 04:49:30 +0000956 def testTan(self):
957 self.assertRaises(TypeError, math.tan)
958 self.ftest('tan(0)', math.tan(0), 0)
959 self.ftest('tan(pi/4)', math.tan(math.pi/4), 1)
960 self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000961 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000962 self.assertTrue(math.isnan(math.tan(INF)))
963 self.assertTrue(math.isnan(math.tan(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +0000964 except:
965 self.assertRaises(ValueError, math.tan, INF)
966 self.assertRaises(ValueError, math.tan, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000967 self.assertTrue(math.isnan(math.tan(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +0000968
Thomas Wouters89f507f2006-12-13 04:49:30 +0000969 def testTanh(self):
970 self.assertRaises(TypeError, math.tanh)
971 self.ftest('tanh(0)', math.tanh(0), 0)
972 self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0)
Christian Heimes53876d92008-04-19 00:31:39 +0000973 self.ftest('tanh(inf)', math.tanh(INF), 1)
974 self.ftest('tanh(-inf)', math.tanh(NINF), -1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000975 self.assertTrue(math.isnan(math.tanh(NAN)))
Victor Stinnerbe3da382010-11-07 14:14:27 +0000976
977 @requires_IEEE_754
978 @unittest.skipIf(sysconfig.get_config_var('TANH_PRESERVES_ZERO_SIGN') == 0,
979 "system tanh() function doesn't copy the sign")
980 def testTanhSign(self):
Christian Heimese57950f2008-04-21 13:08:03 +0000981 # check that tanh(-0.) == -0. on IEEE 754 systems
Victor Stinnerbe3da382010-11-07 14:14:27 +0000982 self.assertEqual(math.tanh(-0.), -0.)
983 self.assertEqual(math.copysign(1., math.tanh(-0.)),
984 math.copysign(1., -0.))
Tim Peters1d120612000-10-12 06:10:25 +0000985
Christian Heimes400adb02008-02-01 08:12:03 +0000986 def test_trunc(self):
987 self.assertEqual(math.trunc(1), 1)
988 self.assertEqual(math.trunc(-1), -1)
989 self.assertEqual(type(math.trunc(1)), int)
990 self.assertEqual(type(math.trunc(1.5)), int)
991 self.assertEqual(math.trunc(1.5), 1)
992 self.assertEqual(math.trunc(-1.5), -1)
993 self.assertEqual(math.trunc(1.999999), 1)
994 self.assertEqual(math.trunc(-1.999999), -1)
995 self.assertEqual(math.trunc(-0.999999), -0)
996 self.assertEqual(math.trunc(-100.999), -100)
997
998 class TestTrunc(object):
999 def __trunc__(self):
1000 return 23
1001
1002 class TestNoTrunc(object):
1003 pass
1004
1005 self.assertEqual(math.trunc(TestTrunc()), 23)
1006
1007 self.assertRaises(TypeError, math.trunc)
1008 self.assertRaises(TypeError, math.trunc, 1, 2)
1009 self.assertRaises(TypeError, math.trunc, TestNoTrunc())
1010
Mark Dickinson8e0c9962010-07-11 17:38:24 +00001011 def testIsfinite(self):
1012 self.assertTrue(math.isfinite(0.0))
1013 self.assertTrue(math.isfinite(-0.0))
1014 self.assertTrue(math.isfinite(1.0))
1015 self.assertTrue(math.isfinite(-1.0))
1016 self.assertFalse(math.isfinite(float("nan")))
1017 self.assertFalse(math.isfinite(float("inf")))
1018 self.assertFalse(math.isfinite(float("-inf")))
1019
Christian Heimes072c0f12008-01-03 23:01:04 +00001020 def testIsnan(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001021 self.assertTrue(math.isnan(float("nan")))
1022 self.assertTrue(math.isnan(float("inf")* 0.))
1023 self.assertFalse(math.isnan(float("inf")))
1024 self.assertFalse(math.isnan(0.))
1025 self.assertFalse(math.isnan(1.))
Christian Heimes072c0f12008-01-03 23:01:04 +00001026
1027 def testIsinf(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001028 self.assertTrue(math.isinf(float("inf")))
1029 self.assertTrue(math.isinf(float("-inf")))
1030 self.assertTrue(math.isinf(1E400))
1031 self.assertTrue(math.isinf(-1E400))
1032 self.assertFalse(math.isinf(float("nan")))
1033 self.assertFalse(math.isinf(0.))
1034 self.assertFalse(math.isinf(1.))
Christian Heimes072c0f12008-01-03 23:01:04 +00001035
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +00001036 @requires_IEEE_754
1037 def test_nan_constant(self):
1038 self.assertTrue(math.isnan(math.nan))
1039
1040 @requires_IEEE_754
1041 def test_inf_constant(self):
1042 self.assertTrue(math.isinf(math.inf))
1043 self.assertGreater(math.inf, 0.0)
1044 self.assertEqual(math.inf, float("inf"))
1045 self.assertEqual(-math.inf, float("-inf"))
1046
Thomas Wouters89f507f2006-12-13 04:49:30 +00001047 # RED_FLAG 16-Oct-2000 Tim
1048 # While 2.0 is more consistent about exceptions than previous releases, it
1049 # still fails this part of the test on some platforms. For now, we only
1050 # *run* test_exceptions() in verbose mode, so that this isn't normally
1051 # tested.
Serhiy Storchaka43767632013-11-03 21:31:38 +02001052 @unittest.skipUnless(verbose, 'requires verbose mode')
1053 def test_exceptions(self):
1054 try:
1055 x = math.exp(-1000000000)
1056 except:
1057 # mathmodule.c is failing to weed out underflows from libm, or
1058 # we've got an fp format with huge dynamic range
1059 self.fail("underflowing exp() should not have raised "
1060 "an exception")
1061 if x != 0:
1062 self.fail("underflowing exp() should have returned 0")
Tim Peters98c81842000-10-16 17:35:13 +00001063
Serhiy Storchaka43767632013-11-03 21:31:38 +02001064 # If this fails, probably using a strict IEEE-754 conforming libm, and x
1065 # is +Inf afterwards. But Python wants overflows detected by default.
1066 try:
1067 x = math.exp(1000000000)
1068 except OverflowError:
1069 pass
1070 else:
1071 self.fail("overflowing exp() didn't trigger OverflowError")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001072
Serhiy Storchaka43767632013-11-03 21:31:38 +02001073 # If this fails, it could be a puzzle. One odd possibility is that
1074 # mathmodule.c's macros are getting confused while comparing
1075 # Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE
1076 # as a result (and so raising OverflowError instead).
1077 try:
1078 x = math.sqrt(-1.0)
1079 except ValueError:
1080 pass
1081 else:
1082 self.fail("sqrt(-1) didn't raise ValueError")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001083
Mark Dickinson63566232009-09-18 21:04:19 +00001084 @requires_IEEE_754
Christian Heimes53876d92008-04-19 00:31:39 +00001085 def test_testfile(self):
Christian Heimes53876d92008-04-19 00:31:39 +00001086 for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file):
1087 # Skip if either the input or result is complex, or if
1088 # flags is nonempty
1089 if ai != 0. or ei != 0. or flags:
1090 continue
1091 if fn in ['rect', 'polar']:
1092 # no real versions of rect, polar
1093 continue
1094 func = getattr(math, fn)
Christian Heimesa342c012008-04-20 21:01:16 +00001095 try:
1096 result = func(ar)
Mark Dickinsona0de26c2008-04-30 23:30:57 +00001097 except ValueError as exc:
1098 message = (("Unexpected ValueError: %s\n " +
1099 "in test %s:%s(%r)\n") % (exc.args[0], id, fn, ar))
Christian Heimesa342c012008-04-20 21:01:16 +00001100 self.fail(message)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001101 except OverflowError:
1102 message = ("Unexpected OverflowError in " +
1103 "test %s:%s(%r)\n" % (id, fn, ar))
1104 self.fail(message)
Christian Heimes53876d92008-04-19 00:31:39 +00001105 self.ftest("%s:%s(%r)" % (id, fn, ar), result, er)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001106
Victor Stinnerbe3da382010-11-07 14:14:27 +00001107 @requires_IEEE_754
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001108 def test_mtestfile(self):
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001109 fail_fmt = "{}:{}({!r}): expected {!r}, got {!r}"
1110
1111 failures = []
1112 for id, fn, arg, expected, flags in parse_mtestfile(math_testcases):
1113 func = getattr(math, fn)
1114
1115 if 'invalid' in flags or 'divide-by-zero' in flags:
1116 expected = 'ValueError'
1117 elif 'overflow' in flags:
1118 expected = 'OverflowError'
1119
1120 try:
1121 got = func(arg)
1122 except ValueError:
1123 got = 'ValueError'
1124 except OverflowError:
1125 got = 'OverflowError'
1126
Mark Dickinson05d2e082009-12-11 20:17:17 +00001127 accuracy_failure = None
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001128 if isinstance(got, float) and isinstance(expected, float):
1129 if math.isnan(expected) and math.isnan(got):
1130 continue
1131 if not math.isnan(expected) and not math.isnan(got):
Mark Dickinson664b5112009-12-16 20:23:42 +00001132 if fn == 'lgamma':
1133 # we use a weaker accuracy test for lgamma;
1134 # lgamma only achieves an absolute error of
1135 # a few multiples of the machine accuracy, in
1136 # general.
Mark Dickinson05d2e082009-12-11 20:17:17 +00001137 accuracy_failure = acc_check(expected, got,
1138 rel_err = 5e-15,
1139 abs_err = 5e-15)
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +00001140 elif fn == 'erfc':
1141 # erfc has less-than-ideal accuracy for large
1142 # arguments (x ~ 25 or so), mainly due to the
1143 # error involved in computing exp(-x*x).
1144 #
1145 # XXX Would be better to weaken this test only
1146 # for large x, instead of for all x.
1147 accuracy_failure = ulps_check(expected, got, 2000)
1148
Mark Dickinson05d2e082009-12-11 20:17:17 +00001149 else:
Mark Dickinson664b5112009-12-16 20:23:42 +00001150 accuracy_failure = ulps_check(expected, got, 20)
Mark Dickinson05d2e082009-12-11 20:17:17 +00001151 if accuracy_failure is None:
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001152 continue
1153
1154 if isinstance(got, str) and isinstance(expected, str):
1155 if got == expected:
1156 continue
1157
1158 fail_msg = fail_fmt.format(id, fn, arg, expected, got)
Mark Dickinson05d2e082009-12-11 20:17:17 +00001159 if accuracy_failure is not None:
1160 fail_msg += ' ({})'.format(accuracy_failure)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001161 failures.append(fail_msg)
1162
1163 if failures:
1164 self.fail('Failures in test_mtestfile:\n ' +
1165 '\n '.join(failures))
1166
1167
Tal Einatd5519ed2015-05-31 22:05:00 +03001168class IsCloseTests(unittest.TestCase):
1169 isclose = math.isclose # sublcasses should override this
1170
1171 def assertIsClose(self, a, b, *args, **kwargs):
1172 self.assertTrue(self.isclose(a, b, *args, **kwargs),
1173 msg="%s and %s should be close!" % (a, b))
1174
1175 def assertIsNotClose(self, a, b, *args, **kwargs):
1176 self.assertFalse(self.isclose(a, b, *args, **kwargs),
1177 msg="%s and %s should not be close!" % (a, b))
1178
1179 def assertAllClose(self, examples, *args, **kwargs):
1180 for a, b in examples:
1181 self.assertIsClose(a, b, *args, **kwargs)
1182
1183 def assertAllNotClose(self, examples, *args, **kwargs):
1184 for a, b in examples:
1185 self.assertIsNotClose(a, b, *args, **kwargs)
1186
1187 def test_negative_tolerances(self):
1188 # ValueError should be raised if either tolerance is less than zero
1189 with self.assertRaises(ValueError):
1190 self.assertIsClose(1, 1, rel_tol=-1e-100)
1191 with self.assertRaises(ValueError):
1192 self.assertIsClose(1, 1, rel_tol=1e-100, abs_tol=-1e10)
1193
1194 def test_identical(self):
1195 # identical values must test as close
1196 identical_examples = [(2.0, 2.0),
1197 (0.1e200, 0.1e200),
1198 (1.123e-300, 1.123e-300),
1199 (12345, 12345.0),
1200 (0.0, -0.0),
1201 (345678, 345678)]
1202 self.assertAllClose(identical_examples, rel_tol=0.0, abs_tol=0.0)
1203
1204 def test_eight_decimal_places(self):
1205 # examples that are close to 1e-8, but not 1e-9
1206 eight_decimal_places_examples = [(1e8, 1e8 + 1),
1207 (-1e-8, -1.000000009e-8),
1208 (1.12345678, 1.12345679)]
1209 self.assertAllClose(eight_decimal_places_examples, rel_tol=1e-8)
1210 self.assertAllNotClose(eight_decimal_places_examples, rel_tol=1e-9)
1211
1212 def test_near_zero(self):
1213 # values close to zero
1214 near_zero_examples = [(1e-9, 0.0),
1215 (-1e-9, 0.0),
1216 (-1e-150, 0.0)]
1217 # these should not be close to any rel_tol
1218 self.assertAllNotClose(near_zero_examples, rel_tol=0.9)
1219 # these should be close to abs_tol=1e-8
1220 self.assertAllClose(near_zero_examples, abs_tol=1e-8)
1221
1222 def test_identical_infinite(self):
1223 # these are close regardless of tolerance -- i.e. they are equal
1224 self.assertIsClose(INF, INF)
1225 self.assertIsClose(INF, INF, abs_tol=0.0)
1226 self.assertIsClose(NINF, NINF)
1227 self.assertIsClose(NINF, NINF, abs_tol=0.0)
1228
1229 def test_inf_ninf_nan(self):
1230 # these should never be close (following IEEE 754 rules for equality)
1231 not_close_examples = [(NAN, NAN),
1232 (NAN, 1e-100),
1233 (1e-100, NAN),
1234 (INF, NAN),
1235 (NAN, INF),
1236 (INF, NINF),
1237 (INF, 1.0),
1238 (1.0, INF),
1239 (INF, 1e308),
1240 (1e308, INF)]
1241 # use largest reasonable tolerance
1242 self.assertAllNotClose(not_close_examples, abs_tol=0.999999999999999)
1243
1244 def test_zero_tolerance(self):
1245 # test with zero tolerance
1246 zero_tolerance_close_examples = [(1.0, 1.0),
1247 (-3.4, -3.4),
1248 (-1e-300, -1e-300)]
1249 self.assertAllClose(zero_tolerance_close_examples, rel_tol=0.0)
1250
1251 zero_tolerance_not_close_examples = [(1.0, 1.000000000000001),
1252 (0.99999999999999, 1.0),
1253 (1.0e200, .999999999999999e200)]
1254 self.assertAllNotClose(zero_tolerance_not_close_examples, rel_tol=0.0)
1255
1256 def test_assymetry(self):
1257 # test the assymetry example from PEP 485
1258 self.assertAllClose([(9, 10), (10, 9)], rel_tol=0.1)
1259
1260 def test_integers(self):
1261 # test with integer values
1262 integer_examples = [(100000001, 100000000),
1263 (123456789, 123456788)]
1264
1265 self.assertAllClose(integer_examples, rel_tol=1e-8)
1266 self.assertAllNotClose(integer_examples, rel_tol=1e-9)
1267
1268 def test_decimals(self):
1269 # test with Decimal values
1270 from decimal import Decimal
1271
1272 decimal_examples = [(Decimal('1.00000001'), Decimal('1.0')),
1273 (Decimal('1.00000001e-20'), Decimal('1.0e-20')),
1274 (Decimal('1.00000001e-100'), Decimal('1.0e-100'))]
1275 self.assertAllClose(decimal_examples, rel_tol=1e-8)
1276 self.assertAllNotClose(decimal_examples, rel_tol=1e-9)
1277
1278 def test_fractions(self):
1279 # test with Fraction values
1280 from fractions import Fraction
1281
1282 # could use some more examples here!
1283 fraction_examples = [(Fraction(1, 100000000) + 1, Fraction(1))]
1284 self.assertAllClose(fraction_examples, rel_tol=1e-8)
1285 self.assertAllNotClose(fraction_examples, rel_tol=1e-9)
1286
1287
Thomas Wouters89f507f2006-12-13 04:49:30 +00001288def test_main():
Christian Heimes53876d92008-04-19 00:31:39 +00001289 from doctest import DocFileSuite
1290 suite = unittest.TestSuite()
1291 suite.addTest(unittest.makeSuite(MathTests))
Tal Einatd5519ed2015-05-31 22:05:00 +03001292 suite.addTest(unittest.makeSuite(IsCloseTests))
Christian Heimes53876d92008-04-19 00:31:39 +00001293 suite.addTest(DocFileSuite("ieee754.txt"))
1294 run_unittest(suite)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001295
1296if __name__ == '__main__':
1297 test_main()