blob: 20524300212ebd8b61a6984c4451a9be25e054e6 [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):
292 self.assertRaises(TypeError, math.copysign)
293 # copysign should let us distinguish signs of zeros
294 self.assertEquals(copysign(1., 0.), 1.)
295 self.assertEquals(copysign(1., -0.), -1.)
296 self.assertEquals(copysign(INF, 0.), INF)
297 self.assertEquals(copysign(INF, -0.), NINF)
298 self.assertEquals(copysign(NINF, 0.), INF)
299 self.assertEquals(copysign(NINF, -0.), NINF)
300 # and of infinities
301 self.assertEquals(copysign(1., INF), 1.)
302 self.assertEquals(copysign(1., NINF), -1.)
303 self.assertEquals(copysign(INF, INF), INF)
304 self.assertEquals(copysign(INF, NINF), NINF)
305 self.assertEquals(copysign(NINF, INF), INF)
306 self.assertEquals(copysign(NINF, NINF), NINF)
307 self.assertTrue(math.isnan(copysign(NAN, 1.)))
308 self.assertTrue(math.isnan(copysign(NAN, INF)))
309 self.assertTrue(math.isnan(copysign(NAN, NINF)))
310 self.assertTrue(math.isnan(copysign(NAN, NAN)))
311 # copysign(INF, NAN) may be INF or it may be NINF, since
312 # we don't know whether the sign bit of NAN is set on any
313 # given platform.
314 self.assertTrue(math.isinf(copysign(INF, NAN)))
315 # similarly, copysign(2., NAN) could be 2. or -2.
316 self.assertEquals(abs(copysign(2., NAN)), 2.)
Christian Heimes53876d92008-04-19 00:31:39 +0000317
Thomas Wouters89f507f2006-12-13 04:49:30 +0000318 def testCos(self):
319 self.assertRaises(TypeError, math.cos)
320 self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0)
321 self.ftest('cos(0)', math.cos(0), 1)
322 self.ftest('cos(pi/2)', math.cos(math.pi/2), 0)
323 self.ftest('cos(pi)', math.cos(math.pi), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000324 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000325 self.assertTrue(math.isnan(math.cos(INF)))
326 self.assertTrue(math.isnan(math.cos(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +0000327 except ValueError:
328 self.assertRaises(ValueError, math.cos, INF)
329 self.assertRaises(ValueError, math.cos, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000330 self.assertTrue(math.isnan(math.cos(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000331
Thomas Wouters89f507f2006-12-13 04:49:30 +0000332 def testCosh(self):
333 self.assertRaises(TypeError, math.cosh)
334 self.ftest('cosh(0)', math.cosh(0), 1)
335 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 +0000336 self.assertEquals(math.cosh(INF), INF)
337 self.assertEquals(math.cosh(NINF), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000338 self.assertTrue(math.isnan(math.cosh(NAN)))
Raymond Hettinger64108af2002-05-13 03:55:01 +0000339
Thomas Wouters89f507f2006-12-13 04:49:30 +0000340 def testDegrees(self):
341 self.assertRaises(TypeError, math.degrees)
342 self.ftest('degrees(pi)', math.degrees(math.pi), 180.0)
343 self.ftest('degrees(pi/2)', math.degrees(math.pi/2), 90.0)
344 self.ftest('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000345
Thomas Wouters89f507f2006-12-13 04:49:30 +0000346 def testExp(self):
347 self.assertRaises(TypeError, math.exp)
348 self.ftest('exp(-1)', math.exp(-1), 1/math.e)
349 self.ftest('exp(0)', math.exp(0), 1)
350 self.ftest('exp(1)', math.exp(1), math.e)
Christian Heimes53876d92008-04-19 00:31:39 +0000351 self.assertEquals(math.exp(INF), INF)
352 self.assertEquals(math.exp(NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000353 self.assertTrue(math.isnan(math.exp(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000354
Thomas Wouters89f507f2006-12-13 04:49:30 +0000355 def testFabs(self):
356 self.assertRaises(TypeError, math.fabs)
357 self.ftest('fabs(-1)', math.fabs(-1), 1)
358 self.ftest('fabs(0)', math.fabs(0), 0)
359 self.ftest('fabs(1)', math.fabs(1), 1)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000360
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000361 def testFactorial(self):
362 def fact(n):
363 result = 1
364 for i in range(1, int(n)+1):
365 result *= i
366 return result
367 values = list(range(10)) + [50, 100, 500]
368 random.shuffle(values)
369 for x in range(10):
370 for cast in (int, float):
371 self.assertEqual(math.factorial(cast(x)), fact(x), (x, fact(x), math.factorial(x)))
372 self.assertRaises(ValueError, math.factorial, -1)
373 self.assertRaises(ValueError, math.factorial, math.pi)
374
Thomas Wouters89f507f2006-12-13 04:49:30 +0000375 def testFloor(self):
376 self.assertRaises(TypeError, math.floor)
Jeffrey Yasskinc2155832008-01-05 20:03:11 +0000377 self.assertEquals(int, type(math.floor(0.5)))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000378 self.ftest('floor(0.5)', math.floor(0.5), 0)
379 self.ftest('floor(1.0)', math.floor(1.0), 1)
380 self.ftest('floor(1.5)', math.floor(1.5), 1)
381 self.ftest('floor(-0.5)', math.floor(-0.5), -1)
382 self.ftest('floor(-1.0)', math.floor(-1.0), -1)
383 self.ftest('floor(-1.5)', math.floor(-1.5), -2)
Guido van Rossum806c2462007-08-06 23:33:07 +0000384 # pow() relies on floor() to check for integers
385 # This fails on some platforms - so check it here
386 self.ftest('floor(1.23e167)', math.floor(1.23e167), 1.23e167)
387 self.ftest('floor(-1.23e167)', math.floor(-1.23e167), -1.23e167)
Christian Heimes53876d92008-04-19 00:31:39 +0000388 #self.assertEquals(math.ceil(INF), INF)
389 #self.assertEquals(math.ceil(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000390 #self.assertTrue(math.isnan(math.floor(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000391
Guido van Rossum13e05de2007-08-23 22:56:55 +0000392 class TestFloor:
393 def __floor__(self):
394 return 42
395 class TestNoFloor:
396 pass
397 self.ftest('floor(TestFloor())', math.floor(TestFloor()), 42)
398 self.assertRaises(TypeError, math.floor, TestNoFloor())
399
400 t = TestNoFloor()
401 t.__floor__ = lambda *args: args
402 self.assertRaises(TypeError, math.floor, t)
403 self.assertRaises(TypeError, math.floor, t, 0)
404
Thomas Wouters89f507f2006-12-13 04:49:30 +0000405 def testFmod(self):
406 self.assertRaises(TypeError, math.fmod)
407 self.ftest('fmod(10,1)', math.fmod(10,1), 0)
408 self.ftest('fmod(10,0.5)', math.fmod(10,0.5), 0)
409 self.ftest('fmod(10,1.5)', math.fmod(10,1.5), 1)
410 self.ftest('fmod(-10,1)', math.fmod(-10,1), 0)
411 self.ftest('fmod(-10,0.5)', math.fmod(-10,0.5), 0)
412 self.ftest('fmod(-10,1.5)', math.fmod(-10,1.5), -1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000413 self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
414 self.assertTrue(math.isnan(math.fmod(1., NAN)))
415 self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000416 self.assertRaises(ValueError, math.fmod, 1., 0.)
417 self.assertRaises(ValueError, math.fmod, INF, 1.)
418 self.assertRaises(ValueError, math.fmod, NINF, 1.)
419 self.assertRaises(ValueError, math.fmod, INF, 0.)
420 self.assertEquals(math.fmod(3.0, INF), 3.0)
421 self.assertEquals(math.fmod(-3.0, INF), -3.0)
422 self.assertEquals(math.fmod(3.0, NINF), 3.0)
423 self.assertEquals(math.fmod(-3.0, NINF), -3.0)
424 self.assertEquals(math.fmod(0.0, 3.0), 0.0)
425 self.assertEquals(math.fmod(0.0, NINF), 0.0)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000426
Thomas Wouters89f507f2006-12-13 04:49:30 +0000427 def testFrexp(self):
428 self.assertRaises(TypeError, math.frexp)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000429
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000430 def testfrexp(name, result, expected):
431 (mant, exp), (emant, eexp) = result, expected
Thomas Wouters89f507f2006-12-13 04:49:30 +0000432 if abs(mant-emant) > eps or exp != eexp:
433 self.fail('%s returned %r, expected %r'%\
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000434 (name, result, expected))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000435
Thomas Wouters89f507f2006-12-13 04:49:30 +0000436 testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
437 testfrexp('frexp(0)', math.frexp(0), (0, 0))
438 testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
439 testfrexp('frexp(2)', math.frexp(2), (0.5, 2))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000440
Christian Heimes53876d92008-04-19 00:31:39 +0000441 self.assertEquals(math.frexp(INF)[0], INF)
442 self.assertEquals(math.frexp(NINF)[0], NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000443 self.assertTrue(math.isnan(math.frexp(NAN)[0]))
Christian Heimes53876d92008-04-19 00:31:39 +0000444
Mark Dickinson63566232009-09-18 21:04:19 +0000445 @requires_IEEE_754
Mark Dickinson5c567082009-04-24 16:39:07 +0000446 @unittest.skipIf(HAVE_DOUBLE_ROUNDING,
447 "fsum is not exact on machines with double rounding")
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000448 def testFsum(self):
449 # math.fsum relies on exact rounding for correct operation.
450 # There's a known problem with IA32 floating-point that causes
451 # inexact rounding in some situations, and will cause the
452 # math.fsum tests below to fail; see issue #2937. On non IEEE
453 # 754 platforms, and on IEEE 754 platforms that exhibit the
454 # problem described in issue #2937, we simply skip the whole
455 # test.
456
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000457 # Python version of math.fsum, for comparison. Uses a
458 # different algorithm based on frexp, ldexp and integer
459 # arithmetic.
460 from sys import float_info
461 mant_dig = float_info.mant_dig
462 etiny = float_info.min_exp - mant_dig
463
464 def msum(iterable):
465 """Full precision summation. Compute sum(iterable) without any
466 intermediate accumulation of error. Based on the 'lsum' function
467 at http://code.activestate.com/recipes/393090/
468
469 """
470 tmant, texp = 0, 0
471 for x in iterable:
472 mant, exp = math.frexp(x)
473 mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig
474 if texp > exp:
475 tmant <<= texp-exp
476 texp = exp
477 else:
478 mant <<= exp-texp
479 tmant += mant
480 # Round tmant * 2**texp to a float. The original recipe
481 # used float(str(tmant)) * 2.0**texp for this, but that's
482 # a little unsafe because str -> float conversion can't be
483 # relied upon to do correct rounding on all platforms.
484 tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp)
485 if tail > 0:
486 h = 1 << (tail-1)
487 tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1)
488 texp += tail
489 return math.ldexp(tmant, texp)
490
491 test_values = [
492 ([], 0.0),
493 ([0.0], 0.0),
494 ([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100),
495 ([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0),
496 ([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0),
497 ([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0),
498 ([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0),
499 ([1./n for n in range(1, 1001)],
500 float.fromhex('0x1.df11f45f4e61ap+2')),
501 ([(-1.)**n/n for n in range(1, 1001)],
502 float.fromhex('-0x1.62a2af1bd3624p-1')),
503 ([1.7**(i+1)-1.7**i for i in range(1000)] + [-1.7**1000], -1.0),
504 ([1e16, 1., 1e-16], 10000000000000002.0),
505 ([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0),
506 # exercise code for resizing partials array
507 ([2.**n - 2.**(n+50) + 2.**(n+52) for n in range(-1074, 972, 2)] +
508 [-2.**1022],
509 float.fromhex('0x1.5555555555555p+970')),
510 ]
511
512 for i, (vals, expected) in enumerate(test_values):
513 try:
514 actual = math.fsum(vals)
515 except OverflowError:
516 self.fail("test %d failed: got OverflowError, expected %r "
517 "for math.fsum(%.100r)" % (i, expected, vals))
518 except ValueError:
519 self.fail("test %d failed: got ValueError, expected %r "
520 "for math.fsum(%.100r)" % (i, expected, vals))
521 self.assertEqual(actual, expected)
522
523 from random import random, gauss, shuffle
524 for j in range(1000):
525 vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10
526 s = 0
527 for i in range(200):
528 v = gauss(0, random()) ** 7 - s
529 s += v
530 vals.append(v)
531 shuffle(vals)
532
533 s = msum(vals)
534 self.assertEqual(msum(vals), math.fsum(vals))
535
Thomas Wouters89f507f2006-12-13 04:49:30 +0000536 def testHypot(self):
537 self.assertRaises(TypeError, math.hypot)
538 self.ftest('hypot(0,0)', math.hypot(0,0), 0)
539 self.ftest('hypot(3,4)', math.hypot(3,4), 5)
Christian Heimes53876d92008-04-19 00:31:39 +0000540 self.assertEqual(math.hypot(NAN, INF), INF)
541 self.assertEqual(math.hypot(INF, NAN), INF)
542 self.assertEqual(math.hypot(NAN, NINF), INF)
543 self.assertEqual(math.hypot(NINF, NAN), INF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000544 self.assertTrue(math.isnan(math.hypot(1.0, NAN)))
545 self.assertTrue(math.isnan(math.hypot(NAN, -2.0)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000546
Thomas Wouters89f507f2006-12-13 04:49:30 +0000547 def testLdexp(self):
548 self.assertRaises(TypeError, math.ldexp)
549 self.ftest('ldexp(0,1)', math.ldexp(0,1), 0)
550 self.ftest('ldexp(1,1)', math.ldexp(1,1), 2)
551 self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5)
552 self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2)
Christian Heimes53876d92008-04-19 00:31:39 +0000553 self.assertRaises(OverflowError, math.ldexp, 1., 1000000)
554 self.assertRaises(OverflowError, math.ldexp, -1., 1000000)
555 self.assertEquals(math.ldexp(1., -1000000), 0.)
556 self.assertEquals(math.ldexp(-1., -1000000), -0.)
557 self.assertEquals(math.ldexp(INF, 30), INF)
558 self.assertEquals(math.ldexp(NINF, -213), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000559 self.assertTrue(math.isnan(math.ldexp(NAN, 0)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000560
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000561 # large second argument
562 for n in [10**5, 10**10, 10**20, 10**40]:
563 self.assertEquals(math.ldexp(INF, -n), INF)
564 self.assertEquals(math.ldexp(NINF, -n), NINF)
565 self.assertEquals(math.ldexp(1., -n), 0.)
566 self.assertEquals(math.ldexp(-1., -n), -0.)
567 self.assertEquals(math.ldexp(0., -n), 0.)
568 self.assertEquals(math.ldexp(-0., -n), -0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000569 self.assertTrue(math.isnan(math.ldexp(NAN, -n)))
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000570
571 self.assertRaises(OverflowError, math.ldexp, 1., n)
572 self.assertRaises(OverflowError, math.ldexp, -1., n)
573 self.assertEquals(math.ldexp(0., n), 0.)
574 self.assertEquals(math.ldexp(-0., n), -0.)
575 self.assertEquals(math.ldexp(INF, n), INF)
576 self.assertEquals(math.ldexp(NINF, n), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000577 self.assertTrue(math.isnan(math.ldexp(NAN, n)))
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000578
Thomas Wouters89f507f2006-12-13 04:49:30 +0000579 def testLog(self):
580 self.assertRaises(TypeError, math.log)
581 self.ftest('log(1/e)', math.log(1/math.e), -1)
582 self.ftest('log(1)', math.log(1), 0)
583 self.ftest('log(e)', math.log(math.e), 1)
584 self.ftest('log(32,2)', math.log(32,2), 5)
585 self.ftest('log(10**40, 10)', math.log(10**40, 10), 40)
586 self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2)
Christian Heimes53876d92008-04-19 00:31:39 +0000587 self.assertEquals(math.log(INF), INF)
588 self.assertRaises(ValueError, math.log, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000589 self.assertTrue(math.isnan(math.log(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000590
591 def testLog1p(self):
592 self.assertRaises(TypeError, math.log1p)
593 self.ftest('log1p(1/e -1)', math.log1p(1/math.e-1), -1)
594 self.ftest('log1p(0)', math.log1p(0), 0)
595 self.ftest('log1p(e-1)', math.log1p(math.e-1), 1)
596 self.ftest('log1p(1)', math.log1p(1), math.log(2))
597 self.assertEquals(math.log1p(INF), INF)
598 self.assertRaises(ValueError, math.log1p, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000599 self.assertTrue(math.isnan(math.log1p(NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000600 n= 2**90
601 self.assertAlmostEquals(math.log1p(n), 62.383246250395075)
602 self.assertAlmostEquals(math.log1p(n), math.log1p(float(n)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000603
Thomas Wouters89f507f2006-12-13 04:49:30 +0000604 def testLog10(self):
605 self.assertRaises(TypeError, math.log10)
606 self.ftest('log10(0.1)', math.log10(0.1), -1)
607 self.ftest('log10(1)', math.log10(1), 0)
608 self.ftest('log10(10)', math.log10(10), 1)
Christian Heimes53876d92008-04-19 00:31:39 +0000609 self.assertEquals(math.log(INF), INF)
610 self.assertRaises(ValueError, math.log10, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000611 self.assertTrue(math.isnan(math.log10(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000612
Thomas Wouters89f507f2006-12-13 04:49:30 +0000613 def testModf(self):
614 self.assertRaises(TypeError, math.modf)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000615
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000616 def testmodf(name, result, expected):
617 (v1, v2), (e1, e2) = result, expected
Thomas Wouters89f507f2006-12-13 04:49:30 +0000618 if abs(v1-e1) > eps or abs(v2-e2):
619 self.fail('%s returned %r, expected %r'%\
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000620 (name, result, expected))
Raymond Hettinger64108af2002-05-13 03:55:01 +0000621
Thomas Wouters89f507f2006-12-13 04:49:30 +0000622 testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
623 testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000624
Christian Heimes53876d92008-04-19 00:31:39 +0000625 self.assertEquals(math.modf(INF), (0.0, INF))
626 self.assertEquals(math.modf(NINF), (-0.0, NINF))
627
628 modf_nan = math.modf(NAN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000629 self.assertTrue(math.isnan(modf_nan[0]))
630 self.assertTrue(math.isnan(modf_nan[1]))
Christian Heimes53876d92008-04-19 00:31:39 +0000631
Thomas Wouters89f507f2006-12-13 04:49:30 +0000632 def testPow(self):
633 self.assertRaises(TypeError, math.pow)
634 self.ftest('pow(0,1)', math.pow(0,1), 0)
635 self.ftest('pow(1,0)', math.pow(1,0), 1)
636 self.ftest('pow(2,1)', math.pow(2,1), 2)
637 self.ftest('pow(2,-1)', math.pow(2,-1), 0.5)
Christian Heimes53876d92008-04-19 00:31:39 +0000638 self.assertEqual(math.pow(INF, 1), INF)
639 self.assertEqual(math.pow(NINF, 1), NINF)
640 self.assertEqual((math.pow(1, INF)), 1.)
641 self.assertEqual((math.pow(1, NINF)), 1.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000642 self.assertTrue(math.isnan(math.pow(NAN, 1)))
643 self.assertTrue(math.isnan(math.pow(2, NAN)))
644 self.assertTrue(math.isnan(math.pow(0, NAN)))
Christian Heimes53876d92008-04-19 00:31:39 +0000645 self.assertEqual(math.pow(1, NAN), 1)
Christian Heimesa342c012008-04-20 21:01:16 +0000646
647 # pow(0., x)
648 self.assertEqual(math.pow(0., INF), 0.)
649 self.assertEqual(math.pow(0., 3.), 0.)
650 self.assertEqual(math.pow(0., 2.3), 0.)
651 self.assertEqual(math.pow(0., 2.), 0.)
652 self.assertEqual(math.pow(0., 0.), 1.)
653 self.assertEqual(math.pow(0., -0.), 1.)
654 self.assertRaises(ValueError, math.pow, 0., -2.)
655 self.assertRaises(ValueError, math.pow, 0., -2.3)
656 self.assertRaises(ValueError, math.pow, 0., -3.)
657 self.assertRaises(ValueError, math.pow, 0., NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000658 self.assertTrue(math.isnan(math.pow(0., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000659
660 # pow(INF, x)
661 self.assertEqual(math.pow(INF, INF), INF)
662 self.assertEqual(math.pow(INF, 3.), INF)
663 self.assertEqual(math.pow(INF, 2.3), INF)
664 self.assertEqual(math.pow(INF, 2.), INF)
665 self.assertEqual(math.pow(INF, 0.), 1.)
666 self.assertEqual(math.pow(INF, -0.), 1.)
667 self.assertEqual(math.pow(INF, -2.), 0.)
668 self.assertEqual(math.pow(INF, -2.3), 0.)
669 self.assertEqual(math.pow(INF, -3.), 0.)
670 self.assertEqual(math.pow(INF, NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000671 self.assertTrue(math.isnan(math.pow(INF, NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000672
673 # pow(-0., x)
674 self.assertEqual(math.pow(-0., INF), 0.)
675 self.assertEqual(math.pow(-0., 3.), -0.)
676 self.assertEqual(math.pow(-0., 2.3), 0.)
677 self.assertEqual(math.pow(-0., 2.), 0.)
678 self.assertEqual(math.pow(-0., 0.), 1.)
679 self.assertEqual(math.pow(-0., -0.), 1.)
680 self.assertRaises(ValueError, math.pow, -0., -2.)
681 self.assertRaises(ValueError, math.pow, -0., -2.3)
682 self.assertRaises(ValueError, math.pow, -0., -3.)
683 self.assertRaises(ValueError, math.pow, -0., NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000684 self.assertTrue(math.isnan(math.pow(-0., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000685
686 # pow(NINF, x)
687 self.assertEqual(math.pow(NINF, INF), INF)
688 self.assertEqual(math.pow(NINF, 3.), NINF)
689 self.assertEqual(math.pow(NINF, 2.3), INF)
690 self.assertEqual(math.pow(NINF, 2.), INF)
691 self.assertEqual(math.pow(NINF, 0.), 1.)
692 self.assertEqual(math.pow(NINF, -0.), 1.)
693 self.assertEqual(math.pow(NINF, -2.), 0.)
694 self.assertEqual(math.pow(NINF, -2.3), 0.)
695 self.assertEqual(math.pow(NINF, -3.), -0.)
696 self.assertEqual(math.pow(NINF, NINF), 0.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000697 self.assertTrue(math.isnan(math.pow(NINF, NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000698
699 # pow(-1, x)
700 self.assertEqual(math.pow(-1., INF), 1.)
701 self.assertEqual(math.pow(-1., 3.), -1.)
702 self.assertRaises(ValueError, math.pow, -1., 2.3)
703 self.assertEqual(math.pow(-1., 2.), 1.)
704 self.assertEqual(math.pow(-1., 0.), 1.)
705 self.assertEqual(math.pow(-1., -0.), 1.)
706 self.assertEqual(math.pow(-1., -2.), 1.)
707 self.assertRaises(ValueError, math.pow, -1., -2.3)
708 self.assertEqual(math.pow(-1., -3.), -1.)
709 self.assertEqual(math.pow(-1., NINF), 1.)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000710 self.assertTrue(math.isnan(math.pow(-1., NAN)))
Christian Heimesa342c012008-04-20 21:01:16 +0000711
712 # pow(1, x)
713 self.assertEqual(math.pow(1., INF), 1.)
714 self.assertEqual(math.pow(1., 3.), 1.)
715 self.assertEqual(math.pow(1., 2.3), 1.)
716 self.assertEqual(math.pow(1., 2.), 1.)
717 self.assertEqual(math.pow(1., 0.), 1.)
718 self.assertEqual(math.pow(1., -0.), 1.)
719 self.assertEqual(math.pow(1., -2.), 1.)
720 self.assertEqual(math.pow(1., -2.3), 1.)
721 self.assertEqual(math.pow(1., -3.), 1.)
722 self.assertEqual(math.pow(1., NINF), 1.)
723 self.assertEqual(math.pow(1., NAN), 1.)
724
725 # pow(x, 0) should be 1 for any x
726 self.assertEqual(math.pow(2.3, 0.), 1.)
727 self.assertEqual(math.pow(-2.3, 0.), 1.)
728 self.assertEqual(math.pow(NAN, 0.), 1.)
729 self.assertEqual(math.pow(2.3, -0.), 1.)
730 self.assertEqual(math.pow(-2.3, -0.), 1.)
731 self.assertEqual(math.pow(NAN, -0.), 1.)
732
733 # pow(x, y) is invalid if x is negative and y is not integral
734 self.assertRaises(ValueError, math.pow, -1., 2.3)
735 self.assertRaises(ValueError, math.pow, -15., -3.1)
736
737 # pow(x, NINF)
738 self.assertEqual(math.pow(1.9, NINF), 0.)
739 self.assertEqual(math.pow(1.1, NINF), 0.)
740 self.assertEqual(math.pow(0.9, NINF), INF)
741 self.assertEqual(math.pow(0.1, NINF), INF)
742 self.assertEqual(math.pow(-0.1, NINF), INF)
743 self.assertEqual(math.pow(-0.9, NINF), INF)
744 self.assertEqual(math.pow(-1.1, NINF), 0.)
745 self.assertEqual(math.pow(-1.9, NINF), 0.)
746
747 # pow(x, INF)
748 self.assertEqual(math.pow(1.9, INF), INF)
749 self.assertEqual(math.pow(1.1, INF), INF)
750 self.assertEqual(math.pow(0.9, INF), 0.)
751 self.assertEqual(math.pow(0.1, INF), 0.)
752 self.assertEqual(math.pow(-0.1, INF), 0.)
753 self.assertEqual(math.pow(-0.9, INF), 0.)
754 self.assertEqual(math.pow(-1.1, INF), INF)
755 self.assertEqual(math.pow(-1.9, INF), INF)
756
757 # pow(x, y) should work for x negative, y an integer
758 self.ftest('(-2.)**3.', math.pow(-2.0, 3.0), -8.0)
759 self.ftest('(-2.)**2.', math.pow(-2.0, 2.0), 4.0)
760 self.ftest('(-2.)**1.', math.pow(-2.0, 1.0), -2.0)
761 self.ftest('(-2.)**0.', math.pow(-2.0, 0.0), 1.0)
762 self.ftest('(-2.)**-0.', math.pow(-2.0, -0.0), 1.0)
763 self.ftest('(-2.)**-1.', math.pow(-2.0, -1.0), -0.5)
764 self.ftest('(-2.)**-2.', math.pow(-2.0, -2.0), 0.25)
765 self.ftest('(-2.)**-3.', math.pow(-2.0, -3.0), -0.125)
766 self.assertRaises(ValueError, math.pow, -2.0, -0.5)
767 self.assertRaises(ValueError, math.pow, -2.0, 0.5)
768
769 # the following tests have been commented out since they don't
770 # really belong here: the implementation of ** for floats is
771 # independent of the implemention of math.pow
772 #self.assertEqual(1**NAN, 1)
773 #self.assertEqual(1**INF, 1)
774 #self.assertEqual(1**NINF, 1)
775 #self.assertEqual(1**0, 1)
776 #self.assertEqual(1.**NAN, 1)
777 #self.assertEqual(1.**INF, 1)
778 #self.assertEqual(1.**NINF, 1)
779 #self.assertEqual(1.**0, 1)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000780
Thomas Wouters89f507f2006-12-13 04:49:30 +0000781 def testRadians(self):
782 self.assertRaises(TypeError, math.radians)
783 self.ftest('radians(180)', math.radians(180), math.pi)
784 self.ftest('radians(90)', math.radians(90), math.pi/2)
785 self.ftest('radians(-45)', math.radians(-45), -math.pi/4)
Guido van Rossumfcce6301996-08-08 18:26:25 +0000786
Thomas Wouters89f507f2006-12-13 04:49:30 +0000787 def testSin(self):
788 self.assertRaises(TypeError, math.sin)
789 self.ftest('sin(0)', math.sin(0), 0)
790 self.ftest('sin(pi/2)', math.sin(math.pi/2), 1)
791 self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000792 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000793 self.assertTrue(math.isnan(math.sin(INF)))
794 self.assertTrue(math.isnan(math.sin(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +0000795 except ValueError:
796 self.assertRaises(ValueError, math.sin, INF)
797 self.assertRaises(ValueError, math.sin, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000798 self.assertTrue(math.isnan(math.sin(NAN)))
Guido van Rossumfcce6301996-08-08 18:26:25 +0000799
Thomas Wouters89f507f2006-12-13 04:49:30 +0000800 def testSinh(self):
801 self.assertRaises(TypeError, math.sinh)
802 self.ftest('sinh(0)', math.sinh(0), 0)
803 self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1)
804 self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0)
Christian Heimes53876d92008-04-19 00:31:39 +0000805 self.assertEquals(math.sinh(INF), INF)
Christian Heimesa342c012008-04-20 21:01:16 +0000806 self.assertEquals(math.sinh(NINF), NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000807 self.assertTrue(math.isnan(math.sinh(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +0000808
Thomas Wouters89f507f2006-12-13 04:49:30 +0000809 def testSqrt(self):
810 self.assertRaises(TypeError, math.sqrt)
811 self.ftest('sqrt(0)', math.sqrt(0), 0)
812 self.ftest('sqrt(1)', math.sqrt(1), 1)
813 self.ftest('sqrt(4)', math.sqrt(4), 2)
Christian Heimes53876d92008-04-19 00:31:39 +0000814 self.assertEquals(math.sqrt(INF), INF)
815 self.assertRaises(ValueError, math.sqrt, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000816 self.assertTrue(math.isnan(math.sqrt(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +0000817
Thomas Wouters89f507f2006-12-13 04:49:30 +0000818 def testTan(self):
819 self.assertRaises(TypeError, math.tan)
820 self.ftest('tan(0)', math.tan(0), 0)
821 self.ftest('tan(pi/4)', math.tan(math.pi/4), 1)
822 self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1)
Christian Heimes53876d92008-04-19 00:31:39 +0000823 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000824 self.assertTrue(math.isnan(math.tan(INF)))
825 self.assertTrue(math.isnan(math.tan(NINF)))
Christian Heimes53876d92008-04-19 00:31:39 +0000826 except:
827 self.assertRaises(ValueError, math.tan, INF)
828 self.assertRaises(ValueError, math.tan, NINF)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000829 self.assertTrue(math.isnan(math.tan(NAN)))
Tim Peters1d120612000-10-12 06:10:25 +0000830
Thomas Wouters89f507f2006-12-13 04:49:30 +0000831 def testTanh(self):
832 self.assertRaises(TypeError, math.tanh)
833 self.ftest('tanh(0)', math.tanh(0), 0)
834 self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0)
Christian Heimes53876d92008-04-19 00:31:39 +0000835 self.ftest('tanh(inf)', math.tanh(INF), 1)
836 self.ftest('tanh(-inf)', math.tanh(NINF), -1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000837 self.assertTrue(math.isnan(math.tanh(NAN)))
Christian Heimese57950f2008-04-21 13:08:03 +0000838 # check that tanh(-0.) == -0. on IEEE 754 systems
839 if float.__getformat__("double").startswith("IEEE"):
840 self.assertEqual(math.tanh(-0.), -0.)
841 self.assertEqual(math.copysign(1., math.tanh(-0.)),
842 math.copysign(1., -0.))
Tim Peters1d120612000-10-12 06:10:25 +0000843
Christian Heimes400adb02008-02-01 08:12:03 +0000844 def test_trunc(self):
845 self.assertEqual(math.trunc(1), 1)
846 self.assertEqual(math.trunc(-1), -1)
847 self.assertEqual(type(math.trunc(1)), int)
848 self.assertEqual(type(math.trunc(1.5)), int)
849 self.assertEqual(math.trunc(1.5), 1)
850 self.assertEqual(math.trunc(-1.5), -1)
851 self.assertEqual(math.trunc(1.999999), 1)
852 self.assertEqual(math.trunc(-1.999999), -1)
853 self.assertEqual(math.trunc(-0.999999), -0)
854 self.assertEqual(math.trunc(-100.999), -100)
855
856 class TestTrunc(object):
857 def __trunc__(self):
858 return 23
859
860 class TestNoTrunc(object):
861 pass
862
863 self.assertEqual(math.trunc(TestTrunc()), 23)
864
865 self.assertRaises(TypeError, math.trunc)
866 self.assertRaises(TypeError, math.trunc, 1, 2)
867 self.assertRaises(TypeError, math.trunc, TestNoTrunc())
868
869 # XXX Doesn't work because the method is looked up on
870 # the type only.
871 #t = TestNoTrunc()
872 #t.__trunc__ = lambda *args: args
873 #self.assertEquals((), math.trunc(t))
874 #self.assertRaises(TypeError, math.trunc, t, 0)
875
Christian Heimes072c0f12008-01-03 23:01:04 +0000876 def testCopysign(self):
877 self.assertEqual(math.copysign(1, 42), 1.0)
878 self.assertEqual(math.copysign(0., 42), 0.0)
879 self.assertEqual(math.copysign(1., -42), -1.0)
880 self.assertEqual(math.copysign(3, 0.), 3.0)
881 self.assertEqual(math.copysign(4., -0.), -4.0)
882
883 def testIsnan(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000884 self.assertTrue(math.isnan(float("nan")))
885 self.assertTrue(math.isnan(float("inf")* 0.))
886 self.assertFalse(math.isnan(float("inf")))
887 self.assertFalse(math.isnan(0.))
888 self.assertFalse(math.isnan(1.))
Christian Heimes072c0f12008-01-03 23:01:04 +0000889
890 def testIsinf(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000891 self.assertTrue(math.isinf(float("inf")))
892 self.assertTrue(math.isinf(float("-inf")))
893 self.assertTrue(math.isinf(1E400))
894 self.assertTrue(math.isinf(-1E400))
895 self.assertFalse(math.isinf(float("nan")))
896 self.assertFalse(math.isinf(0.))
897 self.assertFalse(math.isinf(1.))
Christian Heimes072c0f12008-01-03 23:01:04 +0000898
Thomas Wouters89f507f2006-12-13 04:49:30 +0000899 # RED_FLAG 16-Oct-2000 Tim
900 # While 2.0 is more consistent about exceptions than previous releases, it
901 # still fails this part of the test on some platforms. For now, we only
902 # *run* test_exceptions() in verbose mode, so that this isn't normally
903 # tested.
Tim Peters98c81842000-10-16 17:35:13 +0000904
Thomas Wouters89f507f2006-12-13 04:49:30 +0000905 if verbose:
906 def test_exceptions(self):
907 try:
908 x = math.exp(-1000000000)
909 except:
910 # mathmodule.c is failing to weed out underflows from libm, or
911 # we've got an fp format with huge dynamic range
912 self.fail("underflowing exp() should not have raised "
913 "an exception")
914 if x != 0:
915 self.fail("underflowing exp() should have returned 0")
916
917 # If this fails, probably using a strict IEEE-754 conforming libm, and x
918 # is +Inf afterwards. But Python wants overflows detected by default.
919 try:
920 x = math.exp(1000000000)
921 except OverflowError:
922 pass
923 else:
924 self.fail("overflowing exp() didn't trigger OverflowError")
925
926 # If this fails, it could be a puzzle. One odd possibility is that
927 # mathmodule.c's macros are getting confused while comparing
928 # Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE
929 # as a result (and so raising OverflowError instead).
930 try:
931 x = math.sqrt(-1.0)
932 except ValueError:
933 pass
934 else:
935 self.fail("sqrt(-1) didn't raise ValueError")
936
Mark Dickinson63566232009-09-18 21:04:19 +0000937 @requires_IEEE_754
Christian Heimes53876d92008-04-19 00:31:39 +0000938 def test_testfile(self):
Christian Heimes53876d92008-04-19 00:31:39 +0000939 for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file):
940 # Skip if either the input or result is complex, or if
941 # flags is nonempty
942 if ai != 0. or ei != 0. or flags:
943 continue
944 if fn in ['rect', 'polar']:
945 # no real versions of rect, polar
946 continue
947 func = getattr(math, fn)
Christian Heimesa342c012008-04-20 21:01:16 +0000948 try:
949 result = func(ar)
Mark Dickinsona0de26c2008-04-30 23:30:57 +0000950 except ValueError as exc:
951 message = (("Unexpected ValueError: %s\n " +
952 "in test %s:%s(%r)\n") % (exc.args[0], id, fn, ar))
Christian Heimesa342c012008-04-20 21:01:16 +0000953 self.fail(message)
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000954 except OverflowError:
955 message = ("Unexpected OverflowError in " +
956 "test %s:%s(%r)\n" % (id, fn, ar))
957 self.fail(message)
Christian Heimes53876d92008-04-19 00:31:39 +0000958 self.ftest("%s:%s(%r)" % (id, fn, ar), result, er)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000959
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000960 @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
961 "test requires IEEE 754 doubles")
962 def test_mtestfile(self):
963 ALLOWED_ERROR = 20 # permitted error, in ulps
964 fail_fmt = "{}:{}({!r}): expected {!r}, got {!r}"
965
966 failures = []
967 for id, fn, arg, expected, flags in parse_mtestfile(math_testcases):
968 func = getattr(math, fn)
969
970 if 'invalid' in flags or 'divide-by-zero' in flags:
971 expected = 'ValueError'
972 elif 'overflow' in flags:
973 expected = 'OverflowError'
974
975 try:
976 got = func(arg)
977 except ValueError:
978 got = 'ValueError'
979 except OverflowError:
980 got = 'OverflowError'
981
Mark Dickinson05d2e082009-12-11 20:17:17 +0000982 accuracy_failure = None
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000983 if isinstance(got, float) and isinstance(expected, float):
984 if math.isnan(expected) and math.isnan(got):
985 continue
986 if not math.isnan(expected) and not math.isnan(got):
Mark Dickinson05d2e082009-12-11 20:17:17 +0000987 # we use different closeness criteria for
988 # different functions.
989 if fn == 'gamma':
990 accuracy_failure = ulps_check(expected, got, 20)
991 elif fn == 'lgamma':
992 accuracy_failure = acc_check(expected, got,
993 rel_err = 5e-15,
994 abs_err = 5e-15)
995 else:
996 raise ValueError("don't know how to check accuracy "
997 "for this function")
998 if accuracy_failure is None:
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000999 continue
1000
1001 if isinstance(got, str) and isinstance(expected, str):
1002 if got == expected:
1003 continue
1004
1005 fail_msg = fail_fmt.format(id, fn, arg, expected, got)
Mark Dickinson05d2e082009-12-11 20:17:17 +00001006 if accuracy_failure is not None:
1007 fail_msg += ' ({})'.format(accuracy_failure)
Mark Dickinson12c4bdb2009-09-28 19:21:11 +00001008 failures.append(fail_msg)
1009
1010 if failures:
1011 self.fail('Failures in test_mtestfile:\n ' +
1012 '\n '.join(failures))
1013
1014
Thomas Wouters89f507f2006-12-13 04:49:30 +00001015def test_main():
Christian Heimes53876d92008-04-19 00:31:39 +00001016 from doctest import DocFileSuite
1017 suite = unittest.TestSuite()
1018 suite.addTest(unittest.makeSuite(MathTests))
1019 suite.addTest(DocFileSuite("ieee754.txt"))
1020 run_unittest(suite)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001021
1022if __name__ == '__main__':
1023 test_main()