blob: 525ee09786f1e5e8e5bf3f96528716f2b7114e4c [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
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 Dickinson63566232009-09-18 21:04:19 +000017# decorator for skipping tests on non-IEEE 754 platforms
18requires_IEEE_754 = unittest.skipUnless(
19 float.__getformat__("double").startswith("IEEE"),
20 "test requires IEEE 754 doubles")
21
Mark Dickinson5c567082009-04-24 16:39:07 +000022# detect evidence of double-rounding: fsum is not always correctly
23# rounded on machines that suffer from double rounding.
24x, y = 1e16, 2.9999 # use temporary values to defeat peephole optimizer
25HAVE_DOUBLE_ROUNDING = (x + y == 1e16 + 4)
26
Christian Heimes53876d92008-04-19 00:31:39 +000027# locate file with test values
28if __name__ == '__main__':
29 file = sys.argv[0]
30else:
31 file = __file__
32test_dir = os.path.dirname(file) or os.curdir
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000033math_testcases = os.path.join(test_dir, 'math_testcases.txt')
Christian Heimes53876d92008-04-19 00:31:39 +000034test_file = os.path.join(test_dir, 'cmath_testcases.txt')
35
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000036def to_ulps(x):
37 """Convert a non-NaN float x to an integer, in such a way that
38 adjacent floats are converted to adjacent integers. Then
39 abs(ulps(x) - ulps(y)) gives the difference in ulps between two
40 floats.
41
42 The results from this function will only make sense on platforms
43 where C doubles are represented in IEEE 754 binary64 format.
44
45 """
Mark Dickinsond412ab52009-10-17 07:10:00 +000046 n = struct.unpack('<q', struct.pack('<d', x))[0]
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000047 if n < 0:
48 n = ~(n+2**63)
49 return n
50
Mark Dickinson05d2e082009-12-11 20:17:17 +000051def ulps_check(expected, got, ulps=20):
52 """Given non-NaN floats `expected` and `got`,
53 check that they're equal to within the given number of ulps.
54
55 Returns None on success and an error message on failure."""
56
57 ulps_error = to_ulps(got) - to_ulps(expected)
58 if abs(ulps_error) <= ulps:
59 return None
60 return "error = {} ulps; permitted error = {} ulps".format(ulps_error,
61 ulps)
62
63def acc_check(expected, got, rel_err=2e-15, abs_err = 5e-323):
64 """Determine whether non-NaN floats a and b are equal to within a
65 (small) rounding error. The default values for rel_err and
66 abs_err are chosen to be suitable for platforms where a float is
67 represented by an IEEE 754 double. They allow an error of between
68 9 and 19 ulps."""
69
70 # need to special case infinities, since inf - inf gives nan
71 if math.isinf(expected) and got == expected:
72 return None
73
74 error = got - expected
75
76 permitted_error = max(abs_err, rel_err * abs(expected))
77 if abs(error) < permitted_error:
78 return None
79 return "error = {}; permitted error = {}".format(error,
80 permitted_error)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +000081
82def parse_mtestfile(fname):
83 """Parse a file with test values
84
85 -- starts a comment
86 blank lines, or lines containing only a comment, are ignored
87 other lines are expected to have the form
88 id fn arg -> expected [flag]*
89
90 """
91 with open(fname) as fp:
92 for line in fp:
93 # strip comments, and skip blank lines
94 if '--' in line:
95 line = line[:line.index('--')]
96 if not line.strip():
97 continue
98
99 lhs, rhs = line.split('->')
100 id, fn, arg = lhs.split()
101 rhs_pieces = rhs.split()
102 exp = rhs_pieces[0]
103 flags = rhs_pieces[1:]
104
105 yield (id, fn, float(arg), float(exp), flags)
106
Christian Heimes53876d92008-04-19 00:31:39 +0000107def parse_testfile(fname):
108 """Parse a file with test values
109
110 Empty lines or lines starting with -- are ignored
111 yields id, fn, arg_real, arg_imag, exp_real, exp_imag
112 """
113 with open(fname) as fp:
114 for line in fp:
115 # skip comment lines and blank lines
116 if line.startswith('--') or not line.strip():
117 continue
118
119 lhs, rhs = line.split('->')
120 id, fn, arg_real, arg_imag = lhs.split()
121 rhs_pieces = rhs.split()
122 exp_real, exp_imag = rhs_pieces[0], rhs_pieces[1]
123 flags = rhs_pieces[2:]
124
125 yield (id, fn,
126 float(arg_real), float(arg_imag),
127 float(exp_real), float(exp_imag),
128 flags
129 )
Guido van Rossumfcce6301996-08-08 18:26:25 +0000130
Thomas Wouters89f507f2006-12-13 04:49:30 +0000131class MathTests(unittest.TestCase):
Guido van Rossumfcce6301996-08-08 18:26:25 +0000132
Thomas Wouters89f507f2006-12-13 04:49:30 +0000133 def ftest(self, name, value, expected):
134 if abs(value-expected) > eps:
Guido van Rossum806c2462007-08-06 23:33:07 +0000135 # Use %r instead of %f so the error message
136 # displays full precision. Otherwise discrepancies
137 # in the last few bits will lead to very confusing
138 # error messages
139 self.fail('%s returned %r, expected %r' %
Thomas Wouters89f507f2006-12-13 04:49:30 +0000140 (name, value, expected))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000141
Thomas Wouters89f507f2006-12-13 04:49:30 +0000142 def testConstants(self):
143 self.ftest('pi', math.pi, 3.1415926)
144 self.ftest('e', math.e, 2.7182818)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000145
Thomas Wouters89f507f2006-12-13 04:49:30 +0000146 def testAcos(self):
147 self.assertRaises(TypeError, math.acos)
148 self.ftest('acos(-1)', math.acos(-1), math.pi)
149 self.ftest('acos(0)', math.acos(0), math.pi/2)
150 self.ftest('acos(1)', math.acos(1), 0)
Christian Heimes53876d92008-04-19 00:31:39 +0000151 self.assertRaises(ValueError, math.acos, INF)
152 self.assertRaises(ValueError, math.acos, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000153 self.assertTrue(math.isnan(math.acos(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000154
155 def testAcosh(self):
156 self.assertRaises(TypeError, math.acosh)
157 self.ftest('acosh(1)', math.acosh(1), 0)
158 self.ftest('acosh(2)', math.acosh(2), 1.3169578969248168)
159 self.assertRaises(ValueError, math.acosh, 0)
160 self.assertRaises(ValueError, math.acosh, -1)
161 self.assertEquals(math.acosh(INF), INF)
162 self.assertRaises(ValueError, math.acosh, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000163 self.assertTrue(math.isnan(math.acosh(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000164
Thomas Wouters89f507f2006-12-13 04:49:30 +0000165 def testAsin(self):
166 self.assertRaises(TypeError, math.asin)
167 self.ftest('asin(-1)', math.asin(-1), -math.pi/2)
168 self.ftest('asin(0)', math.asin(0), 0)
169 self.ftest('asin(1)', math.asin(1), math.pi/2)
Christian Heimes53876d92008-04-19 00:31:39 +0000170 self.assertRaises(ValueError, math.asin, INF)
171 self.assertRaises(ValueError, math.asin, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000172 self.assertTrue(math.isnan(math.asin(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000173
174 def testAsinh(self):
175 self.assertRaises(TypeError, math.asinh)
176 self.ftest('asinh(0)', math.asinh(0), 0)
177 self.ftest('asinh(1)', math.asinh(1), 0.88137358701954305)
178 self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305)
179 self.assertEquals(math.asinh(INF), INF)
180 self.assertEquals(math.asinh(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000181 self.assertTrue(math.isnan(math.asinh(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000182
Thomas Wouters89f507f2006-12-13 04:49:30 +0000183 def testAtan(self):
184 self.assertRaises(TypeError, math.atan)
185 self.ftest('atan(-1)', math.atan(-1), -math.pi/4)
186 self.ftest('atan(0)', math.atan(0), 0)
187 self.ftest('atan(1)', math.atan(1), math.pi/4)
Christian Heimes53876d92008-04-19 00:31:39 +0000188 self.ftest('atan(inf)', math.atan(INF), math.pi/2)
Christian Heimesa342c012008-04-20 21:01:16 +0000189 self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000190 self.assertTrue(math.isnan(math.atan(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000191
192 def testAtanh(self):
193 self.assertRaises(TypeError, math.atan)
194 self.ftest('atanh(0)', math.atanh(0), 0)
195 self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489)
196 self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489)
197 self.assertRaises(ValueError, math.atanh, 1)
198 self.assertRaises(ValueError, math.atanh, -1)
199 self.assertRaises(ValueError, math.atanh, INF)
200 self.assertRaises(ValueError, math.atanh, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000201 self.assertTrue(math.isnan(math.atanh(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000202
Thomas Wouters89f507f2006-12-13 04:49:30 +0000203 def testAtan2(self):
204 self.assertRaises(TypeError, math.atan2)
205 self.ftest('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2)
206 self.ftest('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4)
207 self.ftest('atan2(0, 1)', math.atan2(0, 1), 0)
208 self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4)
209 self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000210
Christian Heimese57950f2008-04-21 13:08:03 +0000211 # math.atan2(0, x)
212 self.ftest('atan2(0., -inf)', math.atan2(0., NINF), math.pi)
213 self.ftest('atan2(0., -2.3)', math.atan2(0., -2.3), math.pi)
214 self.ftest('atan2(0., -0.)', math.atan2(0., -0.), math.pi)
215 self.assertEqual(math.atan2(0., 0.), 0.)
216 self.assertEqual(math.atan2(0., 2.3), 0.)
217 self.assertEqual(math.atan2(0., INF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000218 self.assertTrue(math.isnan(math.atan2(0., NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000219 # math.atan2(-0, x)
220 self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi)
221 self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi)
222 self.ftest('atan2(-0., -0.)', math.atan2(-0., -0.), -math.pi)
223 self.assertEqual(math.atan2(-0., 0.), -0.)
224 self.assertEqual(math.atan2(-0., 2.3), -0.)
225 self.assertEqual(math.atan2(-0., INF), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000226 self.assertTrue(math.isnan(math.atan2(-0., NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000227 # math.atan2(INF, x)
228 self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4)
229 self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2)
230 self.ftest('atan2(inf, -0.)', math.atan2(INF, -0.0), math.pi/2)
231 self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2)
232 self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2)
233 self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000234 self.assertTrue(math.isnan(math.atan2(INF, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000235 # math.atan2(NINF, x)
236 self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4)
237 self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2)
238 self.ftest('atan2(-inf, -0.)', math.atan2(NINF, -0.0), -math.pi/2)
239 self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2)
240 self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2)
241 self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000242 self.assertTrue(math.isnan(math.atan2(NINF, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000243 # math.atan2(+finite, x)
244 self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi)
245 self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2)
246 self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2)
247 self.assertEqual(math.atan2(2.3, INF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000248 self.assertTrue(math.isnan(math.atan2(2.3, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000249 # math.atan2(-finite, x)
250 self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi)
251 self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2)
252 self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2)
253 self.assertEqual(math.atan2(-2.3, INF), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000254 self.assertTrue(math.isnan(math.atan2(-2.3, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000255 # math.atan2(NAN, x)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000256 self.assertTrue(math.isnan(math.atan2(NAN, NINF)))
257 self.assertTrue(math.isnan(math.atan2(NAN, -2.3)))
258 self.assertTrue(math.isnan(math.atan2(NAN, -0.)))
259 self.assertTrue(math.isnan(math.atan2(NAN, 0.)))
260 self.assertTrue(math.isnan(math.atan2(NAN, 2.3)))
261 self.assertTrue(math.isnan(math.atan2(NAN, INF)))
262 self.assertTrue(math.isnan(math.atan2(NAN, NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000263
Thomas Wouters89f507f2006-12-13 04:49:30 +0000264 def testCeil(self):
265 self.assertRaises(TypeError, math.ceil)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000266 self.assertEquals(int, type(math.ceil(0.5)))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000267 self.ftest('ceil(0.5)', math.ceil(0.5), 1)
268 self.ftest('ceil(1.0)', math.ceil(1.0), 1)
269 self.ftest('ceil(1.5)', math.ceil(1.5), 2)
270 self.ftest('ceil(-0.5)', math.ceil(-0.5), 0)
271 self.ftest('ceil(-1.0)', math.ceil(-1.0), -1)
272 self.ftest('ceil(-1.5)', math.ceil(-1.5), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000273 #self.assertEquals(math.ceil(INF), INF)
274 #self.assertEquals(math.ceil(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000275 #self.assertTrue(math.isnan(math.ceil(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000276
Guido van Rossum13e05de2007-08-23 22:56:55 +0000277 class TestCeil:
278 def __ceil__(self):
279 return 42
280 class TestNoCeil:
281 pass
282 self.ftest('ceil(TestCeil())', math.ceil(TestCeil()), 42)
283 self.assertRaises(TypeError, math.ceil, TestNoCeil())
284
285 t = TestNoCeil()
286 t.__ceil__ = lambda *args: args
287 self.assertRaises(TypeError, math.ceil, t)
288 self.assertRaises(TypeError, math.ceil, t, 0)
289
Mark Dickinson63566232009-09-18 21:04:19 +0000290 @requires_IEEE_754
291 def testCopysign(self):
Mark Dickinson06b59e02010-02-06 23:16:50 +0000292 self.assertEqual(math.copysign(1, 42), 1.0)
293 self.assertEqual(math.copysign(0., 42), 0.0)
294 self.assertEqual(math.copysign(1., -42), -1.0)
295 self.assertEqual(math.copysign(3, 0.), 3.0)
296 self.assertEqual(math.copysign(4., -0.), -4.0)
297
Mark Dickinson63566232009-09-18 21:04:19 +0000298 self.assertRaises(TypeError, math.copysign)
299 # copysign should let us distinguish signs of zeros
Mark Dickinson06b59e02010-02-06 23:16:50 +0000300 self.assertEquals(math.copysign(1., 0.), 1.)
301 self.assertEquals(math.copysign(1., -0.), -1.)
302 self.assertEquals(math.copysign(INF, 0.), INF)
303 self.assertEquals(math.copysign(INF, -0.), NINF)
304 self.assertEquals(math.copysign(NINF, 0.), INF)
305 self.assertEquals(math.copysign(NINF, -0.), NINF)
Mark Dickinson63566232009-09-18 21:04:19 +0000306 # and of infinities
Mark Dickinson06b59e02010-02-06 23:16:50 +0000307 self.assertEquals(math.copysign(1., INF), 1.)
308 self.assertEquals(math.copysign(1., NINF), -1.)
309 self.assertEquals(math.copysign(INF, INF), INF)
310 self.assertEquals(math.copysign(INF, NINF), NINF)
311 self.assertEquals(math.copysign(NINF, INF), INF)
312 self.assertEquals(math.copysign(NINF, NINF), NINF)
313 self.assertTrue(math.isnan(math.copysign(NAN, 1.)))
314 self.assertTrue(math.isnan(math.copysign(NAN, INF)))
315 self.assertTrue(math.isnan(math.copysign(NAN, NINF)))
316 self.assertTrue(math.isnan(math.copysign(NAN, NAN)))
Mark Dickinson63566232009-09-18 21:04:19 +0000317 # copysign(INF, NAN) may be INF or it may be NINF, since
318 # we don't know whether the sign bit of NAN is set on any
319 # given platform.
Mark Dickinson06b59e02010-02-06 23:16:50 +0000320 self.assertTrue(math.isinf(math.copysign(INF, NAN)))
Mark Dickinson63566232009-09-18 21:04:19 +0000321 # similarly, copysign(2., NAN) could be 2. or -2.
Mark Dickinson06b59e02010-02-06 23:16:50 +0000322 self.assertEquals(abs(math.copysign(2., NAN)), 2.)
Christian Heimes53876d92008-04-19 00:31:39 +0000323
Thomas Wouters89f507f2006-12-13 04:49:30 +0000324 def testCos(self):
325 self.assertRaises(TypeError, math.cos)
326 self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0)
327 self.ftest('cos(0)', math.cos(0), 1)
328 self.ftest('cos(pi/2)', math.cos(math.pi/2), 0)
329 self.ftest('cos(pi)', math.cos(math.pi), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000330 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000331 self.assertTrue(math.isnan(math.cos(INF)))
332 self.assertTrue(math.isnan(math.cos(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +0000333 except ValueError:
334 self.assertRaises(ValueError, math.cos, INF)
335 self.assertRaises(ValueError, math.cos, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000336 self.assertTrue(math.isnan(math.cos(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000337
Thomas Wouters89f507f2006-12-13 04:49:30 +0000338 def testCosh(self):
339 self.assertRaises(TypeError, math.cosh)
340 self.ftest('cosh(0)', math.cosh(0), 1)
341 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 +0000342 self.assertEquals(math.cosh(INF), INF)
343 self.assertEquals(math.cosh(NINF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000344 self.assertTrue(math.isnan(math.cosh(NAN)))
Raymond Hettinger64108af2002-05-13 03:55:01 +0000345
Thomas Wouters89f507f2006-12-13 04:49:30 +0000346 def testDegrees(self):
347 self.assertRaises(TypeError, math.degrees)
348 self.ftest('degrees(pi)', math.degrees(math.pi), 180.0)
349 self.ftest('degrees(pi/2)', math.degrees(math.pi/2), 90.0)
350 self.ftest('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000351
Thomas Wouters89f507f2006-12-13 04:49:30 +0000352 def testExp(self):
353 self.assertRaises(TypeError, math.exp)
354 self.ftest('exp(-1)', math.exp(-1), 1/math.e)
355 self.ftest('exp(0)', math.exp(0), 1)
356 self.ftest('exp(1)', math.exp(1), math.e)
Christian Heimes53876d92008-04-19 00:31:39 +0000357 self.assertEquals(math.exp(INF), INF)
358 self.assertEquals(math.exp(NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000359 self.assertTrue(math.isnan(math.exp(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000360
Thomas Wouters89f507f2006-12-13 04:49:30 +0000361 def testFabs(self):
362 self.assertRaises(TypeError, math.fabs)
363 self.ftest('fabs(-1)', math.fabs(-1), 1)
364 self.ftest('fabs(0)', math.fabs(0), 0)
365 self.ftest('fabs(1)', math.fabs(1), 1)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000366
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000367 def testFactorial(self):
368 def fact(n):
369 result = 1
370 for i in range(1, int(n)+1):
371 result *= i
372 return result
373 values = list(range(10)) + [50, 100, 500]
374 random.shuffle(values)
375 for x in range(10):
376 for cast in (int, float):
377 self.assertEqual(math.factorial(cast(x)), fact(x), (x, fact(x), math.factorial(x)))
378 self.assertRaises(ValueError, math.factorial, -1)
379 self.assertRaises(ValueError, math.factorial, math.pi)
380
Thomas Wouters89f507f2006-12-13 04:49:30 +0000381 def testFloor(self):
382 self.assertRaises(TypeError, math.floor)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000383 self.assertEquals(int, type(math.floor(0.5)))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000384 self.ftest('floor(0.5)', math.floor(0.5), 0)
385 self.ftest('floor(1.0)', math.floor(1.0), 1)
386 self.ftest('floor(1.5)', math.floor(1.5), 1)
387 self.ftest('floor(-0.5)', math.floor(-0.5), -1)
388 self.ftest('floor(-1.0)', math.floor(-1.0), -1)
389 self.ftest('floor(-1.5)', math.floor(-1.5), -2)
Guido van Rossum806c2462007-08-06 23:33:07 +0000390 # pow() relies on floor() to check for integers
391 # This fails on some platforms - so check it here
392 self.ftest('floor(1.23e167)', math.floor(1.23e167), 1.23e167)
393 self.ftest('floor(-1.23e167)', math.floor(-1.23e167), -1.23e167)
Christian Heimes53876d92008-04-19 00:31:39 +0000394 #self.assertEquals(math.ceil(INF), INF)
395 #self.assertEquals(math.ceil(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000396 #self.assertTrue(math.isnan(math.floor(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000397
Guido van Rossum13e05de2007-08-23 22:56:55 +0000398 class TestFloor:
399 def __floor__(self):
400 return 42
401 class TestNoFloor:
402 pass
403 self.ftest('floor(TestFloor())', math.floor(TestFloor()), 42)
404 self.assertRaises(TypeError, math.floor, TestNoFloor())
405
406 t = TestNoFloor()
407 t.__floor__ = lambda *args: args
408 self.assertRaises(TypeError, math.floor, t)
409 self.assertRaises(TypeError, math.floor, t, 0)
410
Thomas Wouters89f507f2006-12-13 04:49:30 +0000411 def testFmod(self):
412 self.assertRaises(TypeError, math.fmod)
413 self.ftest('fmod(10,1)', math.fmod(10,1), 0)
414 self.ftest('fmod(10,0.5)', math.fmod(10,0.5), 0)
415 self.ftest('fmod(10,1.5)', math.fmod(10,1.5), 1)
416 self.ftest('fmod(-10,1)', math.fmod(-10,1), 0)
417 self.ftest('fmod(-10,0.5)', math.fmod(-10,0.5), 0)
418 self.ftest('fmod(-10,1.5)', math.fmod(-10,1.5), -1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000419 self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
420 self.assertTrue(math.isnan(math.fmod(1., NAN)))
421 self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000422 self.assertRaises(ValueError, math.fmod, 1., 0.)
423 self.assertRaises(ValueError, math.fmod, INF, 1.)
424 self.assertRaises(ValueError, math.fmod, NINF, 1.)
425 self.assertRaises(ValueError, math.fmod, INF, 0.)
426 self.assertEquals(math.fmod(3.0, INF), 3.0)
427 self.assertEquals(math.fmod(-3.0, INF), -3.0)
428 self.assertEquals(math.fmod(3.0, NINF), 3.0)
429 self.assertEquals(math.fmod(-3.0, NINF), -3.0)
430 self.assertEquals(math.fmod(0.0, 3.0), 0.0)
431 self.assertEquals(math.fmod(0.0, NINF), 0.0)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000432
Thomas Wouters89f507f2006-12-13 04:49:30 +0000433 def testFrexp(self):
434 self.assertRaises(TypeError, math.frexp)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000435
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000436 def testfrexp(name, result, expected):
437 (mant, exp), (emant, eexp) = result, expected
Thomas Wouters89f507f2006-12-13 04:49:30 +0000438 if abs(mant-emant) > eps or exp != eexp:
439 self.fail('%s returned %r, expected %r'%\
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000440 (name, result, expected))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000441
Thomas Wouters89f507f2006-12-13 04:49:30 +0000442 testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
443 testfrexp('frexp(0)', math.frexp(0), (0, 0))
444 testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
445 testfrexp('frexp(2)', math.frexp(2), (0.5, 2))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000446
Christian Heimes53876d92008-04-19 00:31:39 +0000447 self.assertEquals(math.frexp(INF)[0], INF)
448 self.assertEquals(math.frexp(NINF)[0], NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000449 self.assertTrue(math.isnan(math.frexp(NAN)[0]))
Christian Heimes53876d92008-04-19 00:31:39 +0000450
Mark Dickinson63566232009-09-18 21:04:19 +0000451 @requires_IEEE_754
Mark Dickinson5c567082009-04-24 16:39:07 +0000452 @unittest.skipIf(HAVE_DOUBLE_ROUNDING,
453 "fsum is not exact on machines with double rounding")
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000454 def testFsum(self):
455 # math.fsum relies on exact rounding for correct operation.
456 # There's a known problem with IA32 floating-point that causes
457 # inexact rounding in some situations, and will cause the
458 # math.fsum tests below to fail; see issue #2937. On non IEEE
459 # 754 platforms, and on IEEE 754 platforms that exhibit the
460 # problem described in issue #2937, we simply skip the whole
461 # test.
462
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000463 # Python version of math.fsum, for comparison. Uses a
464 # different algorithm based on frexp, ldexp and integer
465 # arithmetic.
466 from sys import float_info
467 mant_dig = float_info.mant_dig
468 etiny = float_info.min_exp - mant_dig
469
470 def msum(iterable):
471 """Full precision summation. Compute sum(iterable) without any
472 intermediate accumulation of error. Based on the 'lsum' function
473 at http://code.activestate.com/recipes/393090/
474
475 """
476 tmant, texp = 0, 0
477 for x in iterable:
478 mant, exp = math.frexp(x)
479 mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig
480 if texp > exp:
481 tmant <<= texp-exp
482 texp = exp
483 else:
484 mant <<= exp-texp
485 tmant += mant
486 # Round tmant * 2**texp to a float. The original recipe
487 # used float(str(tmant)) * 2.0**texp for this, but that's
488 # a little unsafe because str -> float conversion can't be
489 # relied upon to do correct rounding on all platforms.
490 tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp)
491 if tail > 0:
492 h = 1 << (tail-1)
493 tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1)
494 texp += tail
495 return math.ldexp(tmant, texp)
496
497 test_values = [
498 ([], 0.0),
499 ([0.0], 0.0),
500 ([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100),
501 ([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0),
502 ([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0),
503 ([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0),
504 ([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0),
505 ([1./n for n in range(1, 1001)],
506 float.fromhex('0x1.df11f45f4e61ap+2')),
507 ([(-1.)**n/n for n in range(1, 1001)],
508 float.fromhex('-0x1.62a2af1bd3624p-1')),
509 ([1.7**(i+1)-1.7**i for i in range(1000)] + [-1.7**1000], -1.0),
510 ([1e16, 1., 1e-16], 10000000000000002.0),
511 ([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0),
512 # exercise code for resizing partials array
513 ([2.**n - 2.**(n+50) + 2.**(n+52) for n in range(-1074, 972, 2)] +
514 [-2.**1022],
515 float.fromhex('0x1.5555555555555p+970')),
516 ]
517
518 for i, (vals, expected) in enumerate(test_values):
519 try:
520 actual = math.fsum(vals)
521 except OverflowError:
522 self.fail("test %d failed: got OverflowError, expected %r "
523 "for math.fsum(%.100r)" % (i, expected, vals))
524 except ValueError:
525 self.fail("test %d failed: got ValueError, expected %r "
526 "for math.fsum(%.100r)" % (i, expected, vals))
527 self.assertEqual(actual, expected)
528
529 from random import random, gauss, shuffle
530 for j in range(1000):
531 vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10
532 s = 0
533 for i in range(200):
534 v = gauss(0, random()) ** 7 - s
535 s += v
536 vals.append(v)
537 shuffle(vals)
538
539 s = msum(vals)
540 self.assertEqual(msum(vals), math.fsum(vals))
541
Thomas Wouters89f507f2006-12-13 04:49:30 +0000542 def testHypot(self):
543 self.assertRaises(TypeError, math.hypot)
544 self.ftest('hypot(0,0)', math.hypot(0,0), 0)
545 self.ftest('hypot(3,4)', math.hypot(3,4), 5)
Christian Heimes53876d92008-04-19 00:31:39 +0000546 self.assertEqual(math.hypot(NAN, INF), INF)
547 self.assertEqual(math.hypot(INF, NAN), INF)
548 self.assertEqual(math.hypot(NAN, NINF), INF)
549 self.assertEqual(math.hypot(NINF, NAN), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000550 self.assertTrue(math.isnan(math.hypot(1.0, NAN)))
551 self.assertTrue(math.isnan(math.hypot(NAN, -2.0)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000552
Thomas Wouters89f507f2006-12-13 04:49:30 +0000553 def testLdexp(self):
554 self.assertRaises(TypeError, math.ldexp)
555 self.ftest('ldexp(0,1)', math.ldexp(0,1), 0)
556 self.ftest('ldexp(1,1)', math.ldexp(1,1), 2)
557 self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5)
558 self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2)
Christian Heimes53876d92008-04-19 00:31:39 +0000559 self.assertRaises(OverflowError, math.ldexp, 1., 1000000)
560 self.assertRaises(OverflowError, math.ldexp, -1., 1000000)
561 self.assertEquals(math.ldexp(1., -1000000), 0.)
562 self.assertEquals(math.ldexp(-1., -1000000), -0.)
563 self.assertEquals(math.ldexp(INF, 30), INF)
564 self.assertEquals(math.ldexp(NINF, -213), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000565 self.assertTrue(math.isnan(math.ldexp(NAN, 0)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000566
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000567 # large second argument
568 for n in [10**5, 10**10, 10**20, 10**40]:
569 self.assertEquals(math.ldexp(INF, -n), INF)
570 self.assertEquals(math.ldexp(NINF, -n), NINF)
571 self.assertEquals(math.ldexp(1., -n), 0.)
572 self.assertEquals(math.ldexp(-1., -n), -0.)
573 self.assertEquals(math.ldexp(0., -n), 0.)
574 self.assertEquals(math.ldexp(-0., -n), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000575 self.assertTrue(math.isnan(math.ldexp(NAN, -n)))
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000576
577 self.assertRaises(OverflowError, math.ldexp, 1., n)
578 self.assertRaises(OverflowError, math.ldexp, -1., n)
579 self.assertEquals(math.ldexp(0., n), 0.)
580 self.assertEquals(math.ldexp(-0., n), -0.)
581 self.assertEquals(math.ldexp(INF, n), INF)
582 self.assertEquals(math.ldexp(NINF, n), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000583 self.assertTrue(math.isnan(math.ldexp(NAN, n)))
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000584
Thomas Wouters89f507f2006-12-13 04:49:30 +0000585 def testLog(self):
586 self.assertRaises(TypeError, math.log)
587 self.ftest('log(1/e)', math.log(1/math.e), -1)
588 self.ftest('log(1)', math.log(1), 0)
589 self.ftest('log(e)', math.log(math.e), 1)
590 self.ftest('log(32,2)', math.log(32,2), 5)
591 self.ftest('log(10**40, 10)', math.log(10**40, 10), 40)
592 self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2)
Christian Heimes53876d92008-04-19 00:31:39 +0000593 self.assertEquals(math.log(INF), INF)
594 self.assertRaises(ValueError, math.log, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000595 self.assertTrue(math.isnan(math.log(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000596
597 def testLog1p(self):
598 self.assertRaises(TypeError, math.log1p)
599 self.ftest('log1p(1/e -1)', math.log1p(1/math.e-1), -1)
600 self.ftest('log1p(0)', math.log1p(0), 0)
601 self.ftest('log1p(e-1)', math.log1p(math.e-1), 1)
602 self.ftest('log1p(1)', math.log1p(1), math.log(2))
603 self.assertEquals(math.log1p(INF), INF)
604 self.assertRaises(ValueError, math.log1p, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000605 self.assertTrue(math.isnan(math.log1p(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000606 n= 2**90
607 self.assertAlmostEquals(math.log1p(n), 62.383246250395075)
608 self.assertAlmostEquals(math.log1p(n), math.log1p(float(n)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000609
Thomas Wouters89f507f2006-12-13 04:49:30 +0000610 def testLog10(self):
611 self.assertRaises(TypeError, math.log10)
612 self.ftest('log10(0.1)', math.log10(0.1), -1)
613 self.ftest('log10(1)', math.log10(1), 0)
614 self.ftest('log10(10)', math.log10(10), 1)
Christian Heimes53876d92008-04-19 00:31:39 +0000615 self.assertEquals(math.log(INF), INF)
616 self.assertRaises(ValueError, math.log10, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000617 self.assertTrue(math.isnan(math.log10(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000618
Thomas Wouters89f507f2006-12-13 04:49:30 +0000619 def testModf(self):
620 self.assertRaises(TypeError, math.modf)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000621
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000622 def testmodf(name, result, expected):
623 (v1, v2), (e1, e2) = result, expected
Thomas Wouters89f507f2006-12-13 04:49:30 +0000624 if abs(v1-e1) > eps or abs(v2-e2):
625 self.fail('%s returned %r, expected %r'%\
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000626 (name, result, expected))
Raymond Hettinger64108af2002-05-13 03:55:01 +0000627
Thomas Wouters89f507f2006-12-13 04:49:30 +0000628 testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
629 testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000630
Christian Heimes53876d92008-04-19 00:31:39 +0000631 self.assertEquals(math.modf(INF), (0.0, INF))
632 self.assertEquals(math.modf(NINF), (-0.0, NINF))
633
634 modf_nan = math.modf(NAN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000635 self.assertTrue(math.isnan(modf_nan[0]))
636 self.assertTrue(math.isnan(modf_nan[1]))
Christian Heimes53876d92008-04-19 00:31:39 +0000637
Thomas Wouters89f507f2006-12-13 04:49:30 +0000638 def testPow(self):
639 self.assertRaises(TypeError, math.pow)
640 self.ftest('pow(0,1)', math.pow(0,1), 0)
641 self.ftest('pow(1,0)', math.pow(1,0), 1)
642 self.ftest('pow(2,1)', math.pow(2,1), 2)
643 self.ftest('pow(2,-1)', math.pow(2,-1), 0.5)
Christian Heimes53876d92008-04-19 00:31:39 +0000644 self.assertEqual(math.pow(INF, 1), INF)
645 self.assertEqual(math.pow(NINF, 1), NINF)
646 self.assertEqual((math.pow(1, INF)), 1.)
647 self.assertEqual((math.pow(1, NINF)), 1.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000648 self.assertTrue(math.isnan(math.pow(NAN, 1)))
649 self.assertTrue(math.isnan(math.pow(2, NAN)))
650 self.assertTrue(math.isnan(math.pow(0, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000651 self.assertEqual(math.pow(1, NAN), 1)
Christian Heimesa342c012008-04-20 21:01:16 +0000652
653 # pow(0., x)
654 self.assertEqual(math.pow(0., INF), 0.)
655 self.assertEqual(math.pow(0., 3.), 0.)
656 self.assertEqual(math.pow(0., 2.3), 0.)
657 self.assertEqual(math.pow(0., 2.), 0.)
658 self.assertEqual(math.pow(0., 0.), 1.)
659 self.assertEqual(math.pow(0., -0.), 1.)
660 self.assertRaises(ValueError, math.pow, 0., -2.)
661 self.assertRaises(ValueError, math.pow, 0., -2.3)
662 self.assertRaises(ValueError, math.pow, 0., -3.)
663 self.assertRaises(ValueError, math.pow, 0., NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000664 self.assertTrue(math.isnan(math.pow(0., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000665
666 # pow(INF, x)
667 self.assertEqual(math.pow(INF, INF), INF)
668 self.assertEqual(math.pow(INF, 3.), INF)
669 self.assertEqual(math.pow(INF, 2.3), INF)
670 self.assertEqual(math.pow(INF, 2.), INF)
671 self.assertEqual(math.pow(INF, 0.), 1.)
672 self.assertEqual(math.pow(INF, -0.), 1.)
673 self.assertEqual(math.pow(INF, -2.), 0.)
674 self.assertEqual(math.pow(INF, -2.3), 0.)
675 self.assertEqual(math.pow(INF, -3.), 0.)
676 self.assertEqual(math.pow(INF, NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000677 self.assertTrue(math.isnan(math.pow(INF, NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000678
679 # pow(-0., x)
680 self.assertEqual(math.pow(-0., INF), 0.)
681 self.assertEqual(math.pow(-0., 3.), -0.)
682 self.assertEqual(math.pow(-0., 2.3), 0.)
683 self.assertEqual(math.pow(-0., 2.), 0.)
684 self.assertEqual(math.pow(-0., 0.), 1.)
685 self.assertEqual(math.pow(-0., -0.), 1.)
686 self.assertRaises(ValueError, math.pow, -0., -2.)
687 self.assertRaises(ValueError, math.pow, -0., -2.3)
688 self.assertRaises(ValueError, math.pow, -0., -3.)
689 self.assertRaises(ValueError, math.pow, -0., NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000690 self.assertTrue(math.isnan(math.pow(-0., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000691
692 # pow(NINF, x)
693 self.assertEqual(math.pow(NINF, INF), INF)
694 self.assertEqual(math.pow(NINF, 3.), NINF)
695 self.assertEqual(math.pow(NINF, 2.3), INF)
696 self.assertEqual(math.pow(NINF, 2.), INF)
697 self.assertEqual(math.pow(NINF, 0.), 1.)
698 self.assertEqual(math.pow(NINF, -0.), 1.)
699 self.assertEqual(math.pow(NINF, -2.), 0.)
700 self.assertEqual(math.pow(NINF, -2.3), 0.)
701 self.assertEqual(math.pow(NINF, -3.), -0.)
702 self.assertEqual(math.pow(NINF, NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000703 self.assertTrue(math.isnan(math.pow(NINF, NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000704
705 # pow(-1, x)
706 self.assertEqual(math.pow(-1., INF), 1.)
707 self.assertEqual(math.pow(-1., 3.), -1.)
708 self.assertRaises(ValueError, math.pow, -1., 2.3)
709 self.assertEqual(math.pow(-1., 2.), 1.)
710 self.assertEqual(math.pow(-1., 0.), 1.)
711 self.assertEqual(math.pow(-1., -0.), 1.)
712 self.assertEqual(math.pow(-1., -2.), 1.)
713 self.assertRaises(ValueError, math.pow, -1., -2.3)
714 self.assertEqual(math.pow(-1., -3.), -1.)
715 self.assertEqual(math.pow(-1., NINF), 1.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000716 self.assertTrue(math.isnan(math.pow(-1., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000717
718 # pow(1, x)
719 self.assertEqual(math.pow(1., INF), 1.)
720 self.assertEqual(math.pow(1., 3.), 1.)
721 self.assertEqual(math.pow(1., 2.3), 1.)
722 self.assertEqual(math.pow(1., 2.), 1.)
723 self.assertEqual(math.pow(1., 0.), 1.)
724 self.assertEqual(math.pow(1., -0.), 1.)
725 self.assertEqual(math.pow(1., -2.), 1.)
726 self.assertEqual(math.pow(1., -2.3), 1.)
727 self.assertEqual(math.pow(1., -3.), 1.)
728 self.assertEqual(math.pow(1., NINF), 1.)
729 self.assertEqual(math.pow(1., NAN), 1.)
730
731 # pow(x, 0) should be 1 for any x
732 self.assertEqual(math.pow(2.3, 0.), 1.)
733 self.assertEqual(math.pow(-2.3, 0.), 1.)
734 self.assertEqual(math.pow(NAN, 0.), 1.)
735 self.assertEqual(math.pow(2.3, -0.), 1.)
736 self.assertEqual(math.pow(-2.3, -0.), 1.)
737 self.assertEqual(math.pow(NAN, -0.), 1.)
738
739 # pow(x, y) is invalid if x is negative and y is not integral
740 self.assertRaises(ValueError, math.pow, -1., 2.3)
741 self.assertRaises(ValueError, math.pow, -15., -3.1)
742
743 # pow(x, NINF)
744 self.assertEqual(math.pow(1.9, NINF), 0.)
745 self.assertEqual(math.pow(1.1, NINF), 0.)
746 self.assertEqual(math.pow(0.9, NINF), INF)
747 self.assertEqual(math.pow(0.1, NINF), INF)
748 self.assertEqual(math.pow(-0.1, NINF), INF)
749 self.assertEqual(math.pow(-0.9, NINF), INF)
750 self.assertEqual(math.pow(-1.1, NINF), 0.)
751 self.assertEqual(math.pow(-1.9, NINF), 0.)
752
753 # pow(x, INF)
754 self.assertEqual(math.pow(1.9, INF), INF)
755 self.assertEqual(math.pow(1.1, INF), INF)
756 self.assertEqual(math.pow(0.9, INF), 0.)
757 self.assertEqual(math.pow(0.1, INF), 0.)
758 self.assertEqual(math.pow(-0.1, INF), 0.)
759 self.assertEqual(math.pow(-0.9, INF), 0.)
760 self.assertEqual(math.pow(-1.1, INF), INF)
761 self.assertEqual(math.pow(-1.9, INF), INF)
762
763 # pow(x, y) should work for x negative, y an integer
764 self.ftest('(-2.)**3.', math.pow(-2.0, 3.0), -8.0)
765 self.ftest('(-2.)**2.', math.pow(-2.0, 2.0), 4.0)
766 self.ftest('(-2.)**1.', math.pow(-2.0, 1.0), -2.0)
767 self.ftest('(-2.)**0.', math.pow(-2.0, 0.0), 1.0)
768 self.ftest('(-2.)**-0.', math.pow(-2.0, -0.0), 1.0)
769 self.ftest('(-2.)**-1.', math.pow(-2.0, -1.0), -0.5)
770 self.ftest('(-2.)**-2.', math.pow(-2.0, -2.0), 0.25)
771 self.ftest('(-2.)**-3.', math.pow(-2.0, -3.0), -0.125)
772 self.assertRaises(ValueError, math.pow, -2.0, -0.5)
773 self.assertRaises(ValueError, math.pow, -2.0, 0.5)
774
775 # the following tests have been commented out since they don't
776 # really belong here: the implementation of ** for floats is
777 # independent of the implemention of math.pow
778 #self.assertEqual(1**NAN, 1)
779 #self.assertEqual(1**INF, 1)
780 #self.assertEqual(1**NINF, 1)
781 #self.assertEqual(1**0, 1)
782 #self.assertEqual(1.**NAN, 1)
783 #self.assertEqual(1.**INF, 1)
784 #self.assertEqual(1.**NINF, 1)
785 #self.assertEqual(1.**0, 1)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000786
Thomas Wouters89f507f2006-12-13 04:49:30 +0000787 def testRadians(self):
788 self.assertRaises(TypeError, math.radians)
789 self.ftest('radians(180)', math.radians(180), math.pi)
790 self.ftest('radians(90)', math.radians(90), math.pi/2)
791 self.ftest('radians(-45)', math.radians(-45), -math.pi/4)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000792
Thomas Wouters89f507f2006-12-13 04:49:30 +0000793 def testSin(self):
794 self.assertRaises(TypeError, math.sin)
795 self.ftest('sin(0)', math.sin(0), 0)
796 self.ftest('sin(pi/2)', math.sin(math.pi/2), 1)
797 self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000798 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000799 self.assertTrue(math.isnan(math.sin(INF)))
800 self.assertTrue(math.isnan(math.sin(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +0000801 except ValueError:
802 self.assertRaises(ValueError, math.sin, INF)
803 self.assertRaises(ValueError, math.sin, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000804 self.assertTrue(math.isnan(math.sin(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000805
Thomas Wouters89f507f2006-12-13 04:49:30 +0000806 def testSinh(self):
807 self.assertRaises(TypeError, math.sinh)
808 self.ftest('sinh(0)', math.sinh(0), 0)
809 self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1)
810 self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0)
Christian Heimes53876d92008-04-19 00:31:39 +0000811 self.assertEquals(math.sinh(INF), INF)
Christian Heimesa342c012008-04-20 21:01:16 +0000812 self.assertEquals(math.sinh(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000813 self.assertTrue(math.isnan(math.sinh(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +0000814
Thomas Wouters89f507f2006-12-13 04:49:30 +0000815 def testSqrt(self):
816 self.assertRaises(TypeError, math.sqrt)
817 self.ftest('sqrt(0)', math.sqrt(0), 0)
818 self.ftest('sqrt(1)', math.sqrt(1), 1)
819 self.ftest('sqrt(4)', math.sqrt(4), 2)
Christian Heimes53876d92008-04-19 00:31:39 +0000820 self.assertEquals(math.sqrt(INF), INF)
821 self.assertRaises(ValueError, math.sqrt, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000822 self.assertTrue(math.isnan(math.sqrt(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +0000823
Thomas Wouters89f507f2006-12-13 04:49:30 +0000824 def testTan(self):
825 self.assertRaises(TypeError, math.tan)
826 self.ftest('tan(0)', math.tan(0), 0)
827 self.ftest('tan(pi/4)', math.tan(math.pi/4), 1)
828 self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000829 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000830 self.assertTrue(math.isnan(math.tan(INF)))
831 self.assertTrue(math.isnan(math.tan(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +0000832 except:
833 self.assertRaises(ValueError, math.tan, INF)
834 self.assertRaises(ValueError, math.tan, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000835 self.assertTrue(math.isnan(math.tan(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +0000836
Thomas Wouters89f507f2006-12-13 04:49:30 +0000837 def testTanh(self):
838 self.assertRaises(TypeError, math.tanh)
839 self.ftest('tanh(0)', math.tanh(0), 0)
840 self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0)
Christian Heimes53876d92008-04-19 00:31:39 +0000841 self.ftest('tanh(inf)', math.tanh(INF), 1)
842 self.ftest('tanh(-inf)', math.tanh(NINF), -1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000843 self.assertTrue(math.isnan(math.tanh(NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000844 # check that tanh(-0.) == -0. on IEEE 754 systems
845 if float.__getformat__("double").startswith("IEEE"):
846 self.assertEqual(math.tanh(-0.), -0.)
847 self.assertEqual(math.copysign(1., math.tanh(-0.)),
848 math.copysign(1., -0.))
Tim Peters1d120612000-10-12 06:10:25 +0000849
Christian Heimes400adb02008-02-01 08:12:03 +0000850 def test_trunc(self):
851 self.assertEqual(math.trunc(1), 1)
852 self.assertEqual(math.trunc(-1), -1)
853 self.assertEqual(type(math.trunc(1)), int)
854 self.assertEqual(type(math.trunc(1.5)), int)
855 self.assertEqual(math.trunc(1.5), 1)
856 self.assertEqual(math.trunc(-1.5), -1)
857 self.assertEqual(math.trunc(1.999999), 1)
858 self.assertEqual(math.trunc(-1.999999), -1)
859 self.assertEqual(math.trunc(-0.999999), -0)
860 self.assertEqual(math.trunc(-100.999), -100)
861
862 class TestTrunc(object):
863 def __trunc__(self):
864 return 23
865
866 class TestNoTrunc(object):
867 pass
868
869 self.assertEqual(math.trunc(TestTrunc()), 23)
870
871 self.assertRaises(TypeError, math.trunc)
872 self.assertRaises(TypeError, math.trunc, 1, 2)
873 self.assertRaises(TypeError, math.trunc, TestNoTrunc())
874
875 # XXX Doesn't work because the method is looked up on
876 # the type only.
877 #t = TestNoTrunc()
878 #t.__trunc__ = lambda *args: args
879 #self.assertEquals((), math.trunc(t))
880 #self.assertRaises(TypeError, math.trunc, t, 0)
881
Christian Heimes072c0f12008-01-03 23:01:04 +0000882 def testIsnan(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000883 self.assertTrue(math.isnan(float("nan")))
884 self.assertTrue(math.isnan(float("inf")* 0.))
885 self.assertFalse(math.isnan(float("inf")))
886 self.assertFalse(math.isnan(0.))
887 self.assertFalse(math.isnan(1.))
Christian Heimes072c0f12008-01-03 23:01:04 +0000888
889 def testIsinf(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000890 self.assertTrue(math.isinf(float("inf")))
891 self.assertTrue(math.isinf(float("-inf")))
892 self.assertTrue(math.isinf(1E400))
893 self.assertTrue(math.isinf(-1E400))
894 self.assertFalse(math.isinf(float("nan")))
895 self.assertFalse(math.isinf(0.))
896 self.assertFalse(math.isinf(1.))
Christian Heimes072c0f12008-01-03 23:01:04 +0000897
Thomas Wouters89f507f2006-12-13 04:49:30 +0000898 # RED_FLAG 16-Oct-2000 Tim
899 # While 2.0 is more consistent about exceptions than previous releases, it
900 # still fails this part of the test on some platforms. For now, we only
901 # *run* test_exceptions() in verbose mode, so that this isn't normally
902 # tested.
Tim Peters98c81842000-10-16 17:35:13 +0000903
Thomas Wouters89f507f2006-12-13 04:49:30 +0000904 if verbose:
905 def test_exceptions(self):
906 try:
907 x = math.exp(-1000000000)
908 except:
909 # mathmodule.c is failing to weed out underflows from libm, or
910 # we've got an fp format with huge dynamic range
911 self.fail("underflowing exp() should not have raised "
912 "an exception")
913 if x != 0:
914 self.fail("underflowing exp() should have returned 0")
915
916 # If this fails, probably using a strict IEEE-754 conforming libm, and x
917 # is +Inf afterwards. But Python wants overflows detected by default.
918 try:
919 x = math.exp(1000000000)
920 except OverflowError:
921 pass
922 else:
923 self.fail("overflowing exp() didn't trigger OverflowError")
924
925 # If this fails, it could be a puzzle. One odd possibility is that
926 # mathmodule.c's macros are getting confused while comparing
927 # Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE
928 # as a result (and so raising OverflowError instead).
929 try:
930 x = math.sqrt(-1.0)
931 except ValueError:
932 pass
933 else:
934 self.fail("sqrt(-1) didn't raise ValueError")
935
Mark Dickinson63566232009-09-18 21:04:19 +0000936 @requires_IEEE_754
Christian Heimes53876d92008-04-19 00:31:39 +0000937 def test_testfile(self):
Christian Heimes53876d92008-04-19 00:31:39 +0000938 for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file):
939 # Skip if either the input or result is complex, or if
940 # flags is nonempty
941 if ai != 0. or ei != 0. or flags:
942 continue
943 if fn in ['rect', 'polar']:
944 # no real versions of rect, polar
945 continue
946 func = getattr(math, fn)
Christian Heimesa342c012008-04-20 21:01:16 +0000947 try:
948 result = func(ar)
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000949 except ValueError as exc:
950 message = (("Unexpected ValueError: %s\n " +
951 "in test %s:%s(%r)\n") % (exc.args[0], id, fn, ar))
Christian Heimesa342c012008-04-20 21:01:16 +0000952 self.fail(message)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000953 except OverflowError:
954 message = ("Unexpected OverflowError in " +
955 "test %s:%s(%r)\n" % (id, fn, ar))
956 self.fail(message)
Christian Heimes53876d92008-04-19 00:31:39 +0000957 self.ftest("%s:%s(%r)" % (id, fn, ar), result, er)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000958
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000959 @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
960 "test requires IEEE 754 doubles")
961 def test_mtestfile(self):
962 ALLOWED_ERROR = 20 # permitted error, in ulps
963 fail_fmt = "{}:{}({!r}): expected {!r}, got {!r}"
964
965 failures = []
966 for id, fn, arg, expected, flags in parse_mtestfile(math_testcases):
967 func = getattr(math, fn)
968
969 if 'invalid' in flags or 'divide-by-zero' in flags:
970 expected = 'ValueError'
971 elif 'overflow' in flags:
972 expected = 'OverflowError'
973
974 try:
975 got = func(arg)
976 except ValueError:
977 got = 'ValueError'
978 except OverflowError:
979 got = 'OverflowError'
980
Mark Dickinson05d2e082009-12-11 20:17:17 +0000981 accuracy_failure = None
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000982 if isinstance(got, float) and isinstance(expected, float):
983 if math.isnan(expected) and math.isnan(got):
984 continue
985 if not math.isnan(expected) and not math.isnan(got):
Mark Dickinson664b5112009-12-16 20:23:42 +0000986 if fn == 'lgamma':
987 # we use a weaker accuracy test for lgamma;
988 # lgamma only achieves an absolute error of
989 # a few multiples of the machine accuracy, in
990 # general.
Mark Dickinson05d2e082009-12-11 20:17:17 +0000991 accuracy_failure = acc_check(expected, got,
992 rel_err = 5e-15,
993 abs_err = 5e-15)
994 else:
Mark Dickinson664b5112009-12-16 20:23:42 +0000995 accuracy_failure = ulps_check(expected, got, 20)
Mark Dickinson05d2e082009-12-11 20:17:17 +0000996 if accuracy_failure is None:
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000997 continue
998
999 if isinstance(got, str) and isinstance(expected, str):
1000 if got == expected:
1001 continue
1002
1003 fail_msg = fail_fmt.format(id, fn, arg, expected, got)
Mark Dickinson05d2e082009-12-11 20:17:17 +00001004 if accuracy_failure is not None:
1005 fail_msg += ' ({})'.format(accuracy_failure)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001006 failures.append(fail_msg)
1007
1008 if failures:
1009 self.fail('Failures in test_mtestfile:\n ' +
1010 '\n '.join(failures))
1011
1012
Thomas Wouters89f507f2006-12-13 04:49:30 +00001013def test_main():
Christian Heimes53876d92008-04-19 00:31:39 +00001014 from doctest import DocFileSuite
1015 suite = unittest.TestSuite()
1016 suite.addTest(unittest.makeSuite(MathTests))
1017 suite.addTest(DocFileSuite("ieee754.txt"))
1018 run_unittest(suite)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001019
1020if __name__ == '__main__':
1021 test_main()