blob: b7a516c7e40dd82111a566c0ecec95d382d013df [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
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004from test.support import run_unittest, verbose
Thomas Wouters89f507f2006-12-13 04:49:30 +00005import unittest
6import math
Christian Heimes53876d92008-04-19 00:31:39 +00007import os
8import sys
Georg Brandlc28e1fa2008-06-10 19:20:26 +00009import random
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 Dickinson63566232009-09-18 21:04:19 +000018# decorator for skipping tests on non-IEEE 754 platforms
19requires_IEEE_754 = unittest.skipUnless(
20 float.__getformat__("double").startswith("IEEE"),
21 "test requires IEEE 754 doubles")
22
Mark Dickinson5c567082009-04-24 16:39:07 +000023# detect evidence of double-rounding: fsum is not always correctly
24# rounded on machines that suffer from double rounding.
25x, y = 1e16, 2.9999 # use temporary values to defeat peephole optimizer
26HAVE_DOUBLE_ROUNDING = (x + y == 1e16 + 4)
27
Christian Heimes53876d92008-04-19 00:31:39 +000028# locate file with test values
29if __name__ == '__main__':
30 file = sys.argv[0]
31else:
32 file = __file__
33test_dir = os.path.dirname(file) or os.curdir
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000034math_testcases = os.path.join(test_dir, 'math_testcases.txt')
Christian Heimes53876d92008-04-19 00:31:39 +000035test_file = os.path.join(test_dir, 'cmath_testcases.txt')
36
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000037def to_ulps(x):
38 """Convert a non-NaN float x to an integer, in such a way that
39 adjacent floats are converted to adjacent integers. Then
40 abs(ulps(x) - ulps(y)) gives the difference in ulps between two
41 floats.
42
43 The results from this function will only make sense on platforms
44 where C doubles are represented in IEEE 754 binary64 format.
45
46 """
Mark Dickinsond412ab52009-10-17 07:10:00 +000047 n = struct.unpack('<q', struct.pack('<d', x))[0]
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000048 if n < 0:
49 n = ~(n+2**63)
50 return n
51
Mark Dickinson05d2e082009-12-11 20:17:17 +000052def ulps_check(expected, got, ulps=20):
53 """Given non-NaN floats `expected` and `got`,
54 check that they're equal to within the given number of ulps.
55
56 Returns None on success and an error message on failure."""
57
58 ulps_error = to_ulps(got) - to_ulps(expected)
59 if abs(ulps_error) <= ulps:
60 return None
61 return "error = {} ulps; permitted error = {} ulps".format(ulps_error,
62 ulps)
63
Mark Dickinson4c8a9a22010-05-15 17:02:38 +000064# Here's a pure Python version of the math.factorial algorithm, for
65# documentation and comparison purposes.
66#
67# Formula:
68#
69# factorial(n) = factorial_odd_part(n) << (n - count_set_bits(n))
70#
71# where
72#
73# factorial_odd_part(n) = product_{i >= 0} product_{0 < j <= n >> i; j odd} j
74#
75# The outer product above is an infinite product, but once i >= n.bit_length,
76# (n >> i) < 1 and the corresponding term of the product is empty. So only the
77# finitely many terms for 0 <= i < n.bit_length() contribute anything.
78#
79# We iterate downwards from i == n.bit_length() - 1 to i == 0. The inner
80# product in the formula above starts at 1 for i == n.bit_length(); for each i
81# < n.bit_length() we get the inner product for i from that for i + 1 by
82# multiplying by all j in {n >> i+1 < j <= n >> i; j odd}. In Python terms,
83# this set is range((n >> i+1) + 1 | 1, (n >> i) + 1 | 1, 2).
84
85def count_set_bits(n):
86 """Number of '1' bits in binary expansion of a nonnnegative integer."""
87 return 1 + count_set_bits(n & n - 1) if n else 0
88
89def partial_product(start, stop):
90 """Product of integers in range(start, stop, 2), computed recursively.
91 start and stop should both be odd, with start <= stop.
92
93 """
94 numfactors = (stop - start) >> 1
95 if not numfactors:
96 return 1
97 elif numfactors == 1:
98 return start
99 else:
100 mid = (start + numfactors) | 1
101 return partial_product(start, mid) * partial_product(mid, stop)
102
103def py_factorial(n):
104 """Factorial of nonnegative integer n, via "Binary Split Factorial Formula"
105 described at http://www.luschny.de/math/factorial/binarysplitfact.html
106
107 """
108 inner = outer = 1
109 for i in reversed(range(n.bit_length())):
110 inner *= partial_product((n >> i + 1) + 1 | 1, (n >> i) + 1 | 1)
111 outer *= inner
112 return outer << (n - count_set_bits(n))
113
Mark Dickinson05d2e082009-12-11 20:17:17 +0000114def acc_check(expected, got, rel_err=2e-15, abs_err = 5e-323):
115 """Determine whether non-NaN floats a and b are equal to within a
116 (small) rounding error. The default values for rel_err and
117 abs_err are chosen to be suitable for platforms where a float is
118 represented by an IEEE 754 double. They allow an error of between
119 9 and 19 ulps."""
120
121 # need to special case infinities, since inf - inf gives nan
122 if math.isinf(expected) and got == expected:
123 return None
124
125 error = got - expected
126
127 permitted_error = max(abs_err, rel_err * abs(expected))
128 if abs(error) < permitted_error:
129 return None
130 return "error = {}; permitted error = {}".format(error,
131 permitted_error)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000132
133def parse_mtestfile(fname):
134 """Parse a file with test values
135
136 -- starts a comment
137 blank lines, or lines containing only a comment, are ignored
138 other lines are expected to have the form
139 id fn arg -> expected [flag]*
140
141 """
142 with open(fname) as fp:
143 for line in fp:
144 # strip comments, and skip blank lines
145 if '--' in line:
146 line = line[:line.index('--')]
147 if not line.strip():
148 continue
149
150 lhs, rhs = line.split('->')
151 id, fn, arg = lhs.split()
152 rhs_pieces = rhs.split()
153 exp = rhs_pieces[0]
154 flags = rhs_pieces[1:]
155
156 yield (id, fn, float(arg), float(exp), flags)
157
Christian Heimes53876d92008-04-19 00:31:39 +0000158def parse_testfile(fname):
159 """Parse a file with test values
160
161 Empty lines or lines starting with -- are ignored
162 yields id, fn, arg_real, arg_imag, exp_real, exp_imag
163 """
164 with open(fname) as fp:
165 for line in fp:
166 # skip comment lines and blank lines
167 if line.startswith('--') or not line.strip():
168 continue
169
170 lhs, rhs = line.split('->')
171 id, fn, arg_real, arg_imag = lhs.split()
172 rhs_pieces = rhs.split()
173 exp_real, exp_imag = rhs_pieces[0], rhs_pieces[1]
174 flags = rhs_pieces[2:]
175
176 yield (id, fn,
177 float(arg_real), float(arg_imag),
178 float(exp_real), float(exp_imag),
179 flags
180 )
Guido van Rossumfcce6301996-08-08 18:26:25 +0000181
Thomas Wouters89f507f2006-12-13 04:49:30 +0000182class MathTests(unittest.TestCase):
Guido van Rossumfcce6301996-08-08 18:26:25 +0000183
Thomas Wouters89f507f2006-12-13 04:49:30 +0000184 def ftest(self, name, value, expected):
185 if abs(value-expected) > eps:
Guido van Rossum806c2462007-08-06 23:33:07 +0000186 # Use %r instead of %f so the error message
187 # displays full precision. Otherwise discrepancies
188 # in the last few bits will lead to very confusing
189 # error messages
190 self.fail('%s returned %r, expected %r' %
Thomas Wouters89f507f2006-12-13 04:49:30 +0000191 (name, value, expected))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000192
Thomas Wouters89f507f2006-12-13 04:49:30 +0000193 def testConstants(self):
194 self.ftest('pi', math.pi, 3.1415926)
195 self.ftest('e', math.e, 2.7182818)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000196
Thomas Wouters89f507f2006-12-13 04:49:30 +0000197 def testAcos(self):
198 self.assertRaises(TypeError, math.acos)
199 self.ftest('acos(-1)', math.acos(-1), math.pi)
200 self.ftest('acos(0)', math.acos(0), math.pi/2)
201 self.ftest('acos(1)', math.acos(1), 0)
Christian Heimes53876d92008-04-19 00:31:39 +0000202 self.assertRaises(ValueError, math.acos, INF)
203 self.assertRaises(ValueError, math.acos, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000204 self.assertTrue(math.isnan(math.acos(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000205
206 def testAcosh(self):
207 self.assertRaises(TypeError, math.acosh)
208 self.ftest('acosh(1)', math.acosh(1), 0)
209 self.ftest('acosh(2)', math.acosh(2), 1.3169578969248168)
210 self.assertRaises(ValueError, math.acosh, 0)
211 self.assertRaises(ValueError, math.acosh, -1)
212 self.assertEquals(math.acosh(INF), INF)
213 self.assertRaises(ValueError, math.acosh, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000214 self.assertTrue(math.isnan(math.acosh(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000215
Thomas Wouters89f507f2006-12-13 04:49:30 +0000216 def testAsin(self):
217 self.assertRaises(TypeError, math.asin)
218 self.ftest('asin(-1)', math.asin(-1), -math.pi/2)
219 self.ftest('asin(0)', math.asin(0), 0)
220 self.ftest('asin(1)', math.asin(1), math.pi/2)
Christian Heimes53876d92008-04-19 00:31:39 +0000221 self.assertRaises(ValueError, math.asin, INF)
222 self.assertRaises(ValueError, math.asin, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000223 self.assertTrue(math.isnan(math.asin(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000224
225 def testAsinh(self):
226 self.assertRaises(TypeError, math.asinh)
227 self.ftest('asinh(0)', math.asinh(0), 0)
228 self.ftest('asinh(1)', math.asinh(1), 0.88137358701954305)
229 self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305)
230 self.assertEquals(math.asinh(INF), INF)
231 self.assertEquals(math.asinh(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000232 self.assertTrue(math.isnan(math.asinh(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000233
Thomas Wouters89f507f2006-12-13 04:49:30 +0000234 def testAtan(self):
235 self.assertRaises(TypeError, math.atan)
236 self.ftest('atan(-1)', math.atan(-1), -math.pi/4)
237 self.ftest('atan(0)', math.atan(0), 0)
238 self.ftest('atan(1)', math.atan(1), math.pi/4)
Christian Heimes53876d92008-04-19 00:31:39 +0000239 self.ftest('atan(inf)', math.atan(INF), math.pi/2)
Christian Heimesa342c012008-04-20 21:01:16 +0000240 self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000241 self.assertTrue(math.isnan(math.atan(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000242
243 def testAtanh(self):
244 self.assertRaises(TypeError, math.atan)
245 self.ftest('atanh(0)', math.atanh(0), 0)
246 self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489)
247 self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489)
248 self.assertRaises(ValueError, math.atanh, 1)
249 self.assertRaises(ValueError, math.atanh, -1)
250 self.assertRaises(ValueError, math.atanh, INF)
251 self.assertRaises(ValueError, math.atanh, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000252 self.assertTrue(math.isnan(math.atanh(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000253
Thomas Wouters89f507f2006-12-13 04:49:30 +0000254 def testAtan2(self):
255 self.assertRaises(TypeError, math.atan2)
256 self.ftest('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2)
257 self.ftest('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4)
258 self.ftest('atan2(0, 1)', math.atan2(0, 1), 0)
259 self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4)
260 self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000261
Christian Heimese57950f2008-04-21 13:08:03 +0000262 # math.atan2(0, x)
263 self.ftest('atan2(0., -inf)', math.atan2(0., NINF), math.pi)
264 self.ftest('atan2(0., -2.3)', math.atan2(0., -2.3), math.pi)
265 self.ftest('atan2(0., -0.)', math.atan2(0., -0.), math.pi)
266 self.assertEqual(math.atan2(0., 0.), 0.)
267 self.assertEqual(math.atan2(0., 2.3), 0.)
268 self.assertEqual(math.atan2(0., INF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000269 self.assertTrue(math.isnan(math.atan2(0., NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000270 # math.atan2(-0, x)
271 self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi)
272 self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi)
273 self.ftest('atan2(-0., -0.)', math.atan2(-0., -0.), -math.pi)
274 self.assertEqual(math.atan2(-0., 0.), -0.)
275 self.assertEqual(math.atan2(-0., 2.3), -0.)
276 self.assertEqual(math.atan2(-0., INF), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000277 self.assertTrue(math.isnan(math.atan2(-0., NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000278 # math.atan2(INF, x)
279 self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4)
280 self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2)
281 self.ftest('atan2(inf, -0.)', math.atan2(INF, -0.0), math.pi/2)
282 self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2)
283 self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2)
284 self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000285 self.assertTrue(math.isnan(math.atan2(INF, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000286 # math.atan2(NINF, x)
287 self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4)
288 self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2)
289 self.ftest('atan2(-inf, -0.)', math.atan2(NINF, -0.0), -math.pi/2)
290 self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2)
291 self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2)
292 self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000293 self.assertTrue(math.isnan(math.atan2(NINF, 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(-finite, x)
301 self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi)
302 self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2)
303 self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2)
304 self.assertEqual(math.atan2(-2.3, INF), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000305 self.assertTrue(math.isnan(math.atan2(-2.3, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000306 # math.atan2(NAN, x)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000307 self.assertTrue(math.isnan(math.atan2(NAN, NINF)))
308 self.assertTrue(math.isnan(math.atan2(NAN, -2.3)))
309 self.assertTrue(math.isnan(math.atan2(NAN, -0.)))
310 self.assertTrue(math.isnan(math.atan2(NAN, 0.)))
311 self.assertTrue(math.isnan(math.atan2(NAN, 2.3)))
312 self.assertTrue(math.isnan(math.atan2(NAN, INF)))
313 self.assertTrue(math.isnan(math.atan2(NAN, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000314
Thomas Wouters89f507f2006-12-13 04:49:30 +0000315 def testCeil(self):
316 self.assertRaises(TypeError, math.ceil)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000317 self.assertEquals(int, type(math.ceil(0.5)))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000318 self.ftest('ceil(0.5)', math.ceil(0.5), 1)
319 self.ftest('ceil(1.0)', math.ceil(1.0), 1)
320 self.ftest('ceil(1.5)', math.ceil(1.5), 2)
321 self.ftest('ceil(-0.5)', math.ceil(-0.5), 0)
322 self.ftest('ceil(-1.0)', math.ceil(-1.0), -1)
323 self.ftest('ceil(-1.5)', math.ceil(-1.5), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000324 #self.assertEquals(math.ceil(INF), INF)
325 #self.assertEquals(math.ceil(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000326 #self.assertTrue(math.isnan(math.ceil(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000327
Guido van Rossum13e05de2007-08-23 22:56:55 +0000328 class TestCeil:
329 def __ceil__(self):
330 return 42
331 class TestNoCeil:
332 pass
333 self.ftest('ceil(TestCeil())', math.ceil(TestCeil()), 42)
334 self.assertRaises(TypeError, math.ceil, TestNoCeil())
335
336 t = TestNoCeil()
337 t.__ceil__ = lambda *args: args
338 self.assertRaises(TypeError, math.ceil, t)
339 self.assertRaises(TypeError, math.ceil, t, 0)
340
Mark Dickinson63566232009-09-18 21:04:19 +0000341 @requires_IEEE_754
342 def testCopysign(self):
Mark Dickinson06b59e02010-02-06 23:16:50 +0000343 self.assertEqual(math.copysign(1, 42), 1.0)
344 self.assertEqual(math.copysign(0., 42), 0.0)
345 self.assertEqual(math.copysign(1., -42), -1.0)
346 self.assertEqual(math.copysign(3, 0.), 3.0)
347 self.assertEqual(math.copysign(4., -0.), -4.0)
348
Mark Dickinson63566232009-09-18 21:04:19 +0000349 self.assertRaises(TypeError, math.copysign)
350 # copysign should let us distinguish signs of zeros
Mark Dickinson06b59e02010-02-06 23:16:50 +0000351 self.assertEquals(math.copysign(1., 0.), 1.)
352 self.assertEquals(math.copysign(1., -0.), -1.)
353 self.assertEquals(math.copysign(INF, 0.), INF)
354 self.assertEquals(math.copysign(INF, -0.), NINF)
355 self.assertEquals(math.copysign(NINF, 0.), INF)
356 self.assertEquals(math.copysign(NINF, -0.), NINF)
Mark Dickinson63566232009-09-18 21:04:19 +0000357 # and of infinities
Mark Dickinson06b59e02010-02-06 23:16:50 +0000358 self.assertEquals(math.copysign(1., INF), 1.)
359 self.assertEquals(math.copysign(1., NINF), -1.)
360 self.assertEquals(math.copysign(INF, INF), INF)
361 self.assertEquals(math.copysign(INF, NINF), NINF)
362 self.assertEquals(math.copysign(NINF, INF), INF)
363 self.assertEquals(math.copysign(NINF, NINF), NINF)
364 self.assertTrue(math.isnan(math.copysign(NAN, 1.)))
365 self.assertTrue(math.isnan(math.copysign(NAN, INF)))
366 self.assertTrue(math.isnan(math.copysign(NAN, NINF)))
367 self.assertTrue(math.isnan(math.copysign(NAN, NAN)))
Mark Dickinson63566232009-09-18 21:04:19 +0000368 # copysign(INF, NAN) may be INF or it may be NINF, since
369 # we don't know whether the sign bit of NAN is set on any
370 # given platform.
Mark Dickinson06b59e02010-02-06 23:16:50 +0000371 self.assertTrue(math.isinf(math.copysign(INF, NAN)))
Mark Dickinson63566232009-09-18 21:04:19 +0000372 # similarly, copysign(2., NAN) could be 2. or -2.
Mark Dickinson06b59e02010-02-06 23:16:50 +0000373 self.assertEquals(abs(math.copysign(2., NAN)), 2.)
Christian Heimes53876d92008-04-19 00:31:39 +0000374
Thomas Wouters89f507f2006-12-13 04:49:30 +0000375 def testCos(self):
376 self.assertRaises(TypeError, math.cos)
377 self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0)
378 self.ftest('cos(0)', math.cos(0), 1)
379 self.ftest('cos(pi/2)', math.cos(math.pi/2), 0)
380 self.ftest('cos(pi)', math.cos(math.pi), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000381 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000382 self.assertTrue(math.isnan(math.cos(INF)))
383 self.assertTrue(math.isnan(math.cos(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +0000384 except ValueError:
385 self.assertRaises(ValueError, math.cos, INF)
386 self.assertRaises(ValueError, math.cos, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000387 self.assertTrue(math.isnan(math.cos(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000388
Thomas Wouters89f507f2006-12-13 04:49:30 +0000389 def testCosh(self):
390 self.assertRaises(TypeError, math.cosh)
391 self.ftest('cosh(0)', math.cosh(0), 1)
392 self.ftest('cosh(2)-2*cosh(1)**2', math.cosh(2)-2*math.cosh(1)**2, -1) # Thanks to Lambert
Christian Heimes53876d92008-04-19 00:31:39 +0000393 self.assertEquals(math.cosh(INF), INF)
394 self.assertEquals(math.cosh(NINF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000395 self.assertTrue(math.isnan(math.cosh(NAN)))
Raymond Hettinger64108af2002-05-13 03:55:01 +0000396
Thomas Wouters89f507f2006-12-13 04:49:30 +0000397 def testDegrees(self):
398 self.assertRaises(TypeError, math.degrees)
399 self.ftest('degrees(pi)', math.degrees(math.pi), 180.0)
400 self.ftest('degrees(pi/2)', math.degrees(math.pi/2), 90.0)
401 self.ftest('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000402
Thomas Wouters89f507f2006-12-13 04:49:30 +0000403 def testExp(self):
404 self.assertRaises(TypeError, math.exp)
405 self.ftest('exp(-1)', math.exp(-1), 1/math.e)
406 self.ftest('exp(0)', math.exp(0), 1)
407 self.ftest('exp(1)', math.exp(1), math.e)
Christian Heimes53876d92008-04-19 00:31:39 +0000408 self.assertEquals(math.exp(INF), INF)
409 self.assertEquals(math.exp(NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000410 self.assertTrue(math.isnan(math.exp(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000411
Thomas Wouters89f507f2006-12-13 04:49:30 +0000412 def testFabs(self):
413 self.assertRaises(TypeError, math.fabs)
414 self.ftest('fabs(-1)', math.fabs(-1), 1)
415 self.ftest('fabs(0)', math.fabs(0), 0)
416 self.ftest('fabs(1)', math.fabs(1), 1)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000417
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000418 def testFactorial(self):
Mark Dickinson4c8a9a22010-05-15 17:02:38 +0000419 self.assertEqual(math.factorial(0), 1)
420 self.assertEqual(math.factorial(0.0), 1)
421 total = 1
422 for i in range(1, 1000):
423 total *= i
424 self.assertEqual(math.factorial(i), total)
425 self.assertEqual(math.factorial(float(i)), total)
426 self.assertEqual(math.factorial(i), py_factorial(i))
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000427 self.assertRaises(ValueError, math.factorial, -1)
Mark Dickinson4c8a9a22010-05-15 17:02:38 +0000428 self.assertRaises(ValueError, math.factorial, -1.0)
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000429 self.assertRaises(ValueError, math.factorial, math.pi)
Mark Dickinson4c8a9a22010-05-15 17:02:38 +0000430 self.assertRaises(OverflowError, math.factorial, sys.maxsize+1)
431 self.assertRaises(OverflowError, math.factorial, 10e100)
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000432
Thomas Wouters89f507f2006-12-13 04:49:30 +0000433 def testFloor(self):
434 self.assertRaises(TypeError, math.floor)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000435 self.assertEquals(int, type(math.floor(0.5)))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000436 self.ftest('floor(0.5)', math.floor(0.5), 0)
437 self.ftest('floor(1.0)', math.floor(1.0), 1)
438 self.ftest('floor(1.5)', math.floor(1.5), 1)
439 self.ftest('floor(-0.5)', math.floor(-0.5), -1)
440 self.ftest('floor(-1.0)', math.floor(-1.0), -1)
441 self.ftest('floor(-1.5)', math.floor(-1.5), -2)
Guido van Rossum806c2462007-08-06 23:33:07 +0000442 # pow() relies on floor() to check for integers
443 # This fails on some platforms - so check it here
444 self.ftest('floor(1.23e167)', math.floor(1.23e167), 1.23e167)
445 self.ftest('floor(-1.23e167)', math.floor(-1.23e167), -1.23e167)
Christian Heimes53876d92008-04-19 00:31:39 +0000446 #self.assertEquals(math.ceil(INF), INF)
447 #self.assertEquals(math.ceil(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000448 #self.assertTrue(math.isnan(math.floor(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000449
Guido van Rossum13e05de2007-08-23 22:56:55 +0000450 class TestFloor:
451 def __floor__(self):
452 return 42
453 class TestNoFloor:
454 pass
455 self.ftest('floor(TestFloor())', math.floor(TestFloor()), 42)
456 self.assertRaises(TypeError, math.floor, TestNoFloor())
457
458 t = TestNoFloor()
459 t.__floor__ = lambda *args: args
460 self.assertRaises(TypeError, math.floor, t)
461 self.assertRaises(TypeError, math.floor, t, 0)
462
Thomas Wouters89f507f2006-12-13 04:49:30 +0000463 def testFmod(self):
464 self.assertRaises(TypeError, math.fmod)
465 self.ftest('fmod(10,1)', math.fmod(10,1), 0)
466 self.ftest('fmod(10,0.5)', math.fmod(10,0.5), 0)
467 self.ftest('fmod(10,1.5)', math.fmod(10,1.5), 1)
468 self.ftest('fmod(-10,1)', math.fmod(-10,1), 0)
469 self.ftest('fmod(-10,0.5)', math.fmod(-10,0.5), 0)
470 self.ftest('fmod(-10,1.5)', math.fmod(-10,1.5), -1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000471 self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
472 self.assertTrue(math.isnan(math.fmod(1., NAN)))
473 self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000474 self.assertRaises(ValueError, math.fmod, 1., 0.)
475 self.assertRaises(ValueError, math.fmod, INF, 1.)
476 self.assertRaises(ValueError, math.fmod, NINF, 1.)
477 self.assertRaises(ValueError, math.fmod, INF, 0.)
478 self.assertEquals(math.fmod(3.0, INF), 3.0)
479 self.assertEquals(math.fmod(-3.0, INF), -3.0)
480 self.assertEquals(math.fmod(3.0, NINF), 3.0)
481 self.assertEquals(math.fmod(-3.0, NINF), -3.0)
482 self.assertEquals(math.fmod(0.0, 3.0), 0.0)
483 self.assertEquals(math.fmod(0.0, NINF), 0.0)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000484
Thomas Wouters89f507f2006-12-13 04:49:30 +0000485 def testFrexp(self):
486 self.assertRaises(TypeError, math.frexp)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000487
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000488 def testfrexp(name, result, expected):
489 (mant, exp), (emant, eexp) = result, expected
Thomas Wouters89f507f2006-12-13 04:49:30 +0000490 if abs(mant-emant) > eps or exp != eexp:
491 self.fail('%s returned %r, expected %r'%\
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000492 (name, result, expected))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000493
Thomas Wouters89f507f2006-12-13 04:49:30 +0000494 testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
495 testfrexp('frexp(0)', math.frexp(0), (0, 0))
496 testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
497 testfrexp('frexp(2)', math.frexp(2), (0.5, 2))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000498
Christian Heimes53876d92008-04-19 00:31:39 +0000499 self.assertEquals(math.frexp(INF)[0], INF)
500 self.assertEquals(math.frexp(NINF)[0], NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000501 self.assertTrue(math.isnan(math.frexp(NAN)[0]))
Christian Heimes53876d92008-04-19 00:31:39 +0000502
Mark Dickinson63566232009-09-18 21:04:19 +0000503 @requires_IEEE_754
Mark Dickinson5c567082009-04-24 16:39:07 +0000504 @unittest.skipIf(HAVE_DOUBLE_ROUNDING,
505 "fsum is not exact on machines with double rounding")
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000506 def testFsum(self):
507 # math.fsum relies on exact rounding for correct operation.
508 # There's a known problem with IA32 floating-point that causes
509 # inexact rounding in some situations, and will cause the
510 # math.fsum tests below to fail; see issue #2937. On non IEEE
511 # 754 platforms, and on IEEE 754 platforms that exhibit the
512 # problem described in issue #2937, we simply skip the whole
513 # test.
514
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000515 # Python version of math.fsum, for comparison. Uses a
516 # different algorithm based on frexp, ldexp and integer
517 # arithmetic.
518 from sys import float_info
519 mant_dig = float_info.mant_dig
520 etiny = float_info.min_exp - mant_dig
521
522 def msum(iterable):
523 """Full precision summation. Compute sum(iterable) without any
524 intermediate accumulation of error. Based on the 'lsum' function
525 at http://code.activestate.com/recipes/393090/
526
527 """
528 tmant, texp = 0, 0
529 for x in iterable:
530 mant, exp = math.frexp(x)
531 mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig
532 if texp > exp:
533 tmant <<= texp-exp
534 texp = exp
535 else:
536 mant <<= exp-texp
537 tmant += mant
538 # Round tmant * 2**texp to a float. The original recipe
539 # used float(str(tmant)) * 2.0**texp for this, but that's
540 # a little unsafe because str -> float conversion can't be
541 # relied upon to do correct rounding on all platforms.
542 tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp)
543 if tail > 0:
544 h = 1 << (tail-1)
545 tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1)
546 texp += tail
547 return math.ldexp(tmant, texp)
548
549 test_values = [
550 ([], 0.0),
551 ([0.0], 0.0),
552 ([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100),
553 ([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0),
554 ([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0),
555 ([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0),
556 ([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0),
557 ([1./n for n in range(1, 1001)],
558 float.fromhex('0x1.df11f45f4e61ap+2')),
559 ([(-1.)**n/n for n in range(1, 1001)],
560 float.fromhex('-0x1.62a2af1bd3624p-1')),
561 ([1.7**(i+1)-1.7**i for i in range(1000)] + [-1.7**1000], -1.0),
562 ([1e16, 1., 1e-16], 10000000000000002.0),
563 ([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0),
564 # exercise code for resizing partials array
565 ([2.**n - 2.**(n+50) + 2.**(n+52) for n in range(-1074, 972, 2)] +
566 [-2.**1022],
567 float.fromhex('0x1.5555555555555p+970')),
568 ]
569
570 for i, (vals, expected) in enumerate(test_values):
571 try:
572 actual = math.fsum(vals)
573 except OverflowError:
574 self.fail("test %d failed: got OverflowError, expected %r "
575 "for math.fsum(%.100r)" % (i, expected, vals))
576 except ValueError:
577 self.fail("test %d failed: got ValueError, expected %r "
578 "for math.fsum(%.100r)" % (i, expected, vals))
579 self.assertEqual(actual, expected)
580
581 from random import random, gauss, shuffle
582 for j in range(1000):
583 vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10
584 s = 0
585 for i in range(200):
586 v = gauss(0, random()) ** 7 - s
587 s += v
588 vals.append(v)
589 shuffle(vals)
590
591 s = msum(vals)
592 self.assertEqual(msum(vals), math.fsum(vals))
593
Thomas Wouters89f507f2006-12-13 04:49:30 +0000594 def testHypot(self):
595 self.assertRaises(TypeError, math.hypot)
596 self.ftest('hypot(0,0)', math.hypot(0,0), 0)
597 self.ftest('hypot(3,4)', math.hypot(3,4), 5)
Christian Heimes53876d92008-04-19 00:31:39 +0000598 self.assertEqual(math.hypot(NAN, INF), INF)
599 self.assertEqual(math.hypot(INF, NAN), INF)
600 self.assertEqual(math.hypot(NAN, NINF), INF)
601 self.assertEqual(math.hypot(NINF, NAN), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000602 self.assertTrue(math.isnan(math.hypot(1.0, NAN)))
603 self.assertTrue(math.isnan(math.hypot(NAN, -2.0)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000604
Thomas Wouters89f507f2006-12-13 04:49:30 +0000605 def testLdexp(self):
606 self.assertRaises(TypeError, math.ldexp)
607 self.ftest('ldexp(0,1)', math.ldexp(0,1), 0)
608 self.ftest('ldexp(1,1)', math.ldexp(1,1), 2)
609 self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5)
610 self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2)
Christian Heimes53876d92008-04-19 00:31:39 +0000611 self.assertRaises(OverflowError, math.ldexp, 1., 1000000)
612 self.assertRaises(OverflowError, math.ldexp, -1., 1000000)
613 self.assertEquals(math.ldexp(1., -1000000), 0.)
614 self.assertEquals(math.ldexp(-1., -1000000), -0.)
615 self.assertEquals(math.ldexp(INF, 30), INF)
616 self.assertEquals(math.ldexp(NINF, -213), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000617 self.assertTrue(math.isnan(math.ldexp(NAN, 0)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000618
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000619 # large second argument
620 for n in [10**5, 10**10, 10**20, 10**40]:
621 self.assertEquals(math.ldexp(INF, -n), INF)
622 self.assertEquals(math.ldexp(NINF, -n), NINF)
623 self.assertEquals(math.ldexp(1., -n), 0.)
624 self.assertEquals(math.ldexp(-1., -n), -0.)
625 self.assertEquals(math.ldexp(0., -n), 0.)
626 self.assertEquals(math.ldexp(-0., -n), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000627 self.assertTrue(math.isnan(math.ldexp(NAN, -n)))
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000628
629 self.assertRaises(OverflowError, math.ldexp, 1., n)
630 self.assertRaises(OverflowError, math.ldexp, -1., n)
631 self.assertEquals(math.ldexp(0., n), 0.)
632 self.assertEquals(math.ldexp(-0., n), -0.)
633 self.assertEquals(math.ldexp(INF, n), INF)
634 self.assertEquals(math.ldexp(NINF, n), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000635 self.assertTrue(math.isnan(math.ldexp(NAN, n)))
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000636
Thomas Wouters89f507f2006-12-13 04:49:30 +0000637 def testLog(self):
638 self.assertRaises(TypeError, math.log)
639 self.ftest('log(1/e)', math.log(1/math.e), -1)
640 self.ftest('log(1)', math.log(1), 0)
641 self.ftest('log(e)', math.log(math.e), 1)
642 self.ftest('log(32,2)', math.log(32,2), 5)
643 self.ftest('log(10**40, 10)', math.log(10**40, 10), 40)
644 self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2)
Mark Dickinsonc6037172010-09-29 19:06:36 +0000645 self.ftest('log(10**1000)', math.log(10**1000),
646 2302.5850929940457)
647 self.assertRaises(ValueError, math.log, -1.5)
648 self.assertRaises(ValueError, math.log, -10**1000)
Christian Heimes53876d92008-04-19 00:31:39 +0000649 self.assertRaises(ValueError, math.log, NINF)
Mark Dickinsonc6037172010-09-29 19:06:36 +0000650 self.assertEquals(math.log(INF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000651 self.assertTrue(math.isnan(math.log(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000652
653 def testLog1p(self):
654 self.assertRaises(TypeError, math.log1p)
Christian Heimes53876d92008-04-19 00:31:39 +0000655 n= 2**90
Christian Heimes53876d92008-04-19 00:31:39 +0000656 self.assertAlmostEquals(math.log1p(n), math.log1p(float(n)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000657
Thomas Wouters89f507f2006-12-13 04:49:30 +0000658 def testLog10(self):
659 self.assertRaises(TypeError, math.log10)
660 self.ftest('log10(0.1)', math.log10(0.1), -1)
661 self.ftest('log10(1)', math.log10(1), 0)
662 self.ftest('log10(10)', math.log10(10), 1)
Mark Dickinsonc6037172010-09-29 19:06:36 +0000663 self.ftest('log10(10**1000)', math.log10(10**1000), 1000.0)
664 self.assertRaises(ValueError, math.log10, -1.5)
665 self.assertRaises(ValueError, math.log10, -10**1000)
Christian Heimes53876d92008-04-19 00:31:39 +0000666 self.assertRaises(ValueError, math.log10, NINF)
Mark Dickinsonc6037172010-09-29 19:06:36 +0000667 self.assertEquals(math.log(INF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000668 self.assertTrue(math.isnan(math.log10(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000669
Thomas Wouters89f507f2006-12-13 04:49:30 +0000670 def testModf(self):
671 self.assertRaises(TypeError, math.modf)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000672
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000673 def testmodf(name, result, expected):
674 (v1, v2), (e1, e2) = result, expected
Thomas Wouters89f507f2006-12-13 04:49:30 +0000675 if abs(v1-e1) > eps or abs(v2-e2):
676 self.fail('%s returned %r, expected %r'%\
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000677 (name, result, expected))
Raymond Hettinger64108af2002-05-13 03:55:01 +0000678
Thomas Wouters89f507f2006-12-13 04:49:30 +0000679 testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
680 testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000681
Christian Heimes53876d92008-04-19 00:31:39 +0000682 self.assertEquals(math.modf(INF), (0.0, INF))
683 self.assertEquals(math.modf(NINF), (-0.0, NINF))
684
685 modf_nan = math.modf(NAN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000686 self.assertTrue(math.isnan(modf_nan[0]))
687 self.assertTrue(math.isnan(modf_nan[1]))
Christian Heimes53876d92008-04-19 00:31:39 +0000688
Thomas Wouters89f507f2006-12-13 04:49:30 +0000689 def testPow(self):
690 self.assertRaises(TypeError, math.pow)
691 self.ftest('pow(0,1)', math.pow(0,1), 0)
692 self.ftest('pow(1,0)', math.pow(1,0), 1)
693 self.ftest('pow(2,1)', math.pow(2,1), 2)
694 self.ftest('pow(2,-1)', math.pow(2,-1), 0.5)
Christian Heimes53876d92008-04-19 00:31:39 +0000695 self.assertEqual(math.pow(INF, 1), INF)
696 self.assertEqual(math.pow(NINF, 1), NINF)
697 self.assertEqual((math.pow(1, INF)), 1.)
698 self.assertEqual((math.pow(1, NINF)), 1.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000699 self.assertTrue(math.isnan(math.pow(NAN, 1)))
700 self.assertTrue(math.isnan(math.pow(2, NAN)))
701 self.assertTrue(math.isnan(math.pow(0, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000702 self.assertEqual(math.pow(1, NAN), 1)
Christian Heimesa342c012008-04-20 21:01:16 +0000703
704 # pow(0., x)
705 self.assertEqual(math.pow(0., INF), 0.)
706 self.assertEqual(math.pow(0., 3.), 0.)
707 self.assertEqual(math.pow(0., 2.3), 0.)
708 self.assertEqual(math.pow(0., 2.), 0.)
709 self.assertEqual(math.pow(0., 0.), 1.)
710 self.assertEqual(math.pow(0., -0.), 1.)
711 self.assertRaises(ValueError, math.pow, 0., -2.)
712 self.assertRaises(ValueError, math.pow, 0., -2.3)
713 self.assertRaises(ValueError, math.pow, 0., -3.)
714 self.assertRaises(ValueError, math.pow, 0., NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000715 self.assertTrue(math.isnan(math.pow(0., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000716
717 # pow(INF, x)
718 self.assertEqual(math.pow(INF, INF), INF)
719 self.assertEqual(math.pow(INF, 3.), INF)
720 self.assertEqual(math.pow(INF, 2.3), INF)
721 self.assertEqual(math.pow(INF, 2.), INF)
722 self.assertEqual(math.pow(INF, 0.), 1.)
723 self.assertEqual(math.pow(INF, -0.), 1.)
724 self.assertEqual(math.pow(INF, -2.), 0.)
725 self.assertEqual(math.pow(INF, -2.3), 0.)
726 self.assertEqual(math.pow(INF, -3.), 0.)
727 self.assertEqual(math.pow(INF, NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000728 self.assertTrue(math.isnan(math.pow(INF, NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000729
730 # pow(-0., x)
731 self.assertEqual(math.pow(-0., INF), 0.)
732 self.assertEqual(math.pow(-0., 3.), -0.)
733 self.assertEqual(math.pow(-0., 2.3), 0.)
734 self.assertEqual(math.pow(-0., 2.), 0.)
735 self.assertEqual(math.pow(-0., 0.), 1.)
736 self.assertEqual(math.pow(-0., -0.), 1.)
737 self.assertRaises(ValueError, math.pow, -0., -2.)
738 self.assertRaises(ValueError, math.pow, -0., -2.3)
739 self.assertRaises(ValueError, math.pow, -0., -3.)
740 self.assertRaises(ValueError, math.pow, -0., NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000741 self.assertTrue(math.isnan(math.pow(-0., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000742
743 # pow(NINF, x)
744 self.assertEqual(math.pow(NINF, INF), INF)
745 self.assertEqual(math.pow(NINF, 3.), NINF)
746 self.assertEqual(math.pow(NINF, 2.3), INF)
747 self.assertEqual(math.pow(NINF, 2.), INF)
748 self.assertEqual(math.pow(NINF, 0.), 1.)
749 self.assertEqual(math.pow(NINF, -0.), 1.)
750 self.assertEqual(math.pow(NINF, -2.), 0.)
751 self.assertEqual(math.pow(NINF, -2.3), 0.)
752 self.assertEqual(math.pow(NINF, -3.), -0.)
753 self.assertEqual(math.pow(NINF, NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000754 self.assertTrue(math.isnan(math.pow(NINF, NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000755
756 # pow(-1, x)
757 self.assertEqual(math.pow(-1., INF), 1.)
758 self.assertEqual(math.pow(-1., 3.), -1.)
759 self.assertRaises(ValueError, math.pow, -1., 2.3)
760 self.assertEqual(math.pow(-1., 2.), 1.)
761 self.assertEqual(math.pow(-1., 0.), 1.)
762 self.assertEqual(math.pow(-1., -0.), 1.)
763 self.assertEqual(math.pow(-1., -2.), 1.)
764 self.assertRaises(ValueError, math.pow, -1., -2.3)
765 self.assertEqual(math.pow(-1., -3.), -1.)
766 self.assertEqual(math.pow(-1., NINF), 1.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000767 self.assertTrue(math.isnan(math.pow(-1., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000768
769 # pow(1, x)
770 self.assertEqual(math.pow(1., INF), 1.)
771 self.assertEqual(math.pow(1., 3.), 1.)
772 self.assertEqual(math.pow(1., 2.3), 1.)
773 self.assertEqual(math.pow(1., 2.), 1.)
774 self.assertEqual(math.pow(1., 0.), 1.)
775 self.assertEqual(math.pow(1., -0.), 1.)
776 self.assertEqual(math.pow(1., -2.), 1.)
777 self.assertEqual(math.pow(1., -2.3), 1.)
778 self.assertEqual(math.pow(1., -3.), 1.)
779 self.assertEqual(math.pow(1., NINF), 1.)
780 self.assertEqual(math.pow(1., NAN), 1.)
781
782 # pow(x, 0) should be 1 for any x
783 self.assertEqual(math.pow(2.3, 0.), 1.)
784 self.assertEqual(math.pow(-2.3, 0.), 1.)
785 self.assertEqual(math.pow(NAN, 0.), 1.)
786 self.assertEqual(math.pow(2.3, -0.), 1.)
787 self.assertEqual(math.pow(-2.3, -0.), 1.)
788 self.assertEqual(math.pow(NAN, -0.), 1.)
789
790 # pow(x, y) is invalid if x is negative and y is not integral
791 self.assertRaises(ValueError, math.pow, -1., 2.3)
792 self.assertRaises(ValueError, math.pow, -15., -3.1)
793
794 # pow(x, NINF)
795 self.assertEqual(math.pow(1.9, NINF), 0.)
796 self.assertEqual(math.pow(1.1, NINF), 0.)
797 self.assertEqual(math.pow(0.9, NINF), INF)
798 self.assertEqual(math.pow(0.1, NINF), INF)
799 self.assertEqual(math.pow(-0.1, NINF), INF)
800 self.assertEqual(math.pow(-0.9, NINF), INF)
801 self.assertEqual(math.pow(-1.1, NINF), 0.)
802 self.assertEqual(math.pow(-1.9, NINF), 0.)
803
804 # pow(x, INF)
805 self.assertEqual(math.pow(1.9, INF), INF)
806 self.assertEqual(math.pow(1.1, INF), INF)
807 self.assertEqual(math.pow(0.9, INF), 0.)
808 self.assertEqual(math.pow(0.1, INF), 0.)
809 self.assertEqual(math.pow(-0.1, INF), 0.)
810 self.assertEqual(math.pow(-0.9, INF), 0.)
811 self.assertEqual(math.pow(-1.1, INF), INF)
812 self.assertEqual(math.pow(-1.9, INF), INF)
813
814 # pow(x, y) should work for x negative, y an integer
815 self.ftest('(-2.)**3.', math.pow(-2.0, 3.0), -8.0)
816 self.ftest('(-2.)**2.', math.pow(-2.0, 2.0), 4.0)
817 self.ftest('(-2.)**1.', math.pow(-2.0, 1.0), -2.0)
818 self.ftest('(-2.)**0.', math.pow(-2.0, 0.0), 1.0)
819 self.ftest('(-2.)**-0.', math.pow(-2.0, -0.0), 1.0)
820 self.ftest('(-2.)**-1.', math.pow(-2.0, -1.0), -0.5)
821 self.ftest('(-2.)**-2.', math.pow(-2.0, -2.0), 0.25)
822 self.ftest('(-2.)**-3.', math.pow(-2.0, -3.0), -0.125)
823 self.assertRaises(ValueError, math.pow, -2.0, -0.5)
824 self.assertRaises(ValueError, math.pow, -2.0, 0.5)
825
826 # the following tests have been commented out since they don't
827 # really belong here: the implementation of ** for floats is
828 # independent of the implemention of math.pow
829 #self.assertEqual(1**NAN, 1)
830 #self.assertEqual(1**INF, 1)
831 #self.assertEqual(1**NINF, 1)
832 #self.assertEqual(1**0, 1)
833 #self.assertEqual(1.**NAN, 1)
834 #self.assertEqual(1.**INF, 1)
835 #self.assertEqual(1.**NINF, 1)
836 #self.assertEqual(1.**0, 1)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000837
Thomas Wouters89f507f2006-12-13 04:49:30 +0000838 def testRadians(self):
839 self.assertRaises(TypeError, math.radians)
840 self.ftest('radians(180)', math.radians(180), math.pi)
841 self.ftest('radians(90)', math.radians(90), math.pi/2)
842 self.ftest('radians(-45)', math.radians(-45), -math.pi/4)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000843
Thomas Wouters89f507f2006-12-13 04:49:30 +0000844 def testSin(self):
845 self.assertRaises(TypeError, math.sin)
846 self.ftest('sin(0)', math.sin(0), 0)
847 self.ftest('sin(pi/2)', math.sin(math.pi/2), 1)
848 self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000849 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000850 self.assertTrue(math.isnan(math.sin(INF)))
851 self.assertTrue(math.isnan(math.sin(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +0000852 except ValueError:
853 self.assertRaises(ValueError, math.sin, INF)
854 self.assertRaises(ValueError, math.sin, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000855 self.assertTrue(math.isnan(math.sin(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000856
Thomas Wouters89f507f2006-12-13 04:49:30 +0000857 def testSinh(self):
858 self.assertRaises(TypeError, math.sinh)
859 self.ftest('sinh(0)', math.sinh(0), 0)
860 self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1)
861 self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0)
Christian Heimes53876d92008-04-19 00:31:39 +0000862 self.assertEquals(math.sinh(INF), INF)
Christian Heimesa342c012008-04-20 21:01:16 +0000863 self.assertEquals(math.sinh(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000864 self.assertTrue(math.isnan(math.sinh(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +0000865
Thomas Wouters89f507f2006-12-13 04:49:30 +0000866 def testSqrt(self):
867 self.assertRaises(TypeError, math.sqrt)
868 self.ftest('sqrt(0)', math.sqrt(0), 0)
869 self.ftest('sqrt(1)', math.sqrt(1), 1)
870 self.ftest('sqrt(4)', math.sqrt(4), 2)
Christian Heimes53876d92008-04-19 00:31:39 +0000871 self.assertEquals(math.sqrt(INF), INF)
872 self.assertRaises(ValueError, math.sqrt, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000873 self.assertTrue(math.isnan(math.sqrt(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +0000874
Thomas Wouters89f507f2006-12-13 04:49:30 +0000875 def testTan(self):
876 self.assertRaises(TypeError, math.tan)
877 self.ftest('tan(0)', math.tan(0), 0)
878 self.ftest('tan(pi/4)', math.tan(math.pi/4), 1)
879 self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000880 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000881 self.assertTrue(math.isnan(math.tan(INF)))
882 self.assertTrue(math.isnan(math.tan(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +0000883 except:
884 self.assertRaises(ValueError, math.tan, INF)
885 self.assertRaises(ValueError, math.tan, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000886 self.assertTrue(math.isnan(math.tan(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +0000887
Thomas Wouters89f507f2006-12-13 04:49:30 +0000888 def testTanh(self):
889 self.assertRaises(TypeError, math.tanh)
890 self.ftest('tanh(0)', math.tanh(0), 0)
891 self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0)
Christian Heimes53876d92008-04-19 00:31:39 +0000892 self.ftest('tanh(inf)', math.tanh(INF), 1)
893 self.ftest('tanh(-inf)', math.tanh(NINF), -1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000894 self.assertTrue(math.isnan(math.tanh(NAN)))
Victor Stinnerbe3da382010-11-07 14:14:27 +0000895
896 @requires_IEEE_754
897 @unittest.skipIf(sysconfig.get_config_var('TANH_PRESERVES_ZERO_SIGN') == 0,
898 "system tanh() function doesn't copy the sign")
899 def testTanhSign(self):
Christian Heimese57950f2008-04-21 13:08:03 +0000900 # check that tanh(-0.) == -0. on IEEE 754 systems
Victor Stinnerbe3da382010-11-07 14:14:27 +0000901 self.assertEqual(math.tanh(-0.), -0.)
902 self.assertEqual(math.copysign(1., math.tanh(-0.)),
903 math.copysign(1., -0.))
Tim Peters1d120612000-10-12 06:10:25 +0000904
Christian Heimes400adb02008-02-01 08:12:03 +0000905 def test_trunc(self):
906 self.assertEqual(math.trunc(1), 1)
907 self.assertEqual(math.trunc(-1), -1)
908 self.assertEqual(type(math.trunc(1)), int)
909 self.assertEqual(type(math.trunc(1.5)), int)
910 self.assertEqual(math.trunc(1.5), 1)
911 self.assertEqual(math.trunc(-1.5), -1)
912 self.assertEqual(math.trunc(1.999999), 1)
913 self.assertEqual(math.trunc(-1.999999), -1)
914 self.assertEqual(math.trunc(-0.999999), -0)
915 self.assertEqual(math.trunc(-100.999), -100)
916
917 class TestTrunc(object):
918 def __trunc__(self):
919 return 23
920
921 class TestNoTrunc(object):
922 pass
923
924 self.assertEqual(math.trunc(TestTrunc()), 23)
925
926 self.assertRaises(TypeError, math.trunc)
927 self.assertRaises(TypeError, math.trunc, 1, 2)
928 self.assertRaises(TypeError, math.trunc, TestNoTrunc())
929
Mark Dickinson8e0c9962010-07-11 17:38:24 +0000930 def testIsfinite(self):
931 self.assertTrue(math.isfinite(0.0))
932 self.assertTrue(math.isfinite(-0.0))
933 self.assertTrue(math.isfinite(1.0))
934 self.assertTrue(math.isfinite(-1.0))
935 self.assertFalse(math.isfinite(float("nan")))
936 self.assertFalse(math.isfinite(float("inf")))
937 self.assertFalse(math.isfinite(float("-inf")))
938
Christian Heimes072c0f12008-01-03 23:01:04 +0000939 def testIsnan(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000940 self.assertTrue(math.isnan(float("nan")))
941 self.assertTrue(math.isnan(float("inf")* 0.))
942 self.assertFalse(math.isnan(float("inf")))
943 self.assertFalse(math.isnan(0.))
944 self.assertFalse(math.isnan(1.))
Christian Heimes072c0f12008-01-03 23:01:04 +0000945
946 def testIsinf(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000947 self.assertTrue(math.isinf(float("inf")))
948 self.assertTrue(math.isinf(float("-inf")))
949 self.assertTrue(math.isinf(1E400))
950 self.assertTrue(math.isinf(-1E400))
951 self.assertFalse(math.isinf(float("nan")))
952 self.assertFalse(math.isinf(0.))
953 self.assertFalse(math.isinf(1.))
Christian Heimes072c0f12008-01-03 23:01:04 +0000954
Thomas Wouters89f507f2006-12-13 04:49:30 +0000955 # RED_FLAG 16-Oct-2000 Tim
956 # While 2.0 is more consistent about exceptions than previous releases, it
957 # still fails this part of the test on some platforms. For now, we only
958 # *run* test_exceptions() in verbose mode, so that this isn't normally
959 # tested.
Tim Peters98c81842000-10-16 17:35:13 +0000960
Thomas Wouters89f507f2006-12-13 04:49:30 +0000961 if verbose:
962 def test_exceptions(self):
963 try:
964 x = math.exp(-1000000000)
965 except:
966 # mathmodule.c is failing to weed out underflows from libm, or
967 # we've got an fp format with huge dynamic range
968 self.fail("underflowing exp() should not have raised "
969 "an exception")
970 if x != 0:
971 self.fail("underflowing exp() should have returned 0")
972
973 # If this fails, probably using a strict IEEE-754 conforming libm, and x
974 # is +Inf afterwards. But Python wants overflows detected by default.
975 try:
976 x = math.exp(1000000000)
977 except OverflowError:
978 pass
979 else:
980 self.fail("overflowing exp() didn't trigger OverflowError")
981
982 # If this fails, it could be a puzzle. One odd possibility is that
983 # mathmodule.c's macros are getting confused while comparing
984 # Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE
985 # as a result (and so raising OverflowError instead).
986 try:
987 x = math.sqrt(-1.0)
988 except ValueError:
989 pass
990 else:
991 self.fail("sqrt(-1) didn't raise ValueError")
992
Mark Dickinson63566232009-09-18 21:04:19 +0000993 @requires_IEEE_754
Christian Heimes53876d92008-04-19 00:31:39 +0000994 def test_testfile(self):
Christian Heimes53876d92008-04-19 00:31:39 +0000995 for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file):
996 # Skip if either the input or result is complex, or if
997 # flags is nonempty
998 if ai != 0. or ei != 0. or flags:
999 continue
1000 if fn in ['rect', 'polar']:
1001 # no real versions of rect, polar
1002 continue
1003 func = getattr(math, fn)
Christian Heimesa342c012008-04-20 21:01:16 +00001004 try:
1005 result = func(ar)
Mark Dickinsona0de26c2008-04-30 23:30:57 +00001006 except ValueError as exc:
1007 message = (("Unexpected ValueError: %s\n " +
1008 "in test %s:%s(%r)\n") % (exc.args[0], id, fn, ar))
Christian Heimesa342c012008-04-20 21:01:16 +00001009 self.fail(message)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001010 except OverflowError:
1011 message = ("Unexpected OverflowError in " +
1012 "test %s:%s(%r)\n" % (id, fn, ar))
1013 self.fail(message)
Christian Heimes53876d92008-04-19 00:31:39 +00001014 self.ftest("%s:%s(%r)" % (id, fn, ar), result, er)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001015
Victor Stinnerbe3da382010-11-07 14:14:27 +00001016 @requires_IEEE_754
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001017 def test_mtestfile(self):
1018 ALLOWED_ERROR = 20 # permitted error, in ulps
1019 fail_fmt = "{}:{}({!r}): expected {!r}, got {!r}"
1020
1021 failures = []
1022 for id, fn, arg, expected, flags in parse_mtestfile(math_testcases):
1023 func = getattr(math, fn)
1024
1025 if 'invalid' in flags or 'divide-by-zero' in flags:
1026 expected = 'ValueError'
1027 elif 'overflow' in flags:
1028 expected = 'OverflowError'
1029
1030 try:
1031 got = func(arg)
1032 except ValueError:
1033 got = 'ValueError'
1034 except OverflowError:
1035 got = 'OverflowError'
1036
Mark Dickinson05d2e082009-12-11 20:17:17 +00001037 accuracy_failure = None
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001038 if isinstance(got, float) and isinstance(expected, float):
1039 if math.isnan(expected) and math.isnan(got):
1040 continue
1041 if not math.isnan(expected) and not math.isnan(got):
Mark Dickinson664b5112009-12-16 20:23:42 +00001042 if fn == 'lgamma':
1043 # we use a weaker accuracy test for lgamma;
1044 # lgamma only achieves an absolute error of
1045 # a few multiples of the machine accuracy, in
1046 # general.
Mark Dickinson05d2e082009-12-11 20:17:17 +00001047 accuracy_failure = acc_check(expected, got,
1048 rel_err = 5e-15,
1049 abs_err = 5e-15)
Mark Dickinsonbcdf9da2010-06-13 10:52:38 +00001050 elif fn == 'erfc':
1051 # erfc has less-than-ideal accuracy for large
1052 # arguments (x ~ 25 or so), mainly due to the
1053 # error involved in computing exp(-x*x).
1054 #
1055 # XXX Would be better to weaken this test only
1056 # for large x, instead of for all x.
1057 accuracy_failure = ulps_check(expected, got, 2000)
1058
Mark Dickinson05d2e082009-12-11 20:17:17 +00001059 else:
Mark Dickinson664b5112009-12-16 20:23:42 +00001060 accuracy_failure = ulps_check(expected, got, 20)
Mark Dickinson05d2e082009-12-11 20:17:17 +00001061 if accuracy_failure is None:
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001062 continue
1063
1064 if isinstance(got, str) and isinstance(expected, str):
1065 if got == expected:
1066 continue
1067
1068 fail_msg = fail_fmt.format(id, fn, arg, expected, got)
Mark Dickinson05d2e082009-12-11 20:17:17 +00001069 if accuracy_failure is not None:
1070 fail_msg += ' ({})'.format(accuracy_failure)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001071 failures.append(fail_msg)
1072
1073 if failures:
1074 self.fail('Failures in test_mtestfile:\n ' +
1075 '\n '.join(failures))
1076
1077
Thomas Wouters89f507f2006-12-13 04:49:30 +00001078def test_main():
Christian Heimes53876d92008-04-19 00:31:39 +00001079 from doctest import DocFileSuite
1080 suite = unittest.TestSuite()
1081 suite.addTest(unittest.makeSuite(MathTests))
1082 suite.addTest(DocFileSuite("ieee754.txt"))
1083 run_unittest(suite)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001084
1085if __name__ == '__main__':
1086 test_main()