ยปCore Development>Code coverage>Lib/test/test_math.py

Python code coverage for Lib/test/test_math.py

#countcontent
1n/a# Python test set -- math module
2n/a# XXXX Should not do tests around zero only
3n/a
4n/afrom test.support import run_unittest, verbose, requires_IEEE_754
5n/afrom test import support
6n/aimport unittest
7n/aimport math
8n/aimport os
9n/aimport platform
10n/aimport struct
11n/aimport sys
12n/aimport sysconfig
13n/a
14n/aeps = 1E-05
15n/aNAN = float('nan')
16n/aINF = float('inf')
17n/aNINF = float('-inf')
18n/aFLOAT_MAX = sys.float_info.max
19n/a
20n/a# detect evidence of double-rounding: fsum is not always correctly
21n/a# rounded on machines that suffer from double rounding.
22n/ax, y = 1e16, 2.9999 # use temporary values to defeat peephole optimizer
23n/aHAVE_DOUBLE_ROUNDING = (x + y == 1e16 + 4)
24n/a
25n/a# locate file with test values
26n/aif __name__ == '__main__':
27n/a file = sys.argv[0]
28n/aelse:
29n/a file = __file__
30n/atest_dir = os.path.dirname(file) or os.curdir
31n/amath_testcases = os.path.join(test_dir, 'math_testcases.txt')
32n/atest_file = os.path.join(test_dir, 'cmath_testcases.txt')
33n/a
34n/a
35n/adef to_ulps(x):
36n/a """Convert a non-NaN float x to an integer, in such a way that
37n/a adjacent floats are converted to adjacent integers. Then
38n/a abs(ulps(x) - ulps(y)) gives the difference in ulps between two
39n/a floats.
40n/a
41n/a The results from this function will only make sense on platforms
42n/a where native doubles are represented in IEEE 754 binary64 format.
43n/a
44n/a Note: 0.0 and -0.0 are converted to 0 and -1, respectively.
45n/a """
46n/a n = struct.unpack('<q', struct.pack('<d', x))[0]
47n/a if n < 0:
48n/a n = ~(n+2**63)
49n/a return n
50n/a
51n/a
52n/adef ulp(x):
53n/a """Return the value of the least significant bit of a
54n/a float x, such that the first float bigger than x is x+ulp(x).
55n/a Then, given an expected result x and a tolerance of n ulps,
56n/a the result y should be such that abs(y-x) <= n * ulp(x).
57n/a The results from this function will only make sense on platforms
58n/a where native doubles are represented in IEEE 754 binary64 format.
59n/a """
60n/a x = abs(float(x))
61n/a if math.isnan(x) or math.isinf(x):
62n/a return x
63n/a
64n/a # Find next float up from x.
65n/a n = struct.unpack('<q', struct.pack('<d', x))[0]
66n/a x_next = struct.unpack('<d', struct.pack('<q', n + 1))[0]
67n/a if math.isinf(x_next):
68n/a # Corner case: x was the largest finite float. Then it's
69n/a # not an exact power of two, so we can take the difference
70n/a # between x and the previous float.
71n/a x_prev = struct.unpack('<d', struct.pack('<q', n - 1))[0]
72n/a return x - x_prev
73n/a else:
74n/a return x_next - x
75n/a
76n/a# Here's a pure Python version of the math.factorial algorithm, for
77n/a# documentation and comparison purposes.
78n/a#
79n/a# Formula:
80n/a#
81n/a# factorial(n) = factorial_odd_part(n) << (n - count_set_bits(n))
82n/a#
83n/a# where
84n/a#
85n/a# factorial_odd_part(n) = product_{i >= 0} product_{0 < j <= n >> i; j odd} j
86n/a#
87n/a# The outer product above is an infinite product, but once i >= n.bit_length,
88n/a# (n >> i) < 1 and the corresponding term of the product is empty. So only the
89n/a# finitely many terms for 0 <= i < n.bit_length() contribute anything.
90n/a#
91n/a# We iterate downwards from i == n.bit_length() - 1 to i == 0. The inner
92n/a# product in the formula above starts at 1 for i == n.bit_length(); for each i
93n/a# < n.bit_length() we get the inner product for i from that for i + 1 by
94n/a# multiplying by all j in {n >> i+1 < j <= n >> i; j odd}. In Python terms,
95n/a# this set is range((n >> i+1) + 1 | 1, (n >> i) + 1 | 1, 2).
96n/a
97n/adef count_set_bits(n):
98n/a """Number of '1' bits in binary expansion of a nonnnegative integer."""
99n/a return 1 + count_set_bits(n & n - 1) if n else 0
100n/a
101n/adef partial_product(start, stop):
102n/a """Product of integers in range(start, stop, 2), computed recursively.
103n/a start and stop should both be odd, with start <= stop.
104n/a
105n/a """
106n/a numfactors = (stop - start) >> 1
107n/a if not numfactors:
108n/a return 1
109n/a elif numfactors == 1:
110n/a return start
111n/a else:
112n/a mid = (start + numfactors) | 1
113n/a return partial_product(start, mid) * partial_product(mid, stop)
114n/a
115n/adef py_factorial(n):
116n/a """Factorial of nonnegative integer n, via "Binary Split Factorial Formula"
117n/a described at http://www.luschny.de/math/factorial/binarysplitfact.html
118n/a
119n/a """
120n/a inner = outer = 1
121n/a for i in reversed(range(n.bit_length())):
122n/a inner *= partial_product((n >> i + 1) + 1 | 1, (n >> i) + 1 | 1)
123n/a outer *= inner
124n/a return outer << (n - count_set_bits(n))
125n/a
126n/adef ulp_abs_check(expected, got, ulp_tol, abs_tol):
127n/a """Given finite floats `expected` and `got`, check that they're
128n/a approximately equal to within the given number of ulps or the
129n/a given absolute tolerance, whichever is bigger.
130n/a
131n/a Returns None on success and an error message on failure.
132n/a """
133n/a ulp_error = abs(to_ulps(expected) - to_ulps(got))
134n/a abs_error = abs(expected - got)
135n/a
136n/a # Succeed if either abs_error <= abs_tol or ulp_error <= ulp_tol.
137n/a if abs_error <= abs_tol or ulp_error <= ulp_tol:
138n/a return None
139n/a else:
140n/a fmt = ("error = {:.3g} ({:d} ulps); "
141n/a "permitted error = {:.3g} or {:d} ulps")
142n/a return fmt.format(abs_error, ulp_error, abs_tol, ulp_tol)
143n/a
144n/adef parse_mtestfile(fname):
145n/a """Parse a file with test values
146n/a
147n/a -- starts a comment
148n/a blank lines, or lines containing only a comment, are ignored
149n/a other lines are expected to have the form
150n/a id fn arg -> expected [flag]*
151n/a
152n/a """
153n/a with open(fname) as fp:
154n/a for line in fp:
155n/a # strip comments, and skip blank lines
156n/a if '--' in line:
157n/a line = line[:line.index('--')]
158n/a if not line.strip():
159n/a continue
160n/a
161n/a lhs, rhs = line.split('->')
162n/a id, fn, arg = lhs.split()
163n/a rhs_pieces = rhs.split()
164n/a exp = rhs_pieces[0]
165n/a flags = rhs_pieces[1:]
166n/a
167n/a yield (id, fn, float(arg), float(exp), flags)
168n/a
169n/a
170n/adef parse_testfile(fname):
171n/a """Parse a file with test values
172n/a
173n/a Empty lines or lines starting with -- are ignored
174n/a yields id, fn, arg_real, arg_imag, exp_real, exp_imag
175n/a """
176n/a with open(fname) as fp:
177n/a for line in fp:
178n/a # skip comment lines and blank lines
179n/a if line.startswith('--') or not line.strip():
180n/a continue
181n/a
182n/a lhs, rhs = line.split('->')
183n/a id, fn, arg_real, arg_imag = lhs.split()
184n/a rhs_pieces = rhs.split()
185n/a exp_real, exp_imag = rhs_pieces[0], rhs_pieces[1]
186n/a flags = rhs_pieces[2:]
187n/a
188n/a yield (id, fn,
189n/a float(arg_real), float(arg_imag),
190n/a float(exp_real), float(exp_imag),
191n/a flags)
192n/a
193n/a
194n/adef result_check(expected, got, ulp_tol=5, abs_tol=0.0):
195n/a # Common logic of MathTests.(ftest, test_testcases, test_mtestcases)
196n/a """Compare arguments expected and got, as floats, if either
197n/a is a float, using a tolerance expressed in multiples of
198n/a ulp(expected) or absolutely (if given and greater).
199n/a
200n/a As a convenience, when neither argument is a float, and for
201n/a non-finite floats, exact equality is demanded. Also, nan==nan
202n/a as far as this function is concerned.
203n/a
204n/a Returns None on success and an error message on failure.
205n/a """
206n/a
207n/a # Check exactly equal (applies also to strings representing exceptions)
208n/a if got == expected:
209n/a return None
210n/a
211n/a failure = "not equal"
212n/a
213n/a # Turn mixed float and int comparison (e.g. floor()) to all-float
214n/a if isinstance(expected, float) and isinstance(got, int):
215n/a got = float(got)
216n/a elif isinstance(got, float) and isinstance(expected, int):
217n/a expected = float(expected)
218n/a
219n/a if isinstance(expected, float) and isinstance(got, float):
220n/a if math.isnan(expected) and math.isnan(got):
221n/a # Pass, since both nan
222n/a failure = None
223n/a elif math.isinf(expected) or math.isinf(got):
224n/a # We already know they're not equal, drop through to failure
225n/a pass
226n/a else:
227n/a # Both are finite floats (now). Are they close enough?
228n/a failure = ulp_abs_check(expected, got, ulp_tol, abs_tol)
229n/a
230n/a # arguments are not equal, and if numeric, are too far apart
231n/a if failure is not None:
232n/a fail_fmt = "expected {!r}, got {!r}"
233n/a fail_msg = fail_fmt.format(expected, got)
234n/a fail_msg += ' ({})'.format(failure)
235n/a return fail_msg
236n/a else:
237n/a return None
238n/a
239n/a# Class providing an __index__ method.
240n/aclass MyIndexable(object):
241n/a def __init__(self, value):
242n/a self.value = value
243n/a
244n/a def __index__(self):
245n/a return self.value
246n/a
247n/aclass MathTests(unittest.TestCase):
248n/a
249n/a def ftest(self, name, got, expected, ulp_tol=5, abs_tol=0.0):
250n/a """Compare arguments expected and got, as floats, if either
251n/a is a float, using a tolerance expressed in multiples of
252n/a ulp(expected) or absolutely, whichever is greater.
253n/a
254n/a As a convenience, when neither argument is a float, and for
255n/a non-finite floats, exact equality is demanded. Also, nan==nan
256n/a in this function.
257n/a """
258n/a failure = result_check(expected, got, ulp_tol, abs_tol)
259n/a if failure is not None:
260n/a self.fail("{}: {}".format(name, failure))
261n/a
262n/a def testConstants(self):
263n/a # Ref: Abramowitz & Stegun (Dover, 1965)
264n/a self.ftest('pi', math.pi, 3.141592653589793238462643)
265n/a self.ftest('e', math.e, 2.718281828459045235360287)
266n/a self.assertEqual(math.tau, 2*math.pi)
267n/a
268n/a def testAcos(self):
269n/a self.assertRaises(TypeError, math.acos)
270n/a self.ftest('acos(-1)', math.acos(-1), math.pi)
271n/a self.ftest('acos(0)', math.acos(0), math.pi/2)
272n/a self.ftest('acos(1)', math.acos(1), 0)
273n/a self.assertRaises(ValueError, math.acos, INF)
274n/a self.assertRaises(ValueError, math.acos, NINF)
275n/a self.assertRaises(ValueError, math.acos, 1 + eps)
276n/a self.assertRaises(ValueError, math.acos, -1 - eps)
277n/a self.assertTrue(math.isnan(math.acos(NAN)))
278n/a
279n/a def testAcosh(self):
280n/a self.assertRaises(TypeError, math.acosh)
281n/a self.ftest('acosh(1)', math.acosh(1), 0)
282n/a self.ftest('acosh(2)', math.acosh(2), 1.3169578969248168)
283n/a self.assertRaises(ValueError, math.acosh, 0)
284n/a self.assertRaises(ValueError, math.acosh, -1)
285n/a self.assertEqual(math.acosh(INF), INF)
286n/a self.assertRaises(ValueError, math.acosh, NINF)
287n/a self.assertTrue(math.isnan(math.acosh(NAN)))
288n/a
289n/a def testAsin(self):
290n/a self.assertRaises(TypeError, math.asin)
291n/a self.ftest('asin(-1)', math.asin(-1), -math.pi/2)
292n/a self.ftest('asin(0)', math.asin(0), 0)
293n/a self.ftest('asin(1)', math.asin(1), math.pi/2)
294n/a self.assertRaises(ValueError, math.asin, INF)
295n/a self.assertRaises(ValueError, math.asin, NINF)
296n/a self.assertRaises(ValueError, math.asin, 1 + eps)
297n/a self.assertRaises(ValueError, math.asin, -1 - eps)
298n/a self.assertTrue(math.isnan(math.asin(NAN)))
299n/a
300n/a def testAsinh(self):
301n/a self.assertRaises(TypeError, math.asinh)
302n/a self.ftest('asinh(0)', math.asinh(0), 0)
303n/a self.ftest('asinh(1)', math.asinh(1), 0.88137358701954305)
304n/a self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305)
305n/a self.assertEqual(math.asinh(INF), INF)
306n/a self.assertEqual(math.asinh(NINF), NINF)
307n/a self.assertTrue(math.isnan(math.asinh(NAN)))
308n/a
309n/a def testAtan(self):
310n/a self.assertRaises(TypeError, math.atan)
311n/a self.ftest('atan(-1)', math.atan(-1), -math.pi/4)
312n/a self.ftest('atan(0)', math.atan(0), 0)
313n/a self.ftest('atan(1)', math.atan(1), math.pi/4)
314n/a self.ftest('atan(inf)', math.atan(INF), math.pi/2)
315n/a self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2)
316n/a self.assertTrue(math.isnan(math.atan(NAN)))
317n/a
318n/a def testAtanh(self):
319n/a self.assertRaises(TypeError, math.atan)
320n/a self.ftest('atanh(0)', math.atanh(0), 0)
321n/a self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489)
322n/a self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489)
323n/a self.assertRaises(ValueError, math.atanh, 1)
324n/a self.assertRaises(ValueError, math.atanh, -1)
325n/a self.assertRaises(ValueError, math.atanh, INF)
326n/a self.assertRaises(ValueError, math.atanh, NINF)
327n/a self.assertTrue(math.isnan(math.atanh(NAN)))
328n/a
329n/a def testAtan2(self):
330n/a self.assertRaises(TypeError, math.atan2)
331n/a self.ftest('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2)
332n/a self.ftest('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4)
333n/a self.ftest('atan2(0, 1)', math.atan2(0, 1), 0)
334n/a self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4)
335n/a self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2)
336n/a
337n/a # math.atan2(0, x)
338n/a self.ftest('atan2(0., -inf)', math.atan2(0., NINF), math.pi)
339n/a self.ftest('atan2(0., -2.3)', math.atan2(0., -2.3), math.pi)
340n/a self.ftest('atan2(0., -0.)', math.atan2(0., -0.), math.pi)
341n/a self.assertEqual(math.atan2(0., 0.), 0.)
342n/a self.assertEqual(math.atan2(0., 2.3), 0.)
343n/a self.assertEqual(math.atan2(0., INF), 0.)
344n/a self.assertTrue(math.isnan(math.atan2(0., NAN)))
345n/a # math.atan2(-0, x)
346n/a self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi)
347n/a self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi)
348n/a self.ftest('atan2(-0., -0.)', math.atan2(-0., -0.), -math.pi)
349n/a self.assertEqual(math.atan2(-0., 0.), -0.)
350n/a self.assertEqual(math.atan2(-0., 2.3), -0.)
351n/a self.assertEqual(math.atan2(-0., INF), -0.)
352n/a self.assertTrue(math.isnan(math.atan2(-0., NAN)))
353n/a # math.atan2(INF, x)
354n/a self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4)
355n/a self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2)
356n/a self.ftest('atan2(inf, -0.)', math.atan2(INF, -0.0), math.pi/2)
357n/a self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2)
358n/a self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2)
359n/a self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4)
360n/a self.assertTrue(math.isnan(math.atan2(INF, NAN)))
361n/a # math.atan2(NINF, x)
362n/a self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4)
363n/a self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2)
364n/a self.ftest('atan2(-inf, -0.)', math.atan2(NINF, -0.0), -math.pi/2)
365n/a self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2)
366n/a self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2)
367n/a self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4)
368n/a self.assertTrue(math.isnan(math.atan2(NINF, NAN)))
369n/a # math.atan2(+finite, x)
370n/a self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi)
371n/a self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2)
372n/a self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2)
373n/a self.assertEqual(math.atan2(2.3, INF), 0.)
374n/a self.assertTrue(math.isnan(math.atan2(2.3, NAN)))
375n/a # math.atan2(-finite, x)
376n/a self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi)
377n/a self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2)
378n/a self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2)
379n/a self.assertEqual(math.atan2(-2.3, INF), -0.)
380n/a self.assertTrue(math.isnan(math.atan2(-2.3, NAN)))
381n/a # math.atan2(NAN, x)
382n/a self.assertTrue(math.isnan(math.atan2(NAN, NINF)))
383n/a self.assertTrue(math.isnan(math.atan2(NAN, -2.3)))
384n/a self.assertTrue(math.isnan(math.atan2(NAN, -0.)))
385n/a self.assertTrue(math.isnan(math.atan2(NAN, 0.)))
386n/a self.assertTrue(math.isnan(math.atan2(NAN, 2.3)))
387n/a self.assertTrue(math.isnan(math.atan2(NAN, INF)))
388n/a self.assertTrue(math.isnan(math.atan2(NAN, NAN)))
389n/a
390n/a def testCeil(self):
391n/a self.assertRaises(TypeError, math.ceil)
392n/a self.assertEqual(int, type(math.ceil(0.5)))
393n/a self.ftest('ceil(0.5)', math.ceil(0.5), 1)
394n/a self.ftest('ceil(1.0)', math.ceil(1.0), 1)
395n/a self.ftest('ceil(1.5)', math.ceil(1.5), 2)
396n/a self.ftest('ceil(-0.5)', math.ceil(-0.5), 0)
397n/a self.ftest('ceil(-1.0)', math.ceil(-1.0), -1)
398n/a self.ftest('ceil(-1.5)', math.ceil(-1.5), -1)
399n/a #self.assertEqual(math.ceil(INF), INF)
400n/a #self.assertEqual(math.ceil(NINF), NINF)
401n/a #self.assertTrue(math.isnan(math.ceil(NAN)))
402n/a
403n/a class TestCeil:
404n/a def __ceil__(self):
405n/a return 42
406n/a class TestNoCeil:
407n/a pass
408n/a self.ftest('ceil(TestCeil())', math.ceil(TestCeil()), 42)
409n/a self.assertRaises(TypeError, math.ceil, TestNoCeil())
410n/a
411n/a t = TestNoCeil()
412n/a t.__ceil__ = lambda *args: args
413n/a self.assertRaises(TypeError, math.ceil, t)
414n/a self.assertRaises(TypeError, math.ceil, t, 0)
415n/a
416n/a @requires_IEEE_754
417n/a def testCopysign(self):
418n/a self.assertEqual(math.copysign(1, 42), 1.0)
419n/a self.assertEqual(math.copysign(0., 42), 0.0)
420n/a self.assertEqual(math.copysign(1., -42), -1.0)
421n/a self.assertEqual(math.copysign(3, 0.), 3.0)
422n/a self.assertEqual(math.copysign(4., -0.), -4.0)
423n/a
424n/a self.assertRaises(TypeError, math.copysign)
425n/a # copysign should let us distinguish signs of zeros
426n/a self.assertEqual(math.copysign(1., 0.), 1.)
427n/a self.assertEqual(math.copysign(1., -0.), -1.)
428n/a self.assertEqual(math.copysign(INF, 0.), INF)
429n/a self.assertEqual(math.copysign(INF, -0.), NINF)
430n/a self.assertEqual(math.copysign(NINF, 0.), INF)
431n/a self.assertEqual(math.copysign(NINF, -0.), NINF)
432n/a # and of infinities
433n/a self.assertEqual(math.copysign(1., INF), 1.)
434n/a self.assertEqual(math.copysign(1., NINF), -1.)
435n/a self.assertEqual(math.copysign(INF, INF), INF)
436n/a self.assertEqual(math.copysign(INF, NINF), NINF)
437n/a self.assertEqual(math.copysign(NINF, INF), INF)
438n/a self.assertEqual(math.copysign(NINF, NINF), NINF)
439n/a self.assertTrue(math.isnan(math.copysign(NAN, 1.)))
440n/a self.assertTrue(math.isnan(math.copysign(NAN, INF)))
441n/a self.assertTrue(math.isnan(math.copysign(NAN, NINF)))
442n/a self.assertTrue(math.isnan(math.copysign(NAN, NAN)))
443n/a # copysign(INF, NAN) may be INF or it may be NINF, since
444n/a # we don't know whether the sign bit of NAN is set on any
445n/a # given platform.
446n/a self.assertTrue(math.isinf(math.copysign(INF, NAN)))
447n/a # similarly, copysign(2., NAN) could be 2. or -2.
448n/a self.assertEqual(abs(math.copysign(2., NAN)), 2.)
449n/a
450n/a def testCos(self):
451n/a self.assertRaises(TypeError, math.cos)
452n/a self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0, abs_tol=ulp(1))
453n/a self.ftest('cos(0)', math.cos(0), 1)
454n/a self.ftest('cos(pi/2)', math.cos(math.pi/2), 0, abs_tol=ulp(1))
455n/a self.ftest('cos(pi)', math.cos(math.pi), -1)
456n/a try:
457n/a self.assertTrue(math.isnan(math.cos(INF)))
458n/a self.assertTrue(math.isnan(math.cos(NINF)))
459n/a except ValueError:
460n/a self.assertRaises(ValueError, math.cos, INF)
461n/a self.assertRaises(ValueError, math.cos, NINF)
462n/a self.assertTrue(math.isnan(math.cos(NAN)))
463n/a
464n/a def testCosh(self):
465n/a self.assertRaises(TypeError, math.cosh)
466n/a self.ftest('cosh(0)', math.cosh(0), 1)
467n/a self.ftest('cosh(2)-2*cosh(1)**2', math.cosh(2)-2*math.cosh(1)**2, -1) # Thanks to Lambert
468n/a self.assertEqual(math.cosh(INF), INF)
469n/a self.assertEqual(math.cosh(NINF), INF)
470n/a self.assertTrue(math.isnan(math.cosh(NAN)))
471n/a
472n/a def testDegrees(self):
473n/a self.assertRaises(TypeError, math.degrees)
474n/a self.ftest('degrees(pi)', math.degrees(math.pi), 180.0)
475n/a self.ftest('degrees(pi/2)', math.degrees(math.pi/2), 90.0)
476n/a self.ftest('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0)
477n/a self.ftest('degrees(0)', math.degrees(0), 0)
478n/a
479n/a def testExp(self):
480n/a self.assertRaises(TypeError, math.exp)
481n/a self.ftest('exp(-1)', math.exp(-1), 1/math.e)
482n/a self.ftest('exp(0)', math.exp(0), 1)
483n/a self.ftest('exp(1)', math.exp(1), math.e)
484n/a self.assertEqual(math.exp(INF), INF)
485n/a self.assertEqual(math.exp(NINF), 0.)
486n/a self.assertTrue(math.isnan(math.exp(NAN)))
487n/a self.assertRaises(OverflowError, math.exp, 1000000)
488n/a
489n/a def testFabs(self):
490n/a self.assertRaises(TypeError, math.fabs)
491n/a self.ftest('fabs(-1)', math.fabs(-1), 1)
492n/a self.ftest('fabs(0)', math.fabs(0), 0)
493n/a self.ftest('fabs(1)', math.fabs(1), 1)
494n/a
495n/a def testFactorial(self):
496n/a self.assertEqual(math.factorial(0), 1)
497n/a self.assertEqual(math.factorial(0.0), 1)
498n/a total = 1
499n/a for i in range(1, 1000):
500n/a total *= i
501n/a self.assertEqual(math.factorial(i), total)
502n/a self.assertEqual(math.factorial(float(i)), total)
503n/a self.assertEqual(math.factorial(i), py_factorial(i))
504n/a self.assertRaises(ValueError, math.factorial, -1)
505n/a self.assertRaises(ValueError, math.factorial, -1.0)
506n/a self.assertRaises(ValueError, math.factorial, -10**100)
507n/a self.assertRaises(ValueError, math.factorial, -1e100)
508n/a self.assertRaises(ValueError, math.factorial, math.pi)
509n/a
510n/a # Other implementations may place different upper bounds.
511n/a @support.cpython_only
512n/a def testFactorialHugeInputs(self):
513n/a # Currently raises ValueError for inputs that are too large
514n/a # to fit into a C long.
515n/a self.assertRaises(OverflowError, math.factorial, 10**100)
516n/a self.assertRaises(OverflowError, math.factorial, 1e100)
517n/a
518n/a def testFloor(self):
519n/a self.assertRaises(TypeError, math.floor)
520n/a self.assertEqual(int, type(math.floor(0.5)))
521n/a self.ftest('floor(0.5)', math.floor(0.5), 0)
522n/a self.ftest('floor(1.0)', math.floor(1.0), 1)
523n/a self.ftest('floor(1.5)', math.floor(1.5), 1)
524n/a self.ftest('floor(-0.5)', math.floor(-0.5), -1)
525n/a self.ftest('floor(-1.0)', math.floor(-1.0), -1)
526n/a self.ftest('floor(-1.5)', math.floor(-1.5), -2)
527n/a # pow() relies on floor() to check for integers
528n/a # This fails on some platforms - so check it here
529n/a self.ftest('floor(1.23e167)', math.floor(1.23e167), 1.23e167)
530n/a self.ftest('floor(-1.23e167)', math.floor(-1.23e167), -1.23e167)
531n/a #self.assertEqual(math.ceil(INF), INF)
532n/a #self.assertEqual(math.ceil(NINF), NINF)
533n/a #self.assertTrue(math.isnan(math.floor(NAN)))
534n/a
535n/a class TestFloor:
536n/a def __floor__(self):
537n/a return 42
538n/a class TestNoFloor:
539n/a pass
540n/a self.ftest('floor(TestFloor())', math.floor(TestFloor()), 42)
541n/a self.assertRaises(TypeError, math.floor, TestNoFloor())
542n/a
543n/a t = TestNoFloor()
544n/a t.__floor__ = lambda *args: args
545n/a self.assertRaises(TypeError, math.floor, t)
546n/a self.assertRaises(TypeError, math.floor, t, 0)
547n/a
548n/a def testFmod(self):
549n/a self.assertRaises(TypeError, math.fmod)
550n/a self.ftest('fmod(10, 1)', math.fmod(10, 1), 0.0)
551n/a self.ftest('fmod(10, 0.5)', math.fmod(10, 0.5), 0.0)
552n/a self.ftest('fmod(10, 1.5)', math.fmod(10, 1.5), 1.0)
553n/a self.ftest('fmod(-10, 1)', math.fmod(-10, 1), -0.0)
554n/a self.ftest('fmod(-10, 0.5)', math.fmod(-10, 0.5), -0.0)
555n/a self.ftest('fmod(-10, 1.5)', math.fmod(-10, 1.5), -1.0)
556n/a self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
557n/a self.assertTrue(math.isnan(math.fmod(1., NAN)))
558n/a self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
559n/a self.assertRaises(ValueError, math.fmod, 1., 0.)
560n/a self.assertRaises(ValueError, math.fmod, INF, 1.)
561n/a self.assertRaises(ValueError, math.fmod, NINF, 1.)
562n/a self.assertRaises(ValueError, math.fmod, INF, 0.)
563n/a self.assertEqual(math.fmod(3.0, INF), 3.0)
564n/a self.assertEqual(math.fmod(-3.0, INF), -3.0)
565n/a self.assertEqual(math.fmod(3.0, NINF), 3.0)
566n/a self.assertEqual(math.fmod(-3.0, NINF), -3.0)
567n/a self.assertEqual(math.fmod(0.0, 3.0), 0.0)
568n/a self.assertEqual(math.fmod(0.0, NINF), 0.0)
569n/a
570n/a def testFrexp(self):
571n/a self.assertRaises(TypeError, math.frexp)
572n/a
573n/a def testfrexp(name, result, expected):
574n/a (mant, exp), (emant, eexp) = result, expected
575n/a if abs(mant-emant) > eps or exp != eexp:
576n/a self.fail('%s returned %r, expected %r'%\
577n/a (name, result, expected))
578n/a
579n/a testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
580n/a testfrexp('frexp(0)', math.frexp(0), (0, 0))
581n/a testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
582n/a testfrexp('frexp(2)', math.frexp(2), (0.5, 2))
583n/a
584n/a self.assertEqual(math.frexp(INF)[0], INF)
585n/a self.assertEqual(math.frexp(NINF)[0], NINF)
586n/a self.assertTrue(math.isnan(math.frexp(NAN)[0]))
587n/a
588n/a @requires_IEEE_754
589n/a @unittest.skipIf(HAVE_DOUBLE_ROUNDING,
590n/a "fsum is not exact on machines with double rounding")
591n/a def testFsum(self):
592n/a # math.fsum relies on exact rounding for correct operation.
593n/a # There's a known problem with IA32 floating-point that causes
594n/a # inexact rounding in some situations, and will cause the
595n/a # math.fsum tests below to fail; see issue #2937. On non IEEE
596n/a # 754 platforms, and on IEEE 754 platforms that exhibit the
597n/a # problem described in issue #2937, we simply skip the whole
598n/a # test.
599n/a
600n/a # Python version of math.fsum, for comparison. Uses a
601n/a # different algorithm based on frexp, ldexp and integer
602n/a # arithmetic.
603n/a from sys import float_info
604n/a mant_dig = float_info.mant_dig
605n/a etiny = float_info.min_exp - mant_dig
606n/a
607n/a def msum(iterable):
608n/a """Full precision summation. Compute sum(iterable) without any
609n/a intermediate accumulation of error. Based on the 'lsum' function
610n/a at http://code.activestate.com/recipes/393090/
611n/a
612n/a """
613n/a tmant, texp = 0, 0
614n/a for x in iterable:
615n/a mant, exp = math.frexp(x)
616n/a mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig
617n/a if texp > exp:
618n/a tmant <<= texp-exp
619n/a texp = exp
620n/a else:
621n/a mant <<= exp-texp
622n/a tmant += mant
623n/a # Round tmant * 2**texp to a float. The original recipe
624n/a # used float(str(tmant)) * 2.0**texp for this, but that's
625n/a # a little unsafe because str -> float conversion can't be
626n/a # relied upon to do correct rounding on all platforms.
627n/a tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp)
628n/a if tail > 0:
629n/a h = 1 << (tail-1)
630n/a tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1)
631n/a texp += tail
632n/a return math.ldexp(tmant, texp)
633n/a
634n/a test_values = [
635n/a ([], 0.0),
636n/a ([0.0], 0.0),
637n/a ([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100),
638n/a ([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0),
639n/a ([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0),
640n/a ([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0),
641n/a ([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0),
642n/a ([1./n for n in range(1, 1001)],
643n/a float.fromhex('0x1.df11f45f4e61ap+2')),
644n/a ([(-1.)**n/n for n in range(1, 1001)],
645n/a float.fromhex('-0x1.62a2af1bd3624p-1')),
646n/a ([1.7**(i+1)-1.7**i for i in range(1000)] + [-1.7**1000], -1.0),
647n/a ([1e16, 1., 1e-16], 10000000000000002.0),
648n/a ([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0),
649n/a # exercise code for resizing partials array
650n/a ([2.**n - 2.**(n+50) + 2.**(n+52) for n in range(-1074, 972, 2)] +
651n/a [-2.**1022],
652n/a float.fromhex('0x1.5555555555555p+970')),
653n/a ]
654n/a
655n/a for i, (vals, expected) in enumerate(test_values):
656n/a try:
657n/a actual = math.fsum(vals)
658n/a except OverflowError:
659n/a self.fail("test %d failed: got OverflowError, expected %r "
660n/a "for math.fsum(%.100r)" % (i, expected, vals))
661n/a except ValueError:
662n/a self.fail("test %d failed: got ValueError, expected %r "
663n/a "for math.fsum(%.100r)" % (i, expected, vals))
664n/a self.assertEqual(actual, expected)
665n/a
666n/a from random import random, gauss, shuffle
667n/a for j in range(1000):
668n/a vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10
669n/a s = 0
670n/a for i in range(200):
671n/a v = gauss(0, random()) ** 7 - s
672n/a s += v
673n/a vals.append(v)
674n/a shuffle(vals)
675n/a
676n/a s = msum(vals)
677n/a self.assertEqual(msum(vals), math.fsum(vals))
678n/a
679n/a def testGcd(self):
680n/a gcd = math.gcd
681n/a self.assertEqual(gcd(0, 0), 0)
682n/a self.assertEqual(gcd(1, 0), 1)
683n/a self.assertEqual(gcd(-1, 0), 1)
684n/a self.assertEqual(gcd(0, 1), 1)
685n/a self.assertEqual(gcd(0, -1), 1)
686n/a self.assertEqual(gcd(7, 1), 1)
687n/a self.assertEqual(gcd(7, -1), 1)
688n/a self.assertEqual(gcd(-23, 15), 1)
689n/a self.assertEqual(gcd(120, 84), 12)
690n/a self.assertEqual(gcd(84, -120), 12)
691n/a self.assertEqual(gcd(1216342683557601535506311712,
692n/a 436522681849110124616458784), 32)
693n/a c = 652560
694n/a x = 434610456570399902378880679233098819019853229470286994367836600566
695n/a y = 1064502245825115327754847244914921553977
696n/a a = x * c
697n/a b = y * c
698n/a self.assertEqual(gcd(a, b), c)
699n/a self.assertEqual(gcd(b, a), c)
700n/a self.assertEqual(gcd(-a, b), c)
701n/a self.assertEqual(gcd(b, -a), c)
702n/a self.assertEqual(gcd(a, -b), c)
703n/a self.assertEqual(gcd(-b, a), c)
704n/a self.assertEqual(gcd(-a, -b), c)
705n/a self.assertEqual(gcd(-b, -a), c)
706n/a c = 576559230871654959816130551884856912003141446781646602790216406874
707n/a a = x * c
708n/a b = y * c
709n/a self.assertEqual(gcd(a, b), c)
710n/a self.assertEqual(gcd(b, a), c)
711n/a self.assertEqual(gcd(-a, b), c)
712n/a self.assertEqual(gcd(b, -a), c)
713n/a self.assertEqual(gcd(a, -b), c)
714n/a self.assertEqual(gcd(-b, a), c)
715n/a self.assertEqual(gcd(-a, -b), c)
716n/a self.assertEqual(gcd(-b, -a), c)
717n/a
718n/a self.assertRaises(TypeError, gcd, 120.0, 84)
719n/a self.assertRaises(TypeError, gcd, 120, 84.0)
720n/a self.assertEqual(gcd(MyIndexable(120), MyIndexable(84)), 12)
721n/a
722n/a def testHypot(self):
723n/a self.assertRaises(TypeError, math.hypot)
724n/a self.ftest('hypot(0,0)', math.hypot(0,0), 0)
725n/a self.ftest('hypot(3,4)', math.hypot(3,4), 5)
726n/a self.assertEqual(math.hypot(NAN, INF), INF)
727n/a self.assertEqual(math.hypot(INF, NAN), INF)
728n/a self.assertEqual(math.hypot(NAN, NINF), INF)
729n/a self.assertEqual(math.hypot(NINF, NAN), INF)
730n/a self.assertRaises(OverflowError, math.hypot, FLOAT_MAX, FLOAT_MAX)
731n/a self.assertTrue(math.isnan(math.hypot(1.0, NAN)))
732n/a self.assertTrue(math.isnan(math.hypot(NAN, -2.0)))
733n/a
734n/a def testLdexp(self):
735n/a self.assertRaises(TypeError, math.ldexp)
736n/a self.ftest('ldexp(0,1)', math.ldexp(0,1), 0)
737n/a self.ftest('ldexp(1,1)', math.ldexp(1,1), 2)
738n/a self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5)
739n/a self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2)
740n/a self.assertRaises(OverflowError, math.ldexp, 1., 1000000)
741n/a self.assertRaises(OverflowError, math.ldexp, -1., 1000000)
742n/a self.assertEqual(math.ldexp(1., -1000000), 0.)
743n/a self.assertEqual(math.ldexp(-1., -1000000), -0.)
744n/a self.assertEqual(math.ldexp(INF, 30), INF)
745n/a self.assertEqual(math.ldexp(NINF, -213), NINF)
746n/a self.assertTrue(math.isnan(math.ldexp(NAN, 0)))
747n/a
748n/a # large second argument
749n/a for n in [10**5, 10**10, 10**20, 10**40]:
750n/a self.assertEqual(math.ldexp(INF, -n), INF)
751n/a self.assertEqual(math.ldexp(NINF, -n), NINF)
752n/a self.assertEqual(math.ldexp(1., -n), 0.)
753n/a self.assertEqual(math.ldexp(-1., -n), -0.)
754n/a self.assertEqual(math.ldexp(0., -n), 0.)
755n/a self.assertEqual(math.ldexp(-0., -n), -0.)
756n/a self.assertTrue(math.isnan(math.ldexp(NAN, -n)))
757n/a
758n/a self.assertRaises(OverflowError, math.ldexp, 1., n)
759n/a self.assertRaises(OverflowError, math.ldexp, -1., n)
760n/a self.assertEqual(math.ldexp(0., n), 0.)
761n/a self.assertEqual(math.ldexp(-0., n), -0.)
762n/a self.assertEqual(math.ldexp(INF, n), INF)
763n/a self.assertEqual(math.ldexp(NINF, n), NINF)
764n/a self.assertTrue(math.isnan(math.ldexp(NAN, n)))
765n/a
766n/a def testLog(self):
767n/a self.assertRaises(TypeError, math.log)
768n/a self.ftest('log(1/e)', math.log(1/math.e), -1)
769n/a self.ftest('log(1)', math.log(1), 0)
770n/a self.ftest('log(e)', math.log(math.e), 1)
771n/a self.ftest('log(32,2)', math.log(32,2), 5)
772n/a self.ftest('log(10**40, 10)', math.log(10**40, 10), 40)
773n/a self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2)
774n/a self.ftest('log(10**1000)', math.log(10**1000),
775n/a 2302.5850929940457)
776n/a self.assertRaises(ValueError, math.log, -1.5)
777n/a self.assertRaises(ValueError, math.log, -10**1000)
778n/a self.assertRaises(ValueError, math.log, NINF)
779n/a self.assertEqual(math.log(INF), INF)
780n/a self.assertTrue(math.isnan(math.log(NAN)))
781n/a
782n/a def testLog1p(self):
783n/a self.assertRaises(TypeError, math.log1p)
784n/a for n in [2, 2**90, 2**300]:
785n/a self.assertAlmostEqual(math.log1p(n), math.log1p(float(n)))
786n/a self.assertRaises(ValueError, math.log1p, -1)
787n/a self.assertEqual(math.log1p(INF), INF)
788n/a
789n/a @requires_IEEE_754
790n/a def testLog2(self):
791n/a self.assertRaises(TypeError, math.log2)
792n/a
793n/a # Check some integer values
794n/a self.assertEqual(math.log2(1), 0.0)
795n/a self.assertEqual(math.log2(2), 1.0)
796n/a self.assertEqual(math.log2(4), 2.0)
797n/a
798n/a # Large integer values
799n/a self.assertEqual(math.log2(2**1023), 1023.0)
800n/a self.assertEqual(math.log2(2**1024), 1024.0)
801n/a self.assertEqual(math.log2(2**2000), 2000.0)
802n/a
803n/a self.assertRaises(ValueError, math.log2, -1.5)
804n/a self.assertRaises(ValueError, math.log2, NINF)
805n/a self.assertTrue(math.isnan(math.log2(NAN)))
806n/a
807n/a @requires_IEEE_754
808n/a # log2() is not accurate enough on Mac OS X Tiger (10.4)
809n/a @support.requires_mac_ver(10, 5)
810n/a def testLog2Exact(self):
811n/a # Check that we get exact equality for log2 of powers of 2.
812n/a actual = [math.log2(math.ldexp(1.0, n)) for n in range(-1074, 1024)]
813n/a expected = [float(n) for n in range(-1074, 1024)]
814n/a self.assertEqual(actual, expected)
815n/a
816n/a def testLog10(self):
817n/a self.assertRaises(TypeError, math.log10)
818n/a self.ftest('log10(0.1)', math.log10(0.1), -1)
819n/a self.ftest('log10(1)', math.log10(1), 0)
820n/a self.ftest('log10(10)', math.log10(10), 1)
821n/a self.ftest('log10(10**1000)', math.log10(10**1000), 1000.0)
822n/a self.assertRaises(ValueError, math.log10, -1.5)
823n/a self.assertRaises(ValueError, math.log10, -10**1000)
824n/a self.assertRaises(ValueError, math.log10, NINF)
825n/a self.assertEqual(math.log(INF), INF)
826n/a self.assertTrue(math.isnan(math.log10(NAN)))
827n/a
828n/a def testModf(self):
829n/a self.assertRaises(TypeError, math.modf)
830n/a
831n/a def testmodf(name, result, expected):
832n/a (v1, v2), (e1, e2) = result, expected
833n/a if abs(v1-e1) > eps or abs(v2-e2):
834n/a self.fail('%s returned %r, expected %r'%\
835n/a (name, result, expected))
836n/a
837n/a testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
838n/a testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
839n/a
840n/a self.assertEqual(math.modf(INF), (0.0, INF))
841n/a self.assertEqual(math.modf(NINF), (-0.0, NINF))
842n/a
843n/a modf_nan = math.modf(NAN)
844n/a self.assertTrue(math.isnan(modf_nan[0]))
845n/a self.assertTrue(math.isnan(modf_nan[1]))
846n/a
847n/a def testPow(self):
848n/a self.assertRaises(TypeError, math.pow)
849n/a self.ftest('pow(0,1)', math.pow(0,1), 0)
850n/a self.ftest('pow(1,0)', math.pow(1,0), 1)
851n/a self.ftest('pow(2,1)', math.pow(2,1), 2)
852n/a self.ftest('pow(2,-1)', math.pow(2,-1), 0.5)
853n/a self.assertEqual(math.pow(INF, 1), INF)
854n/a self.assertEqual(math.pow(NINF, 1), NINF)
855n/a self.assertEqual((math.pow(1, INF)), 1.)
856n/a self.assertEqual((math.pow(1, NINF)), 1.)
857n/a self.assertTrue(math.isnan(math.pow(NAN, 1)))
858n/a self.assertTrue(math.isnan(math.pow(2, NAN)))
859n/a self.assertTrue(math.isnan(math.pow(0, NAN)))
860n/a self.assertEqual(math.pow(1, NAN), 1)
861n/a
862n/a # pow(0., x)
863n/a self.assertEqual(math.pow(0., INF), 0.)
864n/a self.assertEqual(math.pow(0., 3.), 0.)
865n/a self.assertEqual(math.pow(0., 2.3), 0.)
866n/a self.assertEqual(math.pow(0., 2.), 0.)
867n/a self.assertEqual(math.pow(0., 0.), 1.)
868n/a self.assertEqual(math.pow(0., -0.), 1.)
869n/a self.assertRaises(ValueError, math.pow, 0., -2.)
870n/a self.assertRaises(ValueError, math.pow, 0., -2.3)
871n/a self.assertRaises(ValueError, math.pow, 0., -3.)
872n/a self.assertRaises(ValueError, math.pow, 0., NINF)
873n/a self.assertTrue(math.isnan(math.pow(0., NAN)))
874n/a
875n/a # pow(INF, x)
876n/a self.assertEqual(math.pow(INF, INF), INF)
877n/a self.assertEqual(math.pow(INF, 3.), INF)
878n/a self.assertEqual(math.pow(INF, 2.3), INF)
879n/a self.assertEqual(math.pow(INF, 2.), INF)
880n/a self.assertEqual(math.pow(INF, 0.), 1.)
881n/a self.assertEqual(math.pow(INF, -0.), 1.)
882n/a self.assertEqual(math.pow(INF, -2.), 0.)
883n/a self.assertEqual(math.pow(INF, -2.3), 0.)
884n/a self.assertEqual(math.pow(INF, -3.), 0.)
885n/a self.assertEqual(math.pow(INF, NINF), 0.)
886n/a self.assertTrue(math.isnan(math.pow(INF, NAN)))
887n/a
888n/a # pow(-0., x)
889n/a self.assertEqual(math.pow(-0., INF), 0.)
890n/a self.assertEqual(math.pow(-0., 3.), -0.)
891n/a self.assertEqual(math.pow(-0., 2.3), 0.)
892n/a self.assertEqual(math.pow(-0., 2.), 0.)
893n/a self.assertEqual(math.pow(-0., 0.), 1.)
894n/a self.assertEqual(math.pow(-0., -0.), 1.)
895n/a self.assertRaises(ValueError, math.pow, -0., -2.)
896n/a self.assertRaises(ValueError, math.pow, -0., -2.3)
897n/a self.assertRaises(ValueError, math.pow, -0., -3.)
898n/a self.assertRaises(ValueError, math.pow, -0., NINF)
899n/a self.assertTrue(math.isnan(math.pow(-0., NAN)))
900n/a
901n/a # pow(NINF, x)
902n/a self.assertEqual(math.pow(NINF, INF), INF)
903n/a self.assertEqual(math.pow(NINF, 3.), NINF)
904n/a self.assertEqual(math.pow(NINF, 2.3), INF)
905n/a self.assertEqual(math.pow(NINF, 2.), INF)
906n/a self.assertEqual(math.pow(NINF, 0.), 1.)
907n/a self.assertEqual(math.pow(NINF, -0.), 1.)
908n/a self.assertEqual(math.pow(NINF, -2.), 0.)
909n/a self.assertEqual(math.pow(NINF, -2.3), 0.)
910n/a self.assertEqual(math.pow(NINF, -3.), -0.)
911n/a self.assertEqual(math.pow(NINF, NINF), 0.)
912n/a self.assertTrue(math.isnan(math.pow(NINF, NAN)))
913n/a
914n/a # pow(-1, x)
915n/a self.assertEqual(math.pow(-1., INF), 1.)
916n/a self.assertEqual(math.pow(-1., 3.), -1.)
917n/a self.assertRaises(ValueError, math.pow, -1., 2.3)
918n/a self.assertEqual(math.pow(-1., 2.), 1.)
919n/a self.assertEqual(math.pow(-1., 0.), 1.)
920n/a self.assertEqual(math.pow(-1., -0.), 1.)
921n/a self.assertEqual(math.pow(-1., -2.), 1.)
922n/a self.assertRaises(ValueError, math.pow, -1., -2.3)
923n/a self.assertEqual(math.pow(-1., -3.), -1.)
924n/a self.assertEqual(math.pow(-1., NINF), 1.)
925n/a self.assertTrue(math.isnan(math.pow(-1., NAN)))
926n/a
927n/a # pow(1, x)
928n/a self.assertEqual(math.pow(1., INF), 1.)
929n/a self.assertEqual(math.pow(1., 3.), 1.)
930n/a self.assertEqual(math.pow(1., 2.3), 1.)
931n/a self.assertEqual(math.pow(1., 2.), 1.)
932n/a self.assertEqual(math.pow(1., 0.), 1.)
933n/a self.assertEqual(math.pow(1., -0.), 1.)
934n/a self.assertEqual(math.pow(1., -2.), 1.)
935n/a self.assertEqual(math.pow(1., -2.3), 1.)
936n/a self.assertEqual(math.pow(1., -3.), 1.)
937n/a self.assertEqual(math.pow(1., NINF), 1.)
938n/a self.assertEqual(math.pow(1., NAN), 1.)
939n/a
940n/a # pow(x, 0) should be 1 for any x
941n/a self.assertEqual(math.pow(2.3, 0.), 1.)
942n/a self.assertEqual(math.pow(-2.3, 0.), 1.)
943n/a self.assertEqual(math.pow(NAN, 0.), 1.)
944n/a self.assertEqual(math.pow(2.3, -0.), 1.)
945n/a self.assertEqual(math.pow(-2.3, -0.), 1.)
946n/a self.assertEqual(math.pow(NAN, -0.), 1.)
947n/a
948n/a # pow(x, y) is invalid if x is negative and y is not integral
949n/a self.assertRaises(ValueError, math.pow, -1., 2.3)
950n/a self.assertRaises(ValueError, math.pow, -15., -3.1)
951n/a
952n/a # pow(x, NINF)
953n/a self.assertEqual(math.pow(1.9, NINF), 0.)
954n/a self.assertEqual(math.pow(1.1, NINF), 0.)
955n/a self.assertEqual(math.pow(0.9, NINF), INF)
956n/a self.assertEqual(math.pow(0.1, NINF), INF)
957n/a self.assertEqual(math.pow(-0.1, NINF), INF)
958n/a self.assertEqual(math.pow(-0.9, NINF), INF)
959n/a self.assertEqual(math.pow(-1.1, NINF), 0.)
960n/a self.assertEqual(math.pow(-1.9, NINF), 0.)
961n/a
962n/a # pow(x, INF)
963n/a self.assertEqual(math.pow(1.9, INF), INF)
964n/a self.assertEqual(math.pow(1.1, INF), INF)
965n/a self.assertEqual(math.pow(0.9, INF), 0.)
966n/a self.assertEqual(math.pow(0.1, INF), 0.)
967n/a self.assertEqual(math.pow(-0.1, INF), 0.)
968n/a self.assertEqual(math.pow(-0.9, INF), 0.)
969n/a self.assertEqual(math.pow(-1.1, INF), INF)
970n/a self.assertEqual(math.pow(-1.9, INF), INF)
971n/a
972n/a # pow(x, y) should work for x negative, y an integer
973n/a self.ftest('(-2.)**3.', math.pow(-2.0, 3.0), -8.0)
974n/a self.ftest('(-2.)**2.', math.pow(-2.0, 2.0), 4.0)
975n/a self.ftest('(-2.)**1.', math.pow(-2.0, 1.0), -2.0)
976n/a self.ftest('(-2.)**0.', math.pow(-2.0, 0.0), 1.0)
977n/a self.ftest('(-2.)**-0.', math.pow(-2.0, -0.0), 1.0)
978n/a self.ftest('(-2.)**-1.', math.pow(-2.0, -1.0), -0.5)
979n/a self.ftest('(-2.)**-2.', math.pow(-2.0, -2.0), 0.25)
980n/a self.ftest('(-2.)**-3.', math.pow(-2.0, -3.0), -0.125)
981n/a self.assertRaises(ValueError, math.pow, -2.0, -0.5)
982n/a self.assertRaises(ValueError, math.pow, -2.0, 0.5)
983n/a
984n/a # the following tests have been commented out since they don't
985n/a # really belong here: the implementation of ** for floats is
986n/a # independent of the implementation of math.pow
987n/a #self.assertEqual(1**NAN, 1)
988n/a #self.assertEqual(1**INF, 1)
989n/a #self.assertEqual(1**NINF, 1)
990n/a #self.assertEqual(1**0, 1)
991n/a #self.assertEqual(1.**NAN, 1)
992n/a #self.assertEqual(1.**INF, 1)
993n/a #self.assertEqual(1.**NINF, 1)
994n/a #self.assertEqual(1.**0, 1)
995n/a
996n/a def testRadians(self):
997n/a self.assertRaises(TypeError, math.radians)
998n/a self.ftest('radians(180)', math.radians(180), math.pi)
999n/a self.ftest('radians(90)', math.radians(90), math.pi/2)
1000n/a self.ftest('radians(-45)', math.radians(-45), -math.pi/4)
1001n/a self.ftest('radians(0)', math.radians(0), 0)
1002n/a
1003n/a def testSin(self):
1004n/a self.assertRaises(TypeError, math.sin)
1005n/a self.ftest('sin(0)', math.sin(0), 0)
1006n/a self.ftest('sin(pi/2)', math.sin(math.pi/2), 1)
1007n/a self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1)
1008n/a try:
1009n/a self.assertTrue(math.isnan(math.sin(INF)))
1010n/a self.assertTrue(math.isnan(math.sin(NINF)))
1011n/a except ValueError:
1012n/a self.assertRaises(ValueError, math.sin, INF)
1013n/a self.assertRaises(ValueError, math.sin, NINF)
1014n/a self.assertTrue(math.isnan(math.sin(NAN)))
1015n/a
1016n/a def testSinh(self):
1017n/a self.assertRaises(TypeError, math.sinh)
1018n/a self.ftest('sinh(0)', math.sinh(0), 0)
1019n/a self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1)
1020n/a self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0)
1021n/a self.assertEqual(math.sinh(INF), INF)
1022n/a self.assertEqual(math.sinh(NINF), NINF)
1023n/a self.assertTrue(math.isnan(math.sinh(NAN)))
1024n/a
1025n/a def testSqrt(self):
1026n/a self.assertRaises(TypeError, math.sqrt)
1027n/a self.ftest('sqrt(0)', math.sqrt(0), 0)
1028n/a self.ftest('sqrt(1)', math.sqrt(1), 1)
1029n/a self.ftest('sqrt(4)', math.sqrt(4), 2)
1030n/a self.assertEqual(math.sqrt(INF), INF)
1031n/a self.assertRaises(ValueError, math.sqrt, -1)
1032n/a self.assertRaises(ValueError, math.sqrt, NINF)
1033n/a self.assertTrue(math.isnan(math.sqrt(NAN)))
1034n/a
1035n/a def testTan(self):
1036n/a self.assertRaises(TypeError, math.tan)
1037n/a self.ftest('tan(0)', math.tan(0), 0)
1038n/a self.ftest('tan(pi/4)', math.tan(math.pi/4), 1)
1039n/a self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1)
1040n/a try:
1041n/a self.assertTrue(math.isnan(math.tan(INF)))
1042n/a self.assertTrue(math.isnan(math.tan(NINF)))
1043n/a except:
1044n/a self.assertRaises(ValueError, math.tan, INF)
1045n/a self.assertRaises(ValueError, math.tan, NINF)
1046n/a self.assertTrue(math.isnan(math.tan(NAN)))
1047n/a
1048n/a def testTanh(self):
1049n/a self.assertRaises(TypeError, math.tanh)
1050n/a self.ftest('tanh(0)', math.tanh(0), 0)
1051n/a self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0,
1052n/a abs_tol=ulp(1))
1053n/a self.ftest('tanh(inf)', math.tanh(INF), 1)
1054n/a self.ftest('tanh(-inf)', math.tanh(NINF), -1)
1055n/a self.assertTrue(math.isnan(math.tanh(NAN)))
1056n/a
1057n/a @requires_IEEE_754
1058n/a @unittest.skipIf(sysconfig.get_config_var('TANH_PRESERVES_ZERO_SIGN') == 0,
1059n/a "system tanh() function doesn't copy the sign")
1060n/a def testTanhSign(self):
1061n/a # check that tanh(-0.) == -0. on IEEE 754 systems
1062n/a self.assertEqual(math.tanh(-0.), -0.)
1063n/a self.assertEqual(math.copysign(1., math.tanh(-0.)),
1064n/a math.copysign(1., -0.))
1065n/a
1066n/a def test_trunc(self):
1067n/a self.assertEqual(math.trunc(1), 1)
1068n/a self.assertEqual(math.trunc(-1), -1)
1069n/a self.assertEqual(type(math.trunc(1)), int)
1070n/a self.assertEqual(type(math.trunc(1.5)), int)
1071n/a self.assertEqual(math.trunc(1.5), 1)
1072n/a self.assertEqual(math.trunc(-1.5), -1)
1073n/a self.assertEqual(math.trunc(1.999999), 1)
1074n/a self.assertEqual(math.trunc(-1.999999), -1)
1075n/a self.assertEqual(math.trunc(-0.999999), -0)
1076n/a self.assertEqual(math.trunc(-100.999), -100)
1077n/a
1078n/a class TestTrunc(object):
1079n/a def __trunc__(self):
1080n/a return 23
1081n/a
1082n/a class TestNoTrunc(object):
1083n/a pass
1084n/a
1085n/a self.assertEqual(math.trunc(TestTrunc()), 23)
1086n/a
1087n/a self.assertRaises(TypeError, math.trunc)
1088n/a self.assertRaises(TypeError, math.trunc, 1, 2)
1089n/a self.assertRaises(TypeError, math.trunc, TestNoTrunc())
1090n/a
1091n/a def testIsfinite(self):
1092n/a self.assertTrue(math.isfinite(0.0))
1093n/a self.assertTrue(math.isfinite(-0.0))
1094n/a self.assertTrue(math.isfinite(1.0))
1095n/a self.assertTrue(math.isfinite(-1.0))
1096n/a self.assertFalse(math.isfinite(float("nan")))
1097n/a self.assertFalse(math.isfinite(float("inf")))
1098n/a self.assertFalse(math.isfinite(float("-inf")))
1099n/a
1100n/a def testIsnan(self):
1101n/a self.assertTrue(math.isnan(float("nan")))
1102n/a self.assertTrue(math.isnan(float("-nan")))
1103n/a self.assertTrue(math.isnan(float("inf") * 0.))
1104n/a self.assertFalse(math.isnan(float("inf")))
1105n/a self.assertFalse(math.isnan(0.))
1106n/a self.assertFalse(math.isnan(1.))
1107n/a
1108n/a def testIsinf(self):
1109n/a self.assertTrue(math.isinf(float("inf")))
1110n/a self.assertTrue(math.isinf(float("-inf")))
1111n/a self.assertTrue(math.isinf(1E400))
1112n/a self.assertTrue(math.isinf(-1E400))
1113n/a self.assertFalse(math.isinf(float("nan")))
1114n/a self.assertFalse(math.isinf(0.))
1115n/a self.assertFalse(math.isinf(1.))
1116n/a
1117n/a @requires_IEEE_754
1118n/a def test_nan_constant(self):
1119n/a self.assertTrue(math.isnan(math.nan))
1120n/a
1121n/a @requires_IEEE_754
1122n/a def test_inf_constant(self):
1123n/a self.assertTrue(math.isinf(math.inf))
1124n/a self.assertGreater(math.inf, 0.0)
1125n/a self.assertEqual(math.inf, float("inf"))
1126n/a self.assertEqual(-math.inf, float("-inf"))
1127n/a
1128n/a # RED_FLAG 16-Oct-2000 Tim
1129n/a # While 2.0 is more consistent about exceptions than previous releases, it
1130n/a # still fails this part of the test on some platforms. For now, we only
1131n/a # *run* test_exceptions() in verbose mode, so that this isn't normally
1132n/a # tested.
1133n/a @unittest.skipUnless(verbose, 'requires verbose mode')
1134n/a def test_exceptions(self):
1135n/a try:
1136n/a x = math.exp(-1000000000)
1137n/a except:
1138n/a # mathmodule.c is failing to weed out underflows from libm, or
1139n/a # we've got an fp format with huge dynamic range
1140n/a self.fail("underflowing exp() should not have raised "
1141n/a "an exception")
1142n/a if x != 0:
1143n/a self.fail("underflowing exp() should have returned 0")
1144n/a
1145n/a # If this fails, probably using a strict IEEE-754 conforming libm, and x
1146n/a # is +Inf afterwards. But Python wants overflows detected by default.
1147n/a try:
1148n/a x = math.exp(1000000000)
1149n/a except OverflowError:
1150n/a pass
1151n/a else:
1152n/a self.fail("overflowing exp() didn't trigger OverflowError")
1153n/a
1154n/a # If this fails, it could be a puzzle. One odd possibility is that
1155n/a # mathmodule.c's macros are getting confused while comparing
1156n/a # Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE
1157n/a # as a result (and so raising OverflowError instead).
1158n/a try:
1159n/a x = math.sqrt(-1.0)
1160n/a except ValueError:
1161n/a pass
1162n/a else:
1163n/a self.fail("sqrt(-1) didn't raise ValueError")
1164n/a
1165n/a @requires_IEEE_754
1166n/a def test_testfile(self):
1167n/a # Some tests need to be skipped on ancient OS X versions.
1168n/a # See issue #27953.
1169n/a SKIP_ON_TIGER = {'tan0064'}
1170n/a
1171n/a osx_version = None
1172n/a if sys.platform == 'darwin':
1173n/a version_txt = platform.mac_ver()[0]
1174n/a try:
1175n/a osx_version = tuple(map(int, version_txt.split('.')))
1176n/a except ValueError:
1177n/a pass
1178n/a
1179n/a fail_fmt = "{}: {}({!r}): {}"
1180n/a
1181n/a failures = []
1182n/a for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file):
1183n/a # Skip if either the input or result is complex
1184n/a if ai != 0.0 or ei != 0.0:
1185n/a continue
1186n/a if fn in ['rect', 'polar']:
1187n/a # no real versions of rect, polar
1188n/a continue
1189n/a # Skip certain tests on OS X 10.4.
1190n/a if osx_version is not None and osx_version < (10, 5):
1191n/a if id in SKIP_ON_TIGER:
1192n/a continue
1193n/a
1194n/a func = getattr(math, fn)
1195n/a
1196n/a if 'invalid' in flags or 'divide-by-zero' in flags:
1197n/a er = 'ValueError'
1198n/a elif 'overflow' in flags:
1199n/a er = 'OverflowError'
1200n/a
1201n/a try:
1202n/a result = func(ar)
1203n/a except ValueError:
1204n/a result = 'ValueError'
1205n/a except OverflowError:
1206n/a result = 'OverflowError'
1207n/a
1208n/a # Default tolerances
1209n/a ulp_tol, abs_tol = 5, 0.0
1210n/a
1211n/a failure = result_check(er, result, ulp_tol, abs_tol)
1212n/a if failure is None:
1213n/a continue
1214n/a
1215n/a msg = fail_fmt.format(id, fn, ar, failure)
1216n/a failures.append(msg)
1217n/a
1218n/a if failures:
1219n/a self.fail('Failures in test_testfile:\n ' +
1220n/a '\n '.join(failures))
1221n/a
1222n/a @requires_IEEE_754
1223n/a def test_mtestfile(self):
1224n/a fail_fmt = "{}: {}({!r}): {}"
1225n/a
1226n/a failures = []
1227n/a for id, fn, arg, expected, flags in parse_mtestfile(math_testcases):
1228n/a func = getattr(math, fn)
1229n/a
1230n/a if 'invalid' in flags or 'divide-by-zero' in flags:
1231n/a expected = 'ValueError'
1232n/a elif 'overflow' in flags:
1233n/a expected = 'OverflowError'
1234n/a
1235n/a try:
1236n/a got = func(arg)
1237n/a except ValueError:
1238n/a got = 'ValueError'
1239n/a except OverflowError:
1240n/a got = 'OverflowError'
1241n/a
1242n/a # Default tolerances
1243n/a ulp_tol, abs_tol = 5, 0.0
1244n/a
1245n/a # Exceptions to the defaults
1246n/a if fn == 'gamma':
1247n/a # Experimental results on one platform gave
1248n/a # an accuracy of <= 10 ulps across the entire float
1249n/a # domain. We weaken that to require 20 ulp accuracy.
1250n/a ulp_tol = 20
1251n/a
1252n/a elif fn == 'lgamma':
1253n/a # we use a weaker accuracy test for lgamma;
1254n/a # lgamma only achieves an absolute error of
1255n/a # a few multiples of the machine accuracy, in
1256n/a # general.
1257n/a abs_tol = 1e-15
1258n/a
1259n/a elif fn == 'erfc' and arg >= 0.0:
1260n/a # erfc has less-than-ideal accuracy for large
1261n/a # arguments (x ~ 25 or so), mainly due to the
1262n/a # error involved in computing exp(-x*x).
1263n/a #
1264n/a # Observed between CPython and mpmath at 25 dp:
1265n/a # x < 0 : err <= 2 ulp
1266n/a # 0 <= x < 1 : err <= 10 ulp
1267n/a # 1 <= x < 10 : err <= 100 ulp
1268n/a # 10 <= x < 20 : err <= 300 ulp
1269n/a # 20 <= x : < 600 ulp
1270n/a #
1271n/a if arg < 1.0:
1272n/a ulp_tol = 10
1273n/a elif arg < 10.0:
1274n/a ulp_tol = 100
1275n/a else:
1276n/a ulp_tol = 1000
1277n/a
1278n/a failure = result_check(expected, got, ulp_tol, abs_tol)
1279n/a if failure is None:
1280n/a continue
1281n/a
1282n/a msg = fail_fmt.format(id, fn, arg, failure)
1283n/a failures.append(msg)
1284n/a
1285n/a if failures:
1286n/a self.fail('Failures in test_mtestfile:\n ' +
1287n/a '\n '.join(failures))
1288n/a
1289n/a
1290n/aclass IsCloseTests(unittest.TestCase):
1291n/a isclose = math.isclose # sublcasses should override this
1292n/a
1293n/a def assertIsClose(self, a, b, *args, **kwargs):
1294n/a self.assertTrue(self.isclose(a, b, *args, **kwargs),
1295n/a msg="%s and %s should be close!" % (a, b))
1296n/a
1297n/a def assertIsNotClose(self, a, b, *args, **kwargs):
1298n/a self.assertFalse(self.isclose(a, b, *args, **kwargs),
1299n/a msg="%s and %s should not be close!" % (a, b))
1300n/a
1301n/a def assertAllClose(self, examples, *args, **kwargs):
1302n/a for a, b in examples:
1303n/a self.assertIsClose(a, b, *args, **kwargs)
1304n/a
1305n/a def assertAllNotClose(self, examples, *args, **kwargs):
1306n/a for a, b in examples:
1307n/a self.assertIsNotClose(a, b, *args, **kwargs)
1308n/a
1309n/a def test_negative_tolerances(self):
1310n/a # ValueError should be raised if either tolerance is less than zero
1311n/a with self.assertRaises(ValueError):
1312n/a self.assertIsClose(1, 1, rel_tol=-1e-100)
1313n/a with self.assertRaises(ValueError):
1314n/a self.assertIsClose(1, 1, rel_tol=1e-100, abs_tol=-1e10)
1315n/a
1316n/a def test_identical(self):
1317n/a # identical values must test as close
1318n/a identical_examples = [(2.0, 2.0),
1319n/a (0.1e200, 0.1e200),
1320n/a (1.123e-300, 1.123e-300),
1321n/a (12345, 12345.0),
1322n/a (0.0, -0.0),
1323n/a (345678, 345678)]
1324n/a self.assertAllClose(identical_examples, rel_tol=0.0, abs_tol=0.0)
1325n/a
1326n/a def test_eight_decimal_places(self):
1327n/a # examples that are close to 1e-8, but not 1e-9
1328n/a eight_decimal_places_examples = [(1e8, 1e8 + 1),
1329n/a (-1e-8, -1.000000009e-8),
1330n/a (1.12345678, 1.12345679)]
1331n/a self.assertAllClose(eight_decimal_places_examples, rel_tol=1e-8)
1332n/a self.assertAllNotClose(eight_decimal_places_examples, rel_tol=1e-9)
1333n/a
1334n/a def test_near_zero(self):
1335n/a # values close to zero
1336n/a near_zero_examples = [(1e-9, 0.0),
1337n/a (-1e-9, 0.0),
1338n/a (-1e-150, 0.0)]
1339n/a # these should not be close to any rel_tol
1340n/a self.assertAllNotClose(near_zero_examples, rel_tol=0.9)
1341n/a # these should be close to abs_tol=1e-8
1342n/a self.assertAllClose(near_zero_examples, abs_tol=1e-8)
1343n/a
1344n/a def test_identical_infinite(self):
1345n/a # these are close regardless of tolerance -- i.e. they are equal
1346n/a self.assertIsClose(INF, INF)
1347n/a self.assertIsClose(INF, INF, abs_tol=0.0)
1348n/a self.assertIsClose(NINF, NINF)
1349n/a self.assertIsClose(NINF, NINF, abs_tol=0.0)
1350n/a
1351n/a def test_inf_ninf_nan(self):
1352n/a # these should never be close (following IEEE 754 rules for equality)
1353n/a not_close_examples = [(NAN, NAN),
1354n/a (NAN, 1e-100),
1355n/a (1e-100, NAN),
1356n/a (INF, NAN),
1357n/a (NAN, INF),
1358n/a (INF, NINF),
1359n/a (INF, 1.0),
1360n/a (1.0, INF),
1361n/a (INF, 1e308),
1362n/a (1e308, INF)]
1363n/a # use largest reasonable tolerance
1364n/a self.assertAllNotClose(not_close_examples, abs_tol=0.999999999999999)
1365n/a
1366n/a def test_zero_tolerance(self):
1367n/a # test with zero tolerance
1368n/a zero_tolerance_close_examples = [(1.0, 1.0),
1369n/a (-3.4, -3.4),
1370n/a (-1e-300, -1e-300)]
1371n/a self.assertAllClose(zero_tolerance_close_examples, rel_tol=0.0)
1372n/a
1373n/a zero_tolerance_not_close_examples = [(1.0, 1.000000000000001),
1374n/a (0.99999999999999, 1.0),
1375n/a (1.0e200, .999999999999999e200)]
1376n/a self.assertAllNotClose(zero_tolerance_not_close_examples, rel_tol=0.0)
1377n/a
1378n/a def test_asymmetry(self):
1379n/a # test the asymmetry example from PEP 485
1380n/a self.assertAllClose([(9, 10), (10, 9)], rel_tol=0.1)
1381n/a
1382n/a def test_integers(self):
1383n/a # test with integer values
1384n/a integer_examples = [(100000001, 100000000),
1385n/a (123456789, 123456788)]
1386n/a
1387n/a self.assertAllClose(integer_examples, rel_tol=1e-8)
1388n/a self.assertAllNotClose(integer_examples, rel_tol=1e-9)
1389n/a
1390n/a def test_decimals(self):
1391n/a # test with Decimal values
1392n/a from decimal import Decimal
1393n/a
1394n/a decimal_examples = [(Decimal('1.00000001'), Decimal('1.0')),
1395n/a (Decimal('1.00000001e-20'), Decimal('1.0e-20')),
1396n/a (Decimal('1.00000001e-100'), Decimal('1.0e-100')),
1397n/a (Decimal('1.00000001e20'), Decimal('1.0e20'))]
1398n/a self.assertAllClose(decimal_examples, rel_tol=1e-8)
1399n/a self.assertAllNotClose(decimal_examples, rel_tol=1e-9)
1400n/a
1401n/a def test_fractions(self):
1402n/a # test with Fraction values
1403n/a from fractions import Fraction
1404n/a
1405n/a fraction_examples = [
1406n/a (Fraction(1, 100000000) + 1, Fraction(1)),
1407n/a (Fraction(100000001), Fraction(100000000)),
1408n/a (Fraction(10**8 + 1, 10**28), Fraction(1, 10**20))]
1409n/a self.assertAllClose(fraction_examples, rel_tol=1e-8)
1410n/a self.assertAllNotClose(fraction_examples, rel_tol=1e-9)
1411n/a
1412n/a
1413n/adef test_main():
1414n/a from doctest import DocFileSuite
1415n/a suite = unittest.TestSuite()
1416n/a suite.addTest(unittest.makeSuite(MathTests))
1417n/a suite.addTest(unittest.makeSuite(IsCloseTests))
1418n/a suite.addTest(DocFileSuite("ieee754.txt"))
1419n/a run_unittest(suite)
1420n/a
1421n/aif __name__ == '__main__':
1422n/a test_main()