blob: 1bbc22d0960eeff16cfbf3c49a32422280f7bfe8 [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
Thomas Wouters89f507f2006-12-13 04:49:30 +00005import unittest
6import math
Christian Heimes53876d92008-04-19 00:31:39 +00007import os
8import sys
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00009import struct
Victor Stinnerbe3da382010-11-07 14:14:27 +000010import sysconfig
Guido van Rossumfcce6301996-08-08 18:26:25 +000011
Christian Heimes53876d92008-04-19 00:31:39 +000012eps = 1E-05
13NAN = float('nan')
14INF = float('inf')
15NINF = float('-inf')
16
Mark Dickinson5c567082009-04-24 16:39:07 +000017# detect evidence of double-rounding: fsum is not always correctly
18# rounded on machines that suffer from double rounding.
19x, y = 1e16, 2.9999 # use temporary values to defeat peephole optimizer
20HAVE_DOUBLE_ROUNDING = (x + y == 1e16 + 4)
21
Christian Heimes53876d92008-04-19 00:31:39 +000022# locate file with test values
23if __name__ == '__main__':
24 file = sys.argv[0]
25else:
26 file = __file__
27test_dir = os.path.dirname(file) or os.curdir
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000028math_testcases = os.path.join(test_dir, 'math_testcases.txt')
Christian Heimes53876d92008-04-19 00:31:39 +000029test_file = os.path.join(test_dir, 'cmath_testcases.txt')
30
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000031def to_ulps(x):
32 """Convert a non-NaN float x to an integer, in such a way that
33 adjacent floats are converted to adjacent integers. Then
34 abs(ulps(x) - ulps(y)) gives the difference in ulps between two
35 floats.
36
37 The results from this function will only make sense on platforms
38 where C doubles are represented in IEEE 754 binary64 format.
39
40 """
Mark Dickinsond412ab52009-10-17 07:10:00 +000041 n = struct.unpack('<q', struct.pack('<d', x))[0]
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000042 if n < 0:
43 n = ~(n+2**63)
44 return n
45
Mark Dickinson05d2e082009-12-11 20:17:17 +000046def ulps_check(expected, got, ulps=20):
47 """Given non-NaN floats `expected` and `got`,
48 check that they're equal to within the given number of ulps.
49
50 Returns None on success and an error message on failure."""
51
52 ulps_error = to_ulps(got) - to_ulps(expected)
53 if abs(ulps_error) <= ulps:
54 return None
55 return "error = {} ulps; permitted error = {} ulps".format(ulps_error,
56 ulps)
57
Mark Dickinson4c8a9a22010-05-15 17:02:38 +000058# Here's a pure Python version of the math.factorial algorithm, for
59# documentation and comparison purposes.
60#
61# Formula:
62#
63# factorial(n) = factorial_odd_part(n) << (n - count_set_bits(n))
64#
65# where
66#
67# factorial_odd_part(n) = product_{i >= 0} product_{0 < j <= n >> i; j odd} j
68#
69# The outer product above is an infinite product, but once i >= n.bit_length,
70# (n >> i) < 1 and the corresponding term of the product is empty. So only the
71# finitely many terms for 0 <= i < n.bit_length() contribute anything.
72#
73# We iterate downwards from i == n.bit_length() - 1 to i == 0. The inner
74# product in the formula above starts at 1 for i == n.bit_length(); for each i
75# < n.bit_length() we get the inner product for i from that for i + 1 by
76# multiplying by all j in {n >> i+1 < j <= n >> i; j odd}. In Python terms,
77# this set is range((n >> i+1) + 1 | 1, (n >> i) + 1 | 1, 2).
78
79def count_set_bits(n):
80 """Number of '1' bits in binary expansion of a nonnnegative integer."""
81 return 1 + count_set_bits(n & n - 1) if n else 0
82
83def partial_product(start, stop):
84 """Product of integers in range(start, stop, 2), computed recursively.
85 start and stop should both be odd, with start <= stop.
86
87 """
88 numfactors = (stop - start) >> 1
89 if not numfactors:
90 return 1
91 elif numfactors == 1:
92 return start
93 else:
94 mid = (start + numfactors) | 1
95 return partial_product(start, mid) * partial_product(mid, stop)
96
97def py_factorial(n):
98 """Factorial of nonnegative integer n, via "Binary Split Factorial Formula"
99 described at http://www.luschny.de/math/factorial/binarysplitfact.html
100
101 """
102 inner = outer = 1
103 for i in reversed(range(n.bit_length())):
104 inner *= partial_product((n >> i + 1) + 1 | 1, (n >> i) + 1 | 1)
105 outer *= inner
106 return outer << (n - count_set_bits(n))
107
Mark Dickinson05d2e082009-12-11 20:17:17 +0000108def acc_check(expected, got, rel_err=2e-15, abs_err = 5e-323):
109 """Determine whether non-NaN floats a and b are equal to within a
110 (small) rounding error. The default values for rel_err and
111 abs_err are chosen to be suitable for platforms where a float is
112 represented by an IEEE 754 double. They allow an error of between
113 9 and 19 ulps."""
114
115 # need to special case infinities, since inf - inf gives nan
116 if math.isinf(expected) and got == expected:
117 return None
118
119 error = got - expected
120
121 permitted_error = max(abs_err, rel_err * abs(expected))
122 if abs(error) < permitted_error:
123 return None
124 return "error = {}; permitted error = {}".format(error,
125 permitted_error)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000126
127def parse_mtestfile(fname):
128 """Parse a file with test values
129
130 -- starts a comment
131 blank lines, or lines containing only a comment, are ignored
132 other lines are expected to have the form
133 id fn arg -> expected [flag]*
134
135 """
136 with open(fname) as fp:
137 for line in fp:
138 # strip comments, and skip blank lines
139 if '--' in line:
140 line = line[:line.index('--')]
141 if not line.strip():
142 continue
143
144 lhs, rhs = line.split('->')
145 id, fn, arg = lhs.split()
146 rhs_pieces = rhs.split()
147 exp = rhs_pieces[0]
148 flags = rhs_pieces[1:]
149
150 yield (id, fn, float(arg), float(exp), flags)
151
Christian Heimes53876d92008-04-19 00:31:39 +0000152def parse_testfile(fname):
153 """Parse a file with test values
154
155 Empty lines or lines starting with -- are ignored
156 yields id, fn, arg_real, arg_imag, exp_real, exp_imag
157 """
158 with open(fname) as fp:
159 for line in fp:
160 # skip comment lines and blank lines
161 if line.startswith('--') or not line.strip():
162 continue
163
164 lhs, rhs = line.split('->')
165 id, fn, arg_real, arg_imag = lhs.split()
166 rhs_pieces = rhs.split()
167 exp_real, exp_imag = rhs_pieces[0], rhs_pieces[1]
168 flags = rhs_pieces[2:]
169
170 yield (id, fn,
171 float(arg_real), float(arg_imag),
172 float(exp_real), float(exp_imag),
173 flags
174 )
Guido van Rossumfcce6301996-08-08 18:26:25 +0000175
Thomas Wouters89f507f2006-12-13 04:49:30 +0000176class MathTests(unittest.TestCase):
Guido van Rossumfcce6301996-08-08 18:26:25 +0000177
Thomas Wouters89f507f2006-12-13 04:49:30 +0000178 def ftest(self, name, value, expected):
179 if abs(value-expected) > eps:
Guido van Rossum806c2462007-08-06 23:33:07 +0000180 # Use %r instead of %f so the error message
181 # displays full precision. Otherwise discrepancies
182 # in the last few bits will lead to very confusing
183 # error messages
184 self.fail('%s returned %r, expected %r' %
Thomas Wouters89f507f2006-12-13 04:49:30 +0000185 (name, value, expected))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000186
Thomas Wouters89f507f2006-12-13 04:49:30 +0000187 def testConstants(self):
188 self.ftest('pi', math.pi, 3.1415926)
189 self.ftest('e', math.e, 2.7182818)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000190
Thomas Wouters89f507f2006-12-13 04:49:30 +0000191 def testAcos(self):
192 self.assertRaises(TypeError, math.acos)
193 self.ftest('acos(-1)', math.acos(-1), math.pi)
194 self.ftest('acos(0)', math.acos(0), math.pi/2)
195 self.ftest('acos(1)', math.acos(1), 0)
Christian Heimes53876d92008-04-19 00:31:39 +0000196 self.assertRaises(ValueError, math.acos, INF)
197 self.assertRaises(ValueError, math.acos, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000198 self.assertTrue(math.isnan(math.acos(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000199
200 def testAcosh(self):
201 self.assertRaises(TypeError, math.acosh)
202 self.ftest('acosh(1)', math.acosh(1), 0)
203 self.ftest('acosh(2)', math.acosh(2), 1.3169578969248168)
204 self.assertRaises(ValueError, math.acosh, 0)
205 self.assertRaises(ValueError, math.acosh, -1)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000206 self.assertEqual(math.acosh(INF), INF)
Christian Heimes53876d92008-04-19 00:31:39 +0000207 self.assertRaises(ValueError, math.acosh, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000208 self.assertTrue(math.isnan(math.acosh(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000209
Thomas Wouters89f507f2006-12-13 04:49:30 +0000210 def testAsin(self):
211 self.assertRaises(TypeError, math.asin)
212 self.ftest('asin(-1)', math.asin(-1), -math.pi/2)
213 self.ftest('asin(0)', math.asin(0), 0)
214 self.ftest('asin(1)', math.asin(1), math.pi/2)
Christian Heimes53876d92008-04-19 00:31:39 +0000215 self.assertRaises(ValueError, math.asin, INF)
216 self.assertRaises(ValueError, math.asin, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000217 self.assertTrue(math.isnan(math.asin(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000218
219 def testAsinh(self):
220 self.assertRaises(TypeError, math.asinh)
221 self.ftest('asinh(0)', math.asinh(0), 0)
222 self.ftest('asinh(1)', math.asinh(1), 0.88137358701954305)
223 self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000224 self.assertEqual(math.asinh(INF), INF)
225 self.assertEqual(math.asinh(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000226 self.assertTrue(math.isnan(math.asinh(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000227
Thomas Wouters89f507f2006-12-13 04:49:30 +0000228 def testAtan(self):
229 self.assertRaises(TypeError, math.atan)
230 self.ftest('atan(-1)', math.atan(-1), -math.pi/4)
231 self.ftest('atan(0)', math.atan(0), 0)
232 self.ftest('atan(1)', math.atan(1), math.pi/4)
Christian Heimes53876d92008-04-19 00:31:39 +0000233 self.ftest('atan(inf)', math.atan(INF), math.pi/2)
Christian Heimesa342c012008-04-20 21:01:16 +0000234 self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000235 self.assertTrue(math.isnan(math.atan(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000236
237 def testAtanh(self):
238 self.assertRaises(TypeError, math.atan)
239 self.ftest('atanh(0)', math.atanh(0), 0)
240 self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489)
241 self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489)
242 self.assertRaises(ValueError, math.atanh, 1)
243 self.assertRaises(ValueError, math.atanh, -1)
244 self.assertRaises(ValueError, math.atanh, INF)
245 self.assertRaises(ValueError, math.atanh, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000246 self.assertTrue(math.isnan(math.atanh(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000247
Thomas Wouters89f507f2006-12-13 04:49:30 +0000248 def testAtan2(self):
249 self.assertRaises(TypeError, math.atan2)
250 self.ftest('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2)
251 self.ftest('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4)
252 self.ftest('atan2(0, 1)', math.atan2(0, 1), 0)
253 self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4)
254 self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000255
Christian Heimese57950f2008-04-21 13:08:03 +0000256 # math.atan2(0, x)
257 self.ftest('atan2(0., -inf)', math.atan2(0., NINF), math.pi)
258 self.ftest('atan2(0., -2.3)', math.atan2(0., -2.3), math.pi)
259 self.ftest('atan2(0., -0.)', math.atan2(0., -0.), math.pi)
260 self.assertEqual(math.atan2(0., 0.), 0.)
261 self.assertEqual(math.atan2(0., 2.3), 0.)
262 self.assertEqual(math.atan2(0., INF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000263 self.assertTrue(math.isnan(math.atan2(0., NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000264 # math.atan2(-0, x)
265 self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi)
266 self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi)
267 self.ftest('atan2(-0., -0.)', math.atan2(-0., -0.), -math.pi)
268 self.assertEqual(math.atan2(-0., 0.), -0.)
269 self.assertEqual(math.atan2(-0., 2.3), -0.)
270 self.assertEqual(math.atan2(-0., INF), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000271 self.assertTrue(math.isnan(math.atan2(-0., NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000272 # math.atan2(INF, x)
273 self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4)
274 self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2)
275 self.ftest('atan2(inf, -0.)', math.atan2(INF, -0.0), math.pi/2)
276 self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2)
277 self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2)
278 self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000279 self.assertTrue(math.isnan(math.atan2(INF, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000280 # math.atan2(NINF, x)
281 self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4)
282 self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2)
283 self.ftest('atan2(-inf, -0.)', math.atan2(NINF, -0.0), -math.pi/2)
284 self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2)
285 self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2)
286 self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000287 self.assertTrue(math.isnan(math.atan2(NINF, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000288 # math.atan2(+finite, x)
289 self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi)
290 self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2)
291 self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2)
292 self.assertEqual(math.atan2(2.3, INF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000293 self.assertTrue(math.isnan(math.atan2(2.3, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000294 # math.atan2(-finite, x)
295 self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi)
296 self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2)
297 self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2)
298 self.assertEqual(math.atan2(-2.3, INF), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000299 self.assertTrue(math.isnan(math.atan2(-2.3, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000300 # math.atan2(NAN, x)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000301 self.assertTrue(math.isnan(math.atan2(NAN, NINF)))
302 self.assertTrue(math.isnan(math.atan2(NAN, -2.3)))
303 self.assertTrue(math.isnan(math.atan2(NAN, -0.)))
304 self.assertTrue(math.isnan(math.atan2(NAN, 0.)))
305 self.assertTrue(math.isnan(math.atan2(NAN, 2.3)))
306 self.assertTrue(math.isnan(math.atan2(NAN, INF)))
307 self.assertTrue(math.isnan(math.atan2(NAN, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000308
Thomas Wouters89f507f2006-12-13 04:49:30 +0000309 def testCeil(self):
310 self.assertRaises(TypeError, math.ceil)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000311 self.assertEqual(int, type(math.ceil(0.5)))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000312 self.ftest('ceil(0.5)', math.ceil(0.5), 1)
313 self.ftest('ceil(1.0)', math.ceil(1.0), 1)
314 self.ftest('ceil(1.5)', math.ceil(1.5), 2)
315 self.ftest('ceil(-0.5)', math.ceil(-0.5), 0)
316 self.ftest('ceil(-1.0)', math.ceil(-1.0), -1)
317 self.ftest('ceil(-1.5)', math.ceil(-1.5), -1)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000318 #self.assertEqual(math.ceil(INF), INF)
319 #self.assertEqual(math.ceil(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000320 #self.assertTrue(math.isnan(math.ceil(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000321
Guido van Rossum13e05de2007-08-23 22:56:55 +0000322 class TestCeil:
323 def __ceil__(self):
324 return 42
325 class TestNoCeil:
326 pass
327 self.ftest('ceil(TestCeil())', math.ceil(TestCeil()), 42)
328 self.assertRaises(TypeError, math.ceil, TestNoCeil())
329
330 t = TestNoCeil()
331 t.__ceil__ = lambda *args: args
332 self.assertRaises(TypeError, math.ceil, t)
333 self.assertRaises(TypeError, math.ceil, t, 0)
334
Mark Dickinson63566232009-09-18 21:04:19 +0000335 @requires_IEEE_754
336 def testCopysign(self):
Mark Dickinson06b59e02010-02-06 23:16:50 +0000337 self.assertEqual(math.copysign(1, 42), 1.0)
338 self.assertEqual(math.copysign(0., 42), 0.0)
339 self.assertEqual(math.copysign(1., -42), -1.0)
340 self.assertEqual(math.copysign(3, 0.), 3.0)
341 self.assertEqual(math.copysign(4., -0.), -4.0)
342
Mark Dickinson63566232009-09-18 21:04:19 +0000343 self.assertRaises(TypeError, math.copysign)
344 # copysign should let us distinguish signs of zeros
Ezio Melottib3aedd42010-11-20 19:04:17 +0000345 self.assertEqual(math.copysign(1., 0.), 1.)
346 self.assertEqual(math.copysign(1., -0.), -1.)
347 self.assertEqual(math.copysign(INF, 0.), INF)
348 self.assertEqual(math.copysign(INF, -0.), NINF)
349 self.assertEqual(math.copysign(NINF, 0.), INF)
350 self.assertEqual(math.copysign(NINF, -0.), NINF)
Mark Dickinson63566232009-09-18 21:04:19 +0000351 # and of infinities
Ezio Melottib3aedd42010-11-20 19:04:17 +0000352 self.assertEqual(math.copysign(1., INF), 1.)
353 self.assertEqual(math.copysign(1., NINF), -1.)
354 self.assertEqual(math.copysign(INF, INF), INF)
355 self.assertEqual(math.copysign(INF, NINF), NINF)
356 self.assertEqual(math.copysign(NINF, INF), INF)
357 self.assertEqual(math.copysign(NINF, NINF), NINF)
Mark Dickinson06b59e02010-02-06 23:16:50 +0000358 self.assertTrue(math.isnan(math.copysign(NAN, 1.)))
359 self.assertTrue(math.isnan(math.copysign(NAN, INF)))
360 self.assertTrue(math.isnan(math.copysign(NAN, NINF)))
361 self.assertTrue(math.isnan(math.copysign(NAN, NAN)))
Mark Dickinson63566232009-09-18 21:04:19 +0000362 # copysign(INF, NAN) may be INF or it may be NINF, since
363 # we don't know whether the sign bit of NAN is set on any
364 # given platform.
Mark Dickinson06b59e02010-02-06 23:16:50 +0000365 self.assertTrue(math.isinf(math.copysign(INF, NAN)))
Mark Dickinson63566232009-09-18 21:04:19 +0000366 # similarly, copysign(2., NAN) could be 2. or -2.
Ezio Melottib3aedd42010-11-20 19:04:17 +0000367 self.assertEqual(abs(math.copysign(2., NAN)), 2.)
Christian Heimes53876d92008-04-19 00:31:39 +0000368
Thomas Wouters89f507f2006-12-13 04:49:30 +0000369 def testCos(self):
370 self.assertRaises(TypeError, math.cos)
371 self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0)
372 self.ftest('cos(0)', math.cos(0), 1)
373 self.ftest('cos(pi/2)', math.cos(math.pi/2), 0)
374 self.ftest('cos(pi)', math.cos(math.pi), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000375 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000376 self.assertTrue(math.isnan(math.cos(INF)))
377 self.assertTrue(math.isnan(math.cos(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +0000378 except ValueError:
379 self.assertRaises(ValueError, math.cos, INF)
380 self.assertRaises(ValueError, math.cos, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000381 self.assertTrue(math.isnan(math.cos(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000382
Thomas Wouters89f507f2006-12-13 04:49:30 +0000383 def testCosh(self):
384 self.assertRaises(TypeError, math.cosh)
385 self.ftest('cosh(0)', math.cosh(0), 1)
386 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 +0000387 self.assertEqual(math.cosh(INF), INF)
388 self.assertEqual(math.cosh(NINF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000389 self.assertTrue(math.isnan(math.cosh(NAN)))
Raymond Hettinger64108af2002-05-13 03:55:01 +0000390
Thomas Wouters89f507f2006-12-13 04:49:30 +0000391 def testDegrees(self):
392 self.assertRaises(TypeError, math.degrees)
393 self.ftest('degrees(pi)', math.degrees(math.pi), 180.0)
394 self.ftest('degrees(pi/2)', math.degrees(math.pi/2), 90.0)
395 self.ftest('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000396
Thomas Wouters89f507f2006-12-13 04:49:30 +0000397 def testExp(self):
398 self.assertRaises(TypeError, math.exp)
399 self.ftest('exp(-1)', math.exp(-1), 1/math.e)
400 self.ftest('exp(0)', math.exp(0), 1)
401 self.ftest('exp(1)', math.exp(1), math.e)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000402 self.assertEqual(math.exp(INF), INF)
403 self.assertEqual(math.exp(NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000404 self.assertTrue(math.isnan(math.exp(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000405
Thomas Wouters89f507f2006-12-13 04:49:30 +0000406 def testFabs(self):
407 self.assertRaises(TypeError, math.fabs)
408 self.ftest('fabs(-1)', math.fabs(-1), 1)
409 self.ftest('fabs(0)', math.fabs(0), 0)
410 self.ftest('fabs(1)', math.fabs(1), 1)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000411
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000412 def testFactorial(self):
Mark Dickinson4c8a9a22010-05-15 17:02:38 +0000413 self.assertEqual(math.factorial(0), 1)
414 self.assertEqual(math.factorial(0.0), 1)
415 total = 1
416 for i in range(1, 1000):
417 total *= i
418 self.assertEqual(math.factorial(i), total)
419 self.assertEqual(math.factorial(float(i)), total)
420 self.assertEqual(math.factorial(i), py_factorial(i))
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000421 self.assertRaises(ValueError, math.factorial, -1)
Mark Dickinson4c8a9a22010-05-15 17:02:38 +0000422 self.assertRaises(ValueError, math.factorial, -1.0)
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000423 self.assertRaises(ValueError, math.factorial, math.pi)
Mark Dickinson4c8a9a22010-05-15 17:02:38 +0000424 self.assertRaises(OverflowError, math.factorial, sys.maxsize+1)
425 self.assertRaises(OverflowError, math.factorial, 10e100)
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000426
Thomas Wouters89f507f2006-12-13 04:49:30 +0000427 def testFloor(self):
428 self.assertRaises(TypeError, math.floor)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000429 self.assertEqual(int, type(math.floor(0.5)))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000430 self.ftest('floor(0.5)', math.floor(0.5), 0)
431 self.ftest('floor(1.0)', math.floor(1.0), 1)
432 self.ftest('floor(1.5)', math.floor(1.5), 1)
433 self.ftest('floor(-0.5)', math.floor(-0.5), -1)
434 self.ftest('floor(-1.0)', math.floor(-1.0), -1)
435 self.ftest('floor(-1.5)', math.floor(-1.5), -2)
Guido van Rossum806c2462007-08-06 23:33:07 +0000436 # pow() relies on floor() to check for integers
437 # This fails on some platforms - so check it here
438 self.ftest('floor(1.23e167)', math.floor(1.23e167), 1.23e167)
439 self.ftest('floor(-1.23e167)', math.floor(-1.23e167), -1.23e167)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000440 #self.assertEqual(math.ceil(INF), INF)
441 #self.assertEqual(math.ceil(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000442 #self.assertTrue(math.isnan(math.floor(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000443
Guido van Rossum13e05de2007-08-23 22:56:55 +0000444 class TestFloor:
445 def __floor__(self):
446 return 42
447 class TestNoFloor:
448 pass
449 self.ftest('floor(TestFloor())', math.floor(TestFloor()), 42)
450 self.assertRaises(TypeError, math.floor, TestNoFloor())
451
452 t = TestNoFloor()
453 t.__floor__ = lambda *args: args
454 self.assertRaises(TypeError, math.floor, t)
455 self.assertRaises(TypeError, math.floor, t, 0)
456
Thomas Wouters89f507f2006-12-13 04:49:30 +0000457 def testFmod(self):
458 self.assertRaises(TypeError, math.fmod)
Mark Dickinson5bc7a442011-05-03 21:13:40 +0100459 self.ftest('fmod(10, 1)', math.fmod(10, 1), 0.0)
460 self.ftest('fmod(10, 0.5)', math.fmod(10, 0.5), 0.0)
461 self.ftest('fmod(10, 1.5)', math.fmod(10, 1.5), 1.0)
462 self.ftest('fmod(-10, 1)', math.fmod(-10, 1), -0.0)
463 self.ftest('fmod(-10, 0.5)', math.fmod(-10, 0.5), -0.0)
464 self.ftest('fmod(-10, 1.5)', math.fmod(-10, 1.5), -1.0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000465 self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
466 self.assertTrue(math.isnan(math.fmod(1., NAN)))
467 self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000468 self.assertRaises(ValueError, math.fmod, 1., 0.)
469 self.assertRaises(ValueError, math.fmod, INF, 1.)
470 self.assertRaises(ValueError, math.fmod, NINF, 1.)
471 self.assertRaises(ValueError, math.fmod, INF, 0.)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000472 self.assertEqual(math.fmod(3.0, INF), 3.0)
473 self.assertEqual(math.fmod(-3.0, INF), -3.0)
474 self.assertEqual(math.fmod(3.0, NINF), 3.0)
475 self.assertEqual(math.fmod(-3.0, NINF), -3.0)
476 self.assertEqual(math.fmod(0.0, 3.0), 0.0)
477 self.assertEqual(math.fmod(0.0, NINF), 0.0)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000478
Thomas Wouters89f507f2006-12-13 04:49:30 +0000479 def testFrexp(self):
480 self.assertRaises(TypeError, math.frexp)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000481
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000482 def testfrexp(name, result, expected):
483 (mant, exp), (emant, eexp) = result, expected
Thomas Wouters89f507f2006-12-13 04:49:30 +0000484 if abs(mant-emant) > eps or exp != eexp:
485 self.fail('%s returned %r, expected %r'%\
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000486 (name, result, expected))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000487
Thomas Wouters89f507f2006-12-13 04:49:30 +0000488 testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
489 testfrexp('frexp(0)', math.frexp(0), (0, 0))
490 testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
491 testfrexp('frexp(2)', math.frexp(2), (0.5, 2))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000492
Ezio Melottib3aedd42010-11-20 19:04:17 +0000493 self.assertEqual(math.frexp(INF)[0], INF)
494 self.assertEqual(math.frexp(NINF)[0], NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000495 self.assertTrue(math.isnan(math.frexp(NAN)[0]))
Christian Heimes53876d92008-04-19 00:31:39 +0000496
Mark Dickinson63566232009-09-18 21:04:19 +0000497 @requires_IEEE_754
Mark Dickinson5c567082009-04-24 16:39:07 +0000498 @unittest.skipIf(HAVE_DOUBLE_ROUNDING,
499 "fsum is not exact on machines with double rounding")
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000500 def testFsum(self):
501 # math.fsum relies on exact rounding for correct operation.
502 # There's a known problem with IA32 floating-point that causes
503 # inexact rounding in some situations, and will cause the
504 # math.fsum tests below to fail; see issue #2937. On non IEEE
505 # 754 platforms, and on IEEE 754 platforms that exhibit the
506 # problem described in issue #2937, we simply skip the whole
507 # test.
508
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000509 # Python version of math.fsum, for comparison. Uses a
510 # different algorithm based on frexp, ldexp and integer
511 # arithmetic.
512 from sys import float_info
513 mant_dig = float_info.mant_dig
514 etiny = float_info.min_exp - mant_dig
515
516 def msum(iterable):
517 """Full precision summation. Compute sum(iterable) without any
518 intermediate accumulation of error. Based on the 'lsum' function
519 at http://code.activestate.com/recipes/393090/
520
521 """
522 tmant, texp = 0, 0
523 for x in iterable:
524 mant, exp = math.frexp(x)
525 mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig
526 if texp > exp:
527 tmant <<= texp-exp
528 texp = exp
529 else:
530 mant <<= exp-texp
531 tmant += mant
532 # Round tmant * 2**texp to a float. The original recipe
533 # used float(str(tmant)) * 2.0**texp for this, but that's
534 # a little unsafe because str -> float conversion can't be
535 # relied upon to do correct rounding on all platforms.
536 tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp)
537 if tail > 0:
538 h = 1 << (tail-1)
539 tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1)
540 texp += tail
541 return math.ldexp(tmant, texp)
542
543 test_values = [
544 ([], 0.0),
545 ([0.0], 0.0),
546 ([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100),
547 ([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0),
548 ([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0),
549 ([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0),
550 ([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0),
551 ([1./n for n in range(1, 1001)],
552 float.fromhex('0x1.df11f45f4e61ap+2')),
553 ([(-1.)**n/n for n in range(1, 1001)],
554 float.fromhex('-0x1.62a2af1bd3624p-1')),
555 ([1.7**(i+1)-1.7**i for i in range(1000)] + [-1.7**1000], -1.0),
556 ([1e16, 1., 1e-16], 10000000000000002.0),
557 ([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0),
558 # exercise code for resizing partials array
559 ([2.**n - 2.**(n+50) + 2.**(n+52) for n in range(-1074, 972, 2)] +
560 [-2.**1022],
561 float.fromhex('0x1.5555555555555p+970')),
562 ]
563
564 for i, (vals, expected) in enumerate(test_values):
565 try:
566 actual = math.fsum(vals)
567 except OverflowError:
568 self.fail("test %d failed: got OverflowError, expected %r "
569 "for math.fsum(%.100r)" % (i, expected, vals))
570 except ValueError:
571 self.fail("test %d failed: got ValueError, expected %r "
572 "for math.fsum(%.100r)" % (i, expected, vals))
573 self.assertEqual(actual, expected)
574
575 from random import random, gauss, shuffle
576 for j in range(1000):
577 vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10
578 s = 0
579 for i in range(200):
580 v = gauss(0, random()) ** 7 - s
581 s += v
582 vals.append(v)
583 shuffle(vals)
584
585 s = msum(vals)
586 self.assertEqual(msum(vals), math.fsum(vals))
587
Thomas Wouters89f507f2006-12-13 04:49:30 +0000588 def testHypot(self):
589 self.assertRaises(TypeError, math.hypot)
590 self.ftest('hypot(0,0)', math.hypot(0,0), 0)
591 self.ftest('hypot(3,4)', math.hypot(3,4), 5)
Christian Heimes53876d92008-04-19 00:31:39 +0000592 self.assertEqual(math.hypot(NAN, INF), INF)
593 self.assertEqual(math.hypot(INF, NAN), INF)
594 self.assertEqual(math.hypot(NAN, NINF), INF)
595 self.assertEqual(math.hypot(NINF, NAN), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000596 self.assertTrue(math.isnan(math.hypot(1.0, NAN)))
597 self.assertTrue(math.isnan(math.hypot(NAN, -2.0)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000598
Thomas Wouters89f507f2006-12-13 04:49:30 +0000599 def testLdexp(self):
600 self.assertRaises(TypeError, math.ldexp)
601 self.ftest('ldexp(0,1)', math.ldexp(0,1), 0)
602 self.ftest('ldexp(1,1)', math.ldexp(1,1), 2)
603 self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5)
604 self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2)
Christian Heimes53876d92008-04-19 00:31:39 +0000605 self.assertRaises(OverflowError, math.ldexp, 1., 1000000)
606 self.assertRaises(OverflowError, math.ldexp, -1., 1000000)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000607 self.assertEqual(math.ldexp(1., -1000000), 0.)
608 self.assertEqual(math.ldexp(-1., -1000000), -0.)
609 self.assertEqual(math.ldexp(INF, 30), INF)
610 self.assertEqual(math.ldexp(NINF, -213), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000611 self.assertTrue(math.isnan(math.ldexp(NAN, 0)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000612
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000613 # large second argument
614 for n in [10**5, 10**10, 10**20, 10**40]:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000615 self.assertEqual(math.ldexp(INF, -n), INF)
616 self.assertEqual(math.ldexp(NINF, -n), NINF)
617 self.assertEqual(math.ldexp(1., -n), 0.)
618 self.assertEqual(math.ldexp(-1., -n), -0.)
619 self.assertEqual(math.ldexp(0., -n), 0.)
620 self.assertEqual(math.ldexp(-0., -n), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000621 self.assertTrue(math.isnan(math.ldexp(NAN, -n)))
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000622
623 self.assertRaises(OverflowError, math.ldexp, 1., n)
624 self.assertRaises(OverflowError, math.ldexp, -1., n)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000625 self.assertEqual(math.ldexp(0., n), 0.)
626 self.assertEqual(math.ldexp(-0., n), -0.)
627 self.assertEqual(math.ldexp(INF, n), INF)
628 self.assertEqual(math.ldexp(NINF, n), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000629 self.assertTrue(math.isnan(math.ldexp(NAN, n)))
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000630
Thomas Wouters89f507f2006-12-13 04:49:30 +0000631 def testLog(self):
632 self.assertRaises(TypeError, math.log)
633 self.ftest('log(1/e)', math.log(1/math.e), -1)
634 self.ftest('log(1)', math.log(1), 0)
635 self.ftest('log(e)', math.log(math.e), 1)
636 self.ftest('log(32,2)', math.log(32,2), 5)
637 self.ftest('log(10**40, 10)', math.log(10**40, 10), 40)
638 self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2)
Mark Dickinsonc6037172010-09-29 19:06:36 +0000639 self.ftest('log(10**1000)', math.log(10**1000),
640 2302.5850929940457)
641 self.assertRaises(ValueError, math.log, -1.5)
642 self.assertRaises(ValueError, math.log, -10**1000)
Christian Heimes53876d92008-04-19 00:31:39 +0000643 self.assertRaises(ValueError, math.log, NINF)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000644 self.assertEqual(math.log(INF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000645 self.assertTrue(math.isnan(math.log(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000646
647 def testLog1p(self):
648 self.assertRaises(TypeError, math.log1p)
Christian Heimes53876d92008-04-19 00:31:39 +0000649 n= 2**90
Ezio Melottib3aedd42010-11-20 19:04:17 +0000650 self.assertAlmostEqual(math.log1p(n), math.log1p(float(n)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000651
Thomas Wouters89f507f2006-12-13 04:49:30 +0000652 def testLog10(self):
653 self.assertRaises(TypeError, math.log10)
654 self.ftest('log10(0.1)', math.log10(0.1), -1)
655 self.ftest('log10(1)', math.log10(1), 0)
656 self.ftest('log10(10)', math.log10(10), 1)
Mark Dickinsonc6037172010-09-29 19:06:36 +0000657 self.ftest('log10(10**1000)', math.log10(10**1000), 1000.0)
658 self.assertRaises(ValueError, math.log10, -1.5)
659 self.assertRaises(ValueError, math.log10, -10**1000)
Christian Heimes53876d92008-04-19 00:31:39 +0000660 self.assertRaises(ValueError, math.log10, NINF)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000661 self.assertEqual(math.log(INF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000662 self.assertTrue(math.isnan(math.log10(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000663
Thomas Wouters89f507f2006-12-13 04:49:30 +0000664 def testModf(self):
665 self.assertRaises(TypeError, math.modf)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000666
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000667 def testmodf(name, result, expected):
668 (v1, v2), (e1, e2) = result, expected
Thomas Wouters89f507f2006-12-13 04:49:30 +0000669 if abs(v1-e1) > eps or abs(v2-e2):
670 self.fail('%s returned %r, expected %r'%\
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000671 (name, result, expected))
Raymond Hettinger64108af2002-05-13 03:55:01 +0000672
Thomas Wouters89f507f2006-12-13 04:49:30 +0000673 testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
674 testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000675
Ezio Melottib3aedd42010-11-20 19:04:17 +0000676 self.assertEqual(math.modf(INF), (0.0, INF))
677 self.assertEqual(math.modf(NINF), (-0.0, NINF))
Christian Heimes53876d92008-04-19 00:31:39 +0000678
679 modf_nan = math.modf(NAN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000680 self.assertTrue(math.isnan(modf_nan[0]))
681 self.assertTrue(math.isnan(modf_nan[1]))
Christian Heimes53876d92008-04-19 00:31:39 +0000682
Thomas Wouters89f507f2006-12-13 04:49:30 +0000683 def testPow(self):
684 self.assertRaises(TypeError, math.pow)
685 self.ftest('pow(0,1)', math.pow(0,1), 0)
686 self.ftest('pow(1,0)', math.pow(1,0), 1)
687 self.ftest('pow(2,1)', math.pow(2,1), 2)
688 self.ftest('pow(2,-1)', math.pow(2,-1), 0.5)
Christian Heimes53876d92008-04-19 00:31:39 +0000689 self.assertEqual(math.pow(INF, 1), INF)
690 self.assertEqual(math.pow(NINF, 1), NINF)
691 self.assertEqual((math.pow(1, INF)), 1.)
692 self.assertEqual((math.pow(1, NINF)), 1.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000693 self.assertTrue(math.isnan(math.pow(NAN, 1)))
694 self.assertTrue(math.isnan(math.pow(2, NAN)))
695 self.assertTrue(math.isnan(math.pow(0, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000696 self.assertEqual(math.pow(1, NAN), 1)
Christian Heimesa342c012008-04-20 21:01:16 +0000697
698 # pow(0., x)
699 self.assertEqual(math.pow(0., INF), 0.)
700 self.assertEqual(math.pow(0., 3.), 0.)
701 self.assertEqual(math.pow(0., 2.3), 0.)
702 self.assertEqual(math.pow(0., 2.), 0.)
703 self.assertEqual(math.pow(0., 0.), 1.)
704 self.assertEqual(math.pow(0., -0.), 1.)
705 self.assertRaises(ValueError, math.pow, 0., -2.)
706 self.assertRaises(ValueError, math.pow, 0., -2.3)
707 self.assertRaises(ValueError, math.pow, 0., -3.)
708 self.assertRaises(ValueError, math.pow, 0., NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000709 self.assertTrue(math.isnan(math.pow(0., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000710
711 # pow(INF, x)
712 self.assertEqual(math.pow(INF, INF), INF)
713 self.assertEqual(math.pow(INF, 3.), INF)
714 self.assertEqual(math.pow(INF, 2.3), INF)
715 self.assertEqual(math.pow(INF, 2.), INF)
716 self.assertEqual(math.pow(INF, 0.), 1.)
717 self.assertEqual(math.pow(INF, -0.), 1.)
718 self.assertEqual(math.pow(INF, -2.), 0.)
719 self.assertEqual(math.pow(INF, -2.3), 0.)
720 self.assertEqual(math.pow(INF, -3.), 0.)
721 self.assertEqual(math.pow(INF, NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000722 self.assertTrue(math.isnan(math.pow(INF, NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000723
724 # pow(-0., x)
725 self.assertEqual(math.pow(-0., INF), 0.)
726 self.assertEqual(math.pow(-0., 3.), -0.)
727 self.assertEqual(math.pow(-0., 2.3), 0.)
728 self.assertEqual(math.pow(-0., 2.), 0.)
729 self.assertEqual(math.pow(-0., 0.), 1.)
730 self.assertEqual(math.pow(-0., -0.), 1.)
731 self.assertRaises(ValueError, math.pow, -0., -2.)
732 self.assertRaises(ValueError, math.pow, -0., -2.3)
733 self.assertRaises(ValueError, math.pow, -0., -3.)
734 self.assertRaises(ValueError, math.pow, -0., NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000735 self.assertTrue(math.isnan(math.pow(-0., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000736
737 # pow(NINF, x)
738 self.assertEqual(math.pow(NINF, INF), INF)
739 self.assertEqual(math.pow(NINF, 3.), NINF)
740 self.assertEqual(math.pow(NINF, 2.3), INF)
741 self.assertEqual(math.pow(NINF, 2.), INF)
742 self.assertEqual(math.pow(NINF, 0.), 1.)
743 self.assertEqual(math.pow(NINF, -0.), 1.)
744 self.assertEqual(math.pow(NINF, -2.), 0.)
745 self.assertEqual(math.pow(NINF, -2.3), 0.)
746 self.assertEqual(math.pow(NINF, -3.), -0.)
747 self.assertEqual(math.pow(NINF, NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000748 self.assertTrue(math.isnan(math.pow(NINF, NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000749
750 # pow(-1, x)
751 self.assertEqual(math.pow(-1., INF), 1.)
752 self.assertEqual(math.pow(-1., 3.), -1.)
753 self.assertRaises(ValueError, math.pow, -1., 2.3)
754 self.assertEqual(math.pow(-1., 2.), 1.)
755 self.assertEqual(math.pow(-1., 0.), 1.)
756 self.assertEqual(math.pow(-1., -0.), 1.)
757 self.assertEqual(math.pow(-1., -2.), 1.)
758 self.assertRaises(ValueError, math.pow, -1., -2.3)
759 self.assertEqual(math.pow(-1., -3.), -1.)
760 self.assertEqual(math.pow(-1., NINF), 1.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000761 self.assertTrue(math.isnan(math.pow(-1., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000762
763 # pow(1, x)
764 self.assertEqual(math.pow(1., INF), 1.)
765 self.assertEqual(math.pow(1., 3.), 1.)
766 self.assertEqual(math.pow(1., 2.3), 1.)
767 self.assertEqual(math.pow(1., 2.), 1.)
768 self.assertEqual(math.pow(1., 0.), 1.)
769 self.assertEqual(math.pow(1., -0.), 1.)
770 self.assertEqual(math.pow(1., -2.), 1.)
771 self.assertEqual(math.pow(1., -2.3), 1.)
772 self.assertEqual(math.pow(1., -3.), 1.)
773 self.assertEqual(math.pow(1., NINF), 1.)
774 self.assertEqual(math.pow(1., NAN), 1.)
775
776 # pow(x, 0) should be 1 for any x
777 self.assertEqual(math.pow(2.3, 0.), 1.)
778 self.assertEqual(math.pow(-2.3, 0.), 1.)
779 self.assertEqual(math.pow(NAN, 0.), 1.)
780 self.assertEqual(math.pow(2.3, -0.), 1.)
781 self.assertEqual(math.pow(-2.3, -0.), 1.)
782 self.assertEqual(math.pow(NAN, -0.), 1.)
783
784 # pow(x, y) is invalid if x is negative and y is not integral
785 self.assertRaises(ValueError, math.pow, -1., 2.3)
786 self.assertRaises(ValueError, math.pow, -15., -3.1)
787
788 # pow(x, NINF)
789 self.assertEqual(math.pow(1.9, NINF), 0.)
790 self.assertEqual(math.pow(1.1, NINF), 0.)
791 self.assertEqual(math.pow(0.9, NINF), INF)
792 self.assertEqual(math.pow(0.1, NINF), INF)
793 self.assertEqual(math.pow(-0.1, NINF), INF)
794 self.assertEqual(math.pow(-0.9, NINF), INF)
795 self.assertEqual(math.pow(-1.1, NINF), 0.)
796 self.assertEqual(math.pow(-1.9, NINF), 0.)
797
798 # pow(x, INF)
799 self.assertEqual(math.pow(1.9, INF), INF)
800 self.assertEqual(math.pow(1.1, INF), INF)
801 self.assertEqual(math.pow(0.9, INF), 0.)
802 self.assertEqual(math.pow(0.1, INF), 0.)
803 self.assertEqual(math.pow(-0.1, INF), 0.)
804 self.assertEqual(math.pow(-0.9, INF), 0.)
805 self.assertEqual(math.pow(-1.1, INF), INF)
806 self.assertEqual(math.pow(-1.9, INF), INF)
807
808 # pow(x, y) should work for x negative, y an integer
809 self.ftest('(-2.)**3.', math.pow(-2.0, 3.0), -8.0)
810 self.ftest('(-2.)**2.', math.pow(-2.0, 2.0), 4.0)
811 self.ftest('(-2.)**1.', math.pow(-2.0, 1.0), -2.0)
812 self.ftest('(-2.)**0.', math.pow(-2.0, 0.0), 1.0)
813 self.ftest('(-2.)**-0.', math.pow(-2.0, -0.0), 1.0)
814 self.ftest('(-2.)**-1.', math.pow(-2.0, -1.0), -0.5)
815 self.ftest('(-2.)**-2.', math.pow(-2.0, -2.0), 0.25)
816 self.ftest('(-2.)**-3.', math.pow(-2.0, -3.0), -0.125)
817 self.assertRaises(ValueError, math.pow, -2.0, -0.5)
818 self.assertRaises(ValueError, math.pow, -2.0, 0.5)
819
820 # the following tests have been commented out since they don't
821 # really belong here: the implementation of ** for floats is
Ezio Melotti13925002011-03-16 11:05:33 +0200822 # independent of the implementation of math.pow
Christian Heimesa342c012008-04-20 21:01:16 +0000823 #self.assertEqual(1**NAN, 1)
824 #self.assertEqual(1**INF, 1)
825 #self.assertEqual(1**NINF, 1)
826 #self.assertEqual(1**0, 1)
827 #self.assertEqual(1.**NAN, 1)
828 #self.assertEqual(1.**INF, 1)
829 #self.assertEqual(1.**NINF, 1)
830 #self.assertEqual(1.**0, 1)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000831
Thomas Wouters89f507f2006-12-13 04:49:30 +0000832 def testRadians(self):
833 self.assertRaises(TypeError, math.radians)
834 self.ftest('radians(180)', math.radians(180), math.pi)
835 self.ftest('radians(90)', math.radians(90), math.pi/2)
836 self.ftest('radians(-45)', math.radians(-45), -math.pi/4)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000837
Thomas Wouters89f507f2006-12-13 04:49:30 +0000838 def testSin(self):
839 self.assertRaises(TypeError, math.sin)
840 self.ftest('sin(0)', math.sin(0), 0)
841 self.ftest('sin(pi/2)', math.sin(math.pi/2), 1)
842 self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000843 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000844 self.assertTrue(math.isnan(math.sin(INF)))
845 self.assertTrue(math.isnan(math.sin(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +0000846 except ValueError:
847 self.assertRaises(ValueError, math.sin, INF)
848 self.assertRaises(ValueError, math.sin, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000849 self.assertTrue(math.isnan(math.sin(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000850
Thomas Wouters89f507f2006-12-13 04:49:30 +0000851 def testSinh(self):
852 self.assertRaises(TypeError, math.sinh)
853 self.ftest('sinh(0)', math.sinh(0), 0)
854 self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1)
855 self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000856 self.assertEqual(math.sinh(INF), INF)
857 self.assertEqual(math.sinh(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000858 self.assertTrue(math.isnan(math.sinh(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +0000859
Thomas Wouters89f507f2006-12-13 04:49:30 +0000860 def testSqrt(self):
861 self.assertRaises(TypeError, math.sqrt)
862 self.ftest('sqrt(0)', math.sqrt(0), 0)
863 self.ftest('sqrt(1)', math.sqrt(1), 1)
864 self.ftest('sqrt(4)', math.sqrt(4), 2)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000865 self.assertEqual(math.sqrt(INF), INF)
Christian Heimes53876d92008-04-19 00:31:39 +0000866 self.assertRaises(ValueError, math.sqrt, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000867 self.assertTrue(math.isnan(math.sqrt(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +0000868
Thomas Wouters89f507f2006-12-13 04:49:30 +0000869 def testTan(self):
870 self.assertRaises(TypeError, math.tan)
871 self.ftest('tan(0)', math.tan(0), 0)
872 self.ftest('tan(pi/4)', math.tan(math.pi/4), 1)
873 self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000874 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000875 self.assertTrue(math.isnan(math.tan(INF)))
876 self.assertTrue(math.isnan(math.tan(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +0000877 except:
878 self.assertRaises(ValueError, math.tan, INF)
879 self.assertRaises(ValueError, math.tan, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000880 self.assertTrue(math.isnan(math.tan(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +0000881
Thomas Wouters89f507f2006-12-13 04:49:30 +0000882 def testTanh(self):
883 self.assertRaises(TypeError, math.tanh)
884 self.ftest('tanh(0)', math.tanh(0), 0)
885 self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0)
Christian Heimes53876d92008-04-19 00:31:39 +0000886 self.ftest('tanh(inf)', math.tanh(INF), 1)
887 self.ftest('tanh(-inf)', math.tanh(NINF), -1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000888 self.assertTrue(math.isnan(math.tanh(NAN)))
Victor Stinnerbe3da382010-11-07 14:14:27 +0000889
890 @requires_IEEE_754
891 @unittest.skipIf(sysconfig.get_config_var('TANH_PRESERVES_ZERO_SIGN') == 0,
892 "system tanh() function doesn't copy the sign")
893 def testTanhSign(self):
Christian Heimese57950f2008-04-21 13:08:03 +0000894 # check that tanh(-0.) == -0. on IEEE 754 systems
Victor Stinnerbe3da382010-11-07 14:14:27 +0000895 self.assertEqual(math.tanh(-0.), -0.)
896 self.assertEqual(math.copysign(1., math.tanh(-0.)),
897 math.copysign(1., -0.))
Tim Peters1d120612000-10-12 06:10:25 +0000898
Christian Heimes400adb02008-02-01 08:12:03 +0000899 def test_trunc(self):
900 self.assertEqual(math.trunc(1), 1)
901 self.assertEqual(math.trunc(-1), -1)
902 self.assertEqual(type(math.trunc(1)), int)
903 self.assertEqual(type(math.trunc(1.5)), int)
904 self.assertEqual(math.trunc(1.5), 1)
905 self.assertEqual(math.trunc(-1.5), -1)
906 self.assertEqual(math.trunc(1.999999), 1)
907 self.assertEqual(math.trunc(-1.999999), -1)
908 self.assertEqual(math.trunc(-0.999999), -0)
909 self.assertEqual(math.trunc(-100.999), -100)
910
911 class TestTrunc(object):
912 def __trunc__(self):
913 return 23
914
915 class TestNoTrunc(object):
916 pass
917
918 self.assertEqual(math.trunc(TestTrunc()), 23)
919
920 self.assertRaises(TypeError, math.trunc)
921 self.assertRaises(TypeError, math.trunc, 1, 2)
922 self.assertRaises(TypeError, math.trunc, TestNoTrunc())
923
Mark Dickinson8e0c9962010-07-11 17:38:24 +0000924 def testIsfinite(self):
925 self.assertTrue(math.isfinite(0.0))
926 self.assertTrue(math.isfinite(-0.0))
927 self.assertTrue(math.isfinite(1.0))
928 self.assertTrue(math.isfinite(-1.0))
929 self.assertFalse(math.isfinite(float("nan")))
930 self.assertFalse(math.isfinite(float("inf")))
931 self.assertFalse(math.isfinite(float("-inf")))
932
Christian Heimes072c0f12008-01-03 23:01:04 +0000933 def testIsnan(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000934 self.assertTrue(math.isnan(float("nan")))
935 self.assertTrue(math.isnan(float("inf")* 0.))
936 self.assertFalse(math.isnan(float("inf")))
937 self.assertFalse(math.isnan(0.))
938 self.assertFalse(math.isnan(1.))
Christian Heimes072c0f12008-01-03 23:01:04 +0000939
940 def testIsinf(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000941 self.assertTrue(math.isinf(float("inf")))
942 self.assertTrue(math.isinf(float("-inf")))
943 self.assertTrue(math.isinf(1E400))
944 self.assertTrue(math.isinf(-1E400))
945 self.assertFalse(math.isinf(float("nan")))
946 self.assertFalse(math.isinf(0.))
947 self.assertFalse(math.isinf(1.))
Christian Heimes072c0f12008-01-03 23:01:04 +0000948
Thomas Wouters89f507f2006-12-13 04:49:30 +0000949 # RED_FLAG 16-Oct-2000 Tim
950 # While 2.0 is more consistent about exceptions than previous releases, it
951 # still fails this part of the test on some platforms. For now, we only
952 # *run* test_exceptions() in verbose mode, so that this isn't normally
953 # tested.
Tim Peters98c81842000-10-16 17:35:13 +0000954
Thomas Wouters89f507f2006-12-13 04:49:30 +0000955 if verbose:
956 def test_exceptions(self):
957 try:
958 x = math.exp(-1000000000)
959 except:
960 # mathmodule.c is failing to weed out underflows from libm, or
961 # we've got an fp format with huge dynamic range
962 self.fail("underflowing exp() should not have raised "
963 "an exception")
964 if x != 0:
965 self.fail("underflowing exp() should have returned 0")
966
967 # If this fails, probably using a strict IEEE-754 conforming libm, and x
968 # is +Inf afterwards. But Python wants overflows detected by default.
969 try:
970 x = math.exp(1000000000)
971 except OverflowError:
972 pass
973 else:
974 self.fail("overflowing exp() didn't trigger OverflowError")
975
976 # If this fails, it could be a puzzle. One odd possibility is that
977 # mathmodule.c's macros are getting confused while comparing
978 # Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE
979 # as a result (and so raising OverflowError instead).
980 try:
981 x = math.sqrt(-1.0)
982 except ValueError:
983 pass
984 else:
985 self.fail("sqrt(-1) didn't raise ValueError")
986
Mark Dickinson63566232009-09-18 21:04:19 +0000987 @requires_IEEE_754
Christian Heimes53876d92008-04-19 00:31:39 +0000988 def test_testfile(self):
Christian Heimes53876d92008-04-19 00:31:39 +0000989 for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file):
990 # Skip if either the input or result is complex, or if
991 # flags is nonempty
992 if ai != 0. or ei != 0. or flags:
993 continue
994 if fn in ['rect', 'polar']:
995 # no real versions of rect, polar
996 continue
997 func = getattr(math, fn)
Christian Heimesa342c012008-04-20 21:01:16 +0000998 try:
999 result = func(ar)
Mark Dickinsona0de26c2008-04-30 23:30:57 +00001000 except ValueError as exc:
1001 message = (("Unexpected ValueError: %s\n " +
1002 "in test %s:%s(%r)\n") % (exc.args[0], id, fn, ar))
Christian Heimesa342c012008-04-20 21:01:16 +00001003 self.fail(message)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001004 except OverflowError:
1005 message = ("Unexpected OverflowError in " +
1006 "test %s:%s(%r)\n" % (id, fn, ar))
1007 self.fail(message)
Christian Heimes53876d92008-04-19 00:31:39 +00001008 self.ftest("%s:%s(%r)" % (id, fn, ar), result, er)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001009
Victor Stinnerbe3da382010-11-07 14:14:27 +00001010 @requires_IEEE_754
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001011 def test_mtestfile(self):
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001012 fail_fmt = "{}:{}({!r}): expected {!r}, got {!r}"
1013
1014 failures = []
1015 for id, fn, arg, expected, flags in parse_mtestfile(math_testcases):
1016 func = getattr(math, fn)
1017
1018 if 'invalid' in flags or 'divide-by-zero' in flags:
1019 expected = 'ValueError'
1020 elif 'overflow' in flags:
1021 expected = 'OverflowError'
1022
1023 try:
1024 got = func(arg)
1025 except ValueError:
1026 got = 'ValueError'
1027 except OverflowError:
1028 got = 'OverflowError'
1029
Mark Dickinson05d2e082009-12-11 20:17:17 +00001030 accuracy_failure = None
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001031 if isinstance(got, float) and isinstance(expected, float):
1032 if math.isnan(expected) and math.isnan(got):
1033 continue
1034 if not math.isnan(expected) and not math.isnan(got):
Mark Dickinson664b5112009-12-16 20:23:42 +00001035 if fn == 'lgamma':
1036 # we use a weaker accuracy test for lgamma;
1037 # lgamma only achieves an absolute error of
1038 # a few multiples of the machine accuracy, in
1039 # general.
Mark Dickinson05d2e082009-12-11 20:17:17 +00001040 accuracy_failure = acc_check(expected, got,
1041 rel_err = 5e-15,
1042 abs_err = 5e-15)
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +00001043 elif fn == 'erfc':
1044 # erfc has less-than-ideal accuracy for large
1045 # arguments (x ~ 25 or so), mainly due to the
1046 # error involved in computing exp(-x*x).
1047 #
1048 # XXX Would be better to weaken this test only
1049 # for large x, instead of for all x.
1050 accuracy_failure = ulps_check(expected, got, 2000)
1051
Mark Dickinson05d2e082009-12-11 20:17:17 +00001052 else:
Mark Dickinson664b5112009-12-16 20:23:42 +00001053 accuracy_failure = ulps_check(expected, got, 20)
Mark Dickinson05d2e082009-12-11 20:17:17 +00001054 if accuracy_failure is None:
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001055 continue
1056
1057 if isinstance(got, str) and isinstance(expected, str):
1058 if got == expected:
1059 continue
1060
1061 fail_msg = fail_fmt.format(id, fn, arg, expected, got)
Mark Dickinson05d2e082009-12-11 20:17:17 +00001062 if accuracy_failure is not None:
1063 fail_msg += ' ({})'.format(accuracy_failure)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001064 failures.append(fail_msg)
1065
1066 if failures:
1067 self.fail('Failures in test_mtestfile:\n ' +
1068 '\n '.join(failures))
1069
1070
Thomas Wouters89f507f2006-12-13 04:49:30 +00001071def test_main():
Christian Heimes53876d92008-04-19 00:31:39 +00001072 from doctest import DocFileSuite
1073 suite = unittest.TestSuite()
1074 suite.addTest(unittest.makeSuite(MathTests))
1075 suite.addTest(DocFileSuite("ieee754.txt"))
1076 run_unittest(suite)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001077
1078if __name__ == '__main__':
1079 test_main()