summaryrefslogtreecommitdiffstats
path: root/win/tclWinError.c
blob: e70e1c28cd6b150e839a559eb4e102026deb8bef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/* 
 * tclWinError.c --
 *
 *	This file contains code for converting from Win32 errors to
 *	errno errors.
 *
 * Copyright (c) 1995-1996 by Sun Microsystems, Inc.
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * RCS: @(#) $Id: tclWinError.c,v 1.5 2002/05/27 10:14:21 dkf Exp $
 */

#include "tclWinInt.h"

/*
 * The following table contains the mapping from Win32 errors to
 * errno errors.
 */

static char errorTable[] = {
    0,
    EINVAL,	/* ERROR_INVALID_FUNCTION	1 */
    ENOENT,	/* ERROR_FILE_NOT_FOUND		2 */
    ENOENT,	/* ERROR_PATH_NOT_FOUND		3 */
    EMFILE,	/* ERROR_TOO_MANY_OPEN_FILES	4 */
    EACCES,	/* ERROR_ACCESS_DENIED		5 */
    EBADF,	/* ERROR_INVALID_HANDLE		6 */
    ENOMEM,	/* ERROR_ARENA_TRASHED		7 */
    ENOMEM,	/* ERROR_NOT_ENOUGH_MEMORY	8 */
    ENOMEM,	/* ERROR_INVALID_BLOCK		9 */
    E2BIG,	/* ERROR_BAD_ENVIRONMENT	10 */
    ENOEXEC,	/* ERROR_BAD_FORMAT		11 */
    EACCES,	/* ERROR_INVALID_ACCESS		12 */
    EINVAL,	/* ERROR_INVALID_DATA		13 */
    EFAULT,	/* ERROR_OUT_OF_MEMORY		14 */
    ENOENT,	/* ERROR_INVALID_DRIVE		15 */
    EACCES,	/* ERROR_CURRENT_DIRECTORY	16 */
    EXDEV,	/* ERROR_NOT_SAME_DEVICE	17 */
    ENOENT,	/* ERROR_NO_MORE_FILES		18 */
    EROFS,	/* ERROR_WRITE_PROTECT		19 */
    ENXIO,	/* ERROR_BAD_UNIT		20 */
    EBUSY,	/* ERROR_NOT_READY		21 */
    EIO,	/* ERROR_BAD_COMMAND		22 */
    EIO,	/* ERROR_CRC			23 */
    EIO,	/* ERROR_BAD_LENGTH		24 */
    EIO,	/* ERROR_SEEK			25 */
    EIO,	/* ERROR_NOT_DOS_DISK		26 */
    ENXIO,	/* ERROR_SECTOR_NOT_FOUND	27 */
    EBUSY,	/* ERROR_OUT_OF_PAPER		28 */
    EIO,	/* ERROR_WRITE_FAULT		29 */
    EIO,	/* ERROR_READ_FAULT		30 */
    EIO,	/* ERROR_GEN_FAILURE		31 */
    EACCES,	/* ERROR_SHARING_VIOLATION	32 */
    EACCES,	/* ERROR_LOCK_VIOLATION		33 */
    ENXIO,	/* ERROR_WRONG_DISK		34 */
    ENFILE,	/* ERROR_FCB_UNAVAILABLE	35 */
    ENFILE,	/* ERROR_SHARING_BUFFER_EXCEEDED	36 */
    EINVAL,	/* 37 */
    EINVAL,	/* 38 */
    ENOSPC,	/* ERROR_HANDLE_DISK_FULL	39 */
    EINVAL,	/* 40 */
    EINVAL,	/* 41 */
    EINVAL,	/* 42 */
    EINVAL,	/* 43 */
    EINVAL,	/* 44 */
    EINVAL,	/* 45 */
    EINVAL,	/* 46 */
    EINVAL,	/* 47 */
    EINVAL,	/* 48 */
    EINVAL,	/* 49 */
    ENODEV,	/* ERROR_NOT_SUPPORTED		50 */
    EBUSY,	/* ERROR_REM_NOT_LIST		51 */
    EEXIST,	/* ERROR_DUP_NAME		52 */
    ENOENT,	/* ERROR_BAD_NETPATH		53 */
    EBUSY,	/* ERROR_NETWORK_BUSY		54 */
    ENODEV,	/* ERROR_DEV_NOT_EXIST		55 */
    EAGAIN,	/* ERROR_TOO_MANY_CMDS		56 */
    EIO,	/* ERROR_ADAP_HDW_ERR		57 */
    EIO,	/* ERROR_BAD_NET_RESP		58 */
    EIO,	/* ERROR_UNEXP_NET_ERR		59 */
    EINVAL,	/* ERROR_BAD_REM_ADAP		60 */
    EFBIG,	/* ERROR_PRINTQ_FULL		61 */
    ENOSPC,	/* ERROR_NO_SPOOL_SPACE		62 */
    ENOENT,	/* ERROR_PRINT_CANCELLED	63 */
    ENOENT,	/* ERROR_NETNAME_DELETED	64 */
    EACCES,	/* ERROR_NETWORK_ACCESS_DENIED	65 */
    ENODEV,	/* ERROR_BAD_DEV_TYPE		66 */
    ENOENT,	/* ERROR_BAD_NET_NAME		67 */
    ENFILE,	/* ERROR_TOO_MANY_NAMES		68 */
    EIO,	/* ERROR_TOO_MANY_SESS		69 */
    EAGAIN,	/* ERROR_SHARING_PAUSED		70 */
    EINVAL,	/* ERROR_REQ_NOT_ACCEP		71 */
    EAGAIN,	/* ERROR_REDIR_PAUSED		72 */
    EINVAL,	/* 73 */
    EINVAL,	/* 74 */
    EINVAL,	/* 75 */
    EINVAL,	/* 76 */
    EINVAL,	/* 77 */
    EINVAL,	/* 78 */
    EINVAL,	/* 79 */
    EEXIST,	/* ERROR_FILE_EXISTS		80 */
    EINVAL,	/* 81 */
    ENOSPC,	/* ERROR_CANNOT_MAKE		82 */
    EIO,	/* ERROR_FAIL_I24		83 */
    ENFILE,	/* ERROR_OUT_OF_STRUCTURES	84 */
    EEXIST,	/* ERROR_ALREADY_ASSIGNED	85 */
    EPERM,	/* ERROR_INVALID_PASSWORD	86 */
    EINVAL,	/* ERROR_INVALID_PARAMETER	87 */
    EIO,	/* ERROR_NET_WRITE_FAULT	88 */
    EAGAIN,	/* ERROR_NO_PROC_SLOTS		89 */
    EINVAL,	/* 90 */
    EINVAL,	/* 91 */
    EINVAL,	/* 92 */
    EINVAL,	/* 93 */
    EINVAL,	/* 94 */
    EINVAL,	/* 95 */
    EINVAL,	/* 96 */
    EINVAL,	/* 97 */
    EINVAL,	/* 98 */
    EINVAL,	/* 99 */
    EINVAL,	/* 100 */
    EINVAL,	/* 101 */
    EINVAL,	/* 102 */
    EINVAL,	/* 103 */
    EINVAL,	/* 104 */
    EINVAL,	/* 105 */
    EINVAL,	/* 106 */
    EXDEV,	/* ERROR_DISK_CHANGE		107 */
    EAGAIN,	/* ERROR_DRIVE_LOCKED		108 */
    EPIPE,	/* ERROR_BROKEN_PIPE		109 */
    ENOENT,	/* ERROR_OPEN_FAILED		110 */
    EINVAL,	/* ERROR_BUFFER_OVERFLOW	111 */
    ENOSPC,	/* ERROR_DISK_FULL		112 */
    EMFILE,	/* ERROR_NO_MORE_SEARCH_HANDLES	113 */
    EBADF,	/* ERROR_INVALID_TARGET_HANDLE	114 */
    EFAULT,	/* ERROR_PROTECTION_VIOLATION	115 */
    EINVAL,	/* 116 */
    EINVAL,	/* 117 */
    EINVAL,	/* 118 */
    EINVAL,	/* 119 */
    EINVAL,	/* 120 */
    EINVAL,	/* 121 */
    EINVAL,	/* 122 */
    ENOENT,	/* ERROR_INVALID_NAME		123 */
    EINVAL,	/* 124 */
    EINVAL,	/* 125 */
    EINVAL,	/* 126 */
    EINVAL,	/* ERROR_PROC_NOT_FOUND		127 */
    ECHILD,	/* ERROR_WAIT_NO_CHILDREN	128 */
    ECHILD,	/* ERROR_CHILD_NOT_COMPLETE	129 */
    EBADF,	/* ERROR_DIRECT_ACCESS_HANDLE	130 */
    EINVAL,	/* ERROR_NEGATIVE_SEEK		131 */
    ESPIPE,	/* ERROR_SEEK_ON_DEVICE		132 */
    EINVAL,	/* 133 */
    EINVAL,	/* 134 */
    EINVAL,	/* 135 */
    EINVAL,	/* 136 */
    EINVAL,	/* 137 */
    EINVAL,	/* 138 */
    EINVAL,	/* 139 */
    EINVAL,	/* 140 */
    EINVAL,	/* 141 */
    EAGAIN,	/* ERROR_BUSY_DRIVE		142 */
    EINVAL,	/* 143 */
    EINVAL,	/* 144 */
    EEXIST,	/* ERROR_DIR_NOT_EMPTY		145 */
    EINVAL,	/* 146 */
    EINVAL,	/* 147 */
    EINVAL,	/* 148 */
    EINVAL,	/* 149 */
    EINVAL,	/* 150 */
    EINVAL,	/* 151 */
    EINVAL,	/* 152 */
    EINVAL,	/* 153 */
    EINVAL,	/* 154 */
    EINVAL,	/* 155 */
    EINVAL,	/* 156 */
    EINVAL,	/* 157 */
    EACCES,	/* ERROR_NOT_LOCKED		158 */
    EINVAL,	/* 159 */
    EINVAL,	/* 160 */
    ENOENT,	/* ERROR_BAD_PATHNAME	        161 */
    EINVAL,	/* 162 */
    EINVAL,	/* 163 */
    EINVAL,	/* 164 */
    EINVAL,	/* 165 */
    EINVAL,	/* 166 */
    EACCES,	/* ERROR_LOCK_FAILED		167 */
    EINVAL,	/* 168 */
    EINVAL,	/* 169 */
    EINVAL,	/* 170 */
    EINVAL,	/* 171 */
    EINVAL,	/* 172 */
    EINVAL,	/* 173 */
    EINVAL,	/* 174 */
    EINVAL,	/* 175 */
    EINVAL,	/* 176 */
    EINVAL,	/* 177 */
    EINVAL,	/* 178 */
    EINVAL,	/* 179 */
    EINVAL,	/* 180 */
    EINVAL,	/* 181 */
    EINVAL,	/* 182 */
    EEXIST,	/* ERROR_ALREADY_EXISTS		183 */
    ECHILD,	/* ERROR_NO_CHILD_PROCESS	184 */
    EINVAL,	/* 185 */
    EINVAL,	/* 186 */
    EINVAL,	/* 187 */
    EINVAL,	/* 188 */
    EINVAL,	/* 189 */
    EINVAL,	/* 190 */
    EINVAL,	/* 191 */
    EINVAL,	/* 192 */
    EINVAL,	/* 193 */
    EINVAL,	/* 194 */
    EINVAL,	/* 195 */
    EINVAL,	/* 196 */
    EINVAL,	/* 197 */
    EINVAL,	/* 198 */
    EINVAL,	/* 199 */
    EINVAL,	/* 200 */
    EINVAL,	/* 201 */
    EINVAL,	/* 202 */
    EINVAL,	/* 203 */
    EINVAL,	/* 204 */
    EINVAL,	/* 205 */
    ENAMETOOLONG,/* ERROR_FILENAME_EXCED_RANGE	206 */
    EINVAL,	/* 207 */
    EINVAL,	/* 208 */
    EINVAL,	/* 209 */
    EINVAL,	/* 210 */
    EINVAL,	/* 211 */
    EINVAL,	/* 212 */
    EINVAL,	/* 213 */
    EINVAL,	/* 214 */
    EINVAL,	/* 215 */
    EINVAL,	/* 216 */
    EINVAL,	/* 217 */
    EINVAL,	/* 218 */
    EINVAL,	/* 219 */
    EINVAL,	/* 220 */
    EINVAL,	/* 221 */
    EINVAL,	/* 222 */
    EINVAL,	/* 223 */
    EINVAL,	/* 224 */
    EINVAL,	/* 225 */
    EINVAL,	/* 226 */
    EINVAL,	/* 227 */
    EINVAL,	/* 228 */
    EINVAL,	/* 229 */
    EPIPE,	/* ERROR_BAD_PIPE		230 */
    EAGAIN,	/* ERROR_PIPE_BUSY		231 */
    EPIPE,	/* ERROR_NO_DATA		232 */
    EPIPE,	/* ERROR_PIPE_NOT_CONNECTED	233 */
    EINVAL,	/* 234 */
    EINVAL,	/* 235 */
    EINVAL,	/* 236 */
    EINVAL,	/* 237 */
    EINVAL,	/* 238 */
    EINVAL,	/* 239 */
    EINVAL,	/* 240 */
    EINVAL,	/* 241 */
    EINVAL,	/* 242 */
    EINVAL,	/* 243 */
    EINVAL,	/* 244 */
    EINVAL,	/* 245 */
    EINVAL,	/* 246 */
    EINVAL,	/* 247 */
    EINVAL,	/* 248 */
    EINVAL,	/* 249 */
    EINVAL,	/* 250 */
    EINVAL,	/* 251 */
    EINVAL,	/* 252 */
    EINVAL,	/* 253 */
    EINVAL,	/* 254 */
    EINVAL,	/* 255 */
    EINVAL,	/* 256 */
    EINVAL,	/* 257 */
    EINVAL,	/* 258 */
    EINVAL,	/* 259 */
    EINVAL,	/* 260 */
    EINVAL,	/* 261 */
    EINVAL,	/* 262 */
    EINVAL,	/* 263 */
    EINVAL,	/* 264 */
    EINVAL,	/* 265 */
    EINVAL,	/* 266 */
    ENOTDIR,	/* ERROR_DIRECTORY		267 */
};

static const unsigned int tableLen = sizeof(errorTable);

/*
 * The following table contains the mapping from WinSock errors to
 * errno errors.
 */

static int wsaErrorTable[] = {
    EWOULDBLOCK,	/* WSAEWOULDBLOCK */
    EINPROGRESS,	/* WSAEINPROGRESS */
    EALREADY,		/* WSAEALREADY */
    ENOTSOCK,		/* WSAENOTSOCK */
    EDESTADDRREQ,	/* WSAEDESTADDRREQ */
    EMSGSIZE,		/* WSAEMSGSIZE */
    EPROTOTYPE,		/* WSAEPROTOTYPE */
    ENOPROTOOPT,	/* WSAENOPROTOOPT */
    EPROTONOSUPPORT,	/* WSAEPROTONOSUPPORT */
    ESOCKTNOSUPPORT,	/* WSAESOCKTNOSUPPORT */
    EOPNOTSUPP,		/* WSAEOPNOTSUPP */
    EPFNOSUPPORT,	/* WSAEPFNOSUPPORT */
    EAFNOSUPPORT,	/* WSAEAFNOSUPPORT */
    EADDRINUSE,		/* WSAEADDRINUSE */
    EADDRNOTAVAIL,	/* WSAEADDRNOTAVAIL */
    ENETDOWN,		/* WSAENETDOWN */
    ENETUNREACH,	/* WSAENETUNREACH */
    ENETRESET,		/* WSAENETRESET */
    ECONNABORTED,	/* WSAECONNABORTED */
    ECONNRESET,		/* WSAECONNRESET */
    ENOBUFS,		/* WSAENOBUFS */
    EISCONN,		/* WSAEISCONN */
    ENOTCONN,		/* WSAENOTCONN */
    ESHUTDOWN,		/* WSAESHUTDOWN */
    ETOOMANYREFS,	/* WSAETOOMANYREFS */
    ETIMEDOUT,		/* WSAETIMEDOUT */
    ECONNREFUSED,	/* WSAECONNREFUSED */
    ELOOP,		/* WSAELOOP */
    ENAMETOOLONG,	/* WSAENAMETOOLONG */
    EHOSTDOWN,		/* WSAEHOSTDOWN */
    EHOSTUNREACH,	/* WSAEHOSTUNREACH */
    ENOTEMPTY,		/* WSAENOTEMPTY */
    EAGAIN,		/* WSAEPROCLIM */
    EUSERS,		/* WSAEUSERS */
    EDQUOT,		/* WSAEDQUOT */
    ESTALE,		/* WSAESTALE */
    EREMOTE,		/* WSAEREMOTE */
};

/*
 *----------------------------------------------------------------------
 *
 * TclWinConvertError --
 *
 *	This routine converts a Win32 error into an errno value.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Sets the errno global variable.
 *
 *----------------------------------------------------------------------
 */

void
TclWinConvertError(errCode)
    DWORD errCode;		/* Win32 error code. */
{
    if (errCode >= tableLen) {
	Tcl_SetErrno(EINVAL);
    } else {
	Tcl_SetErrno(errorTable[errCode]);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TclWinConvertWSAError --
 *
 *	This routine converts a WinSock error into an errno value.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Sets the errno global variable.
 *
 *----------------------------------------------------------------------
 */

void
TclWinConvertWSAError(errCode)
    DWORD errCode;		/* Win32 error code. */
{
    if ((errCode >= WSAEWOULDBLOCK) && (errCode <= WSAEREMOTE)) {
	Tcl_SetErrno(wsaErrorTable[errCode - WSAEWOULDBLOCK]);
    } else {
	Tcl_SetErrno(EINVAL);
    }
}
= ulp_abs_check(expected, got, ulp_tol, abs_tol) # arguments are not equal, and if numeric, are too far apart if failure is not None: fail_fmt = "expected {!r}, got {!r}" fail_msg = fail_fmt.format(expected, got) fail_msg += ' ({})'.format(failure) return fail_msg else: return None # Class providing an __index__ method. class MyIndexable(object): def __init__(self, value): self.value = value def __index__(self): return self.value class MathTests(unittest.TestCase): def ftest(self, name, got, expected, ulp_tol=5, abs_tol=0.0): """Compare arguments expected and got, as floats, if either is a float, using a tolerance expressed in multiples of ulp(expected) or absolutely, whichever is greater. As a convenience, when neither argument is a float, and for non-finite floats, exact equality is demanded. Also, nan==nan in this function. """ failure = result_check(expected, got, ulp_tol, abs_tol) if failure is not None: self.fail("{}: {}".format(name, failure)) def testConstants(self): # Ref: Abramowitz & Stegun (Dover, 1965) self.ftest('pi', math.pi, 3.141592653589793238462643) self.ftest('e', math.e, 2.718281828459045235360287) self.assertEqual(math.tau, 2*math.pi) def testAcos(self): self.assertRaises(TypeError, math.acos) self.ftest('acos(-1)', math.acos(-1), math.pi) self.ftest('acos(0)', math.acos(0), math.pi/2) self.ftest('acos(1)', math.acos(1), 0) self.assertRaises(ValueError, math.acos, INF) self.assertRaises(ValueError, math.acos, NINF) self.assertRaises(ValueError, math.acos, 1 + eps) self.assertRaises(ValueError, math.acos, -1 - eps) self.assertTrue(math.isnan(math.acos(NAN))) def testAcosh(self): self.assertRaises(TypeError, math.acosh) self.ftest('acosh(1)', math.acosh(1), 0) self.ftest('acosh(2)', math.acosh(2), 1.3169578969248168) self.assertRaises(ValueError, math.acosh, 0) self.assertRaises(ValueError, math.acosh, -1) self.assertEqual(math.acosh(INF), INF) self.assertRaises(ValueError, math.acosh, NINF) self.assertTrue(math.isnan(math.acosh(NAN))) def testAsin(self): self.assertRaises(TypeError, math.asin) self.ftest('asin(-1)', math.asin(-1), -math.pi/2) self.ftest('asin(0)', math.asin(0), 0) self.ftest('asin(1)', math.asin(1), math.pi/2) self.assertRaises(ValueError, math.asin, INF) self.assertRaises(ValueError, math.asin, NINF) self.assertRaises(ValueError, math.asin, 1 + eps) self.assertRaises(ValueError, math.asin, -1 - eps) self.assertTrue(math.isnan(math.asin(NAN))) def testAsinh(self): self.assertRaises(TypeError, math.asinh) self.ftest('asinh(0)', math.asinh(0), 0) self.ftest('asinh(1)', math.asinh(1), 0.88137358701954305) self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305) self.assertEqual(math.asinh(INF), INF) self.assertEqual(math.asinh(NINF), NINF) self.assertTrue(math.isnan(math.asinh(NAN))) def testAtan(self): self.assertRaises(TypeError, math.atan) self.ftest('atan(-1)', math.atan(-1), -math.pi/4) self.ftest('atan(0)', math.atan(0), 0) self.ftest('atan(1)', math.atan(1), math.pi/4) self.ftest('atan(inf)', math.atan(INF), math.pi/2) self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2) self.assertTrue(math.isnan(math.atan(NAN))) def testAtanh(self): self.assertRaises(TypeError, math.atan) self.ftest('atanh(0)', math.atanh(0), 0) self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489) self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489) self.assertRaises(ValueError, math.atanh, 1) self.assertRaises(ValueError, math.atanh, -1) self.assertRaises(ValueError, math.atanh, INF) self.assertRaises(ValueError, math.atanh, NINF) self.assertTrue(math.isnan(math.atanh(NAN))) def testAtan2(self): self.assertRaises(TypeError, math.atan2) self.ftest('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2) self.ftest('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4) self.ftest('atan2(0, 1)', math.atan2(0, 1), 0) self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4) self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2) # math.atan2(0, x) self.ftest('atan2(0., -inf)', math.atan2(0., NINF), math.pi) self.ftest('atan2(0., -2.3)', math.atan2(0., -2.3), math.pi) self.ftest('atan2(0., -0.)', math.atan2(0., -0.), math.pi) self.assertEqual(math.atan2(0., 0.), 0.) self.assertEqual(math.atan2(0., 2.3), 0.) self.assertEqual(math.atan2(0., INF), 0.) self.assertTrue(math.isnan(math.atan2(0., NAN))) # math.atan2(-0, x) self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi) self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi) self.ftest('atan2(-0., -0.)', math.atan2(-0., -0.), -math.pi) self.assertEqual(math.atan2(-0., 0.), -0.) self.assertEqual(math.atan2(-0., 2.3), -0.) self.assertEqual(math.atan2(-0., INF), -0.) self.assertTrue(math.isnan(math.atan2(-0., NAN))) # math.atan2(INF, x) self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4) self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2) self.ftest('atan2(inf, -0.)', math.atan2(INF, -0.0), math.pi/2) self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2) self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2) self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4) self.assertTrue(math.isnan(math.atan2(INF, NAN))) # math.atan2(NINF, x) self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4) self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2) self.ftest('atan2(-inf, -0.)', math.atan2(NINF, -0.0), -math.pi/2) self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2) self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2) self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4) self.assertTrue(math.isnan(math.atan2(NINF, NAN))) # math.atan2(+finite, x) self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi) self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2) self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2) self.assertEqual(math.atan2(2.3, INF), 0.) self.assertTrue(math.isnan(math.atan2(2.3, NAN))) # math.atan2(-finite, x) self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi) self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2) self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2) self.assertEqual(math.atan2(-2.3, INF), -0.) self.assertTrue(math.isnan(math.atan2(-2.3, NAN))) # math.atan2(NAN, x) self.assertTrue(math.isnan(math.atan2(NAN, NINF))) self.assertTrue(math.isnan(math.atan2(NAN, -2.3))) self.assertTrue(math.isnan(math.atan2(NAN, -0.))) self.assertTrue(math.isnan(math.atan2(NAN, 0.))) self.assertTrue(math.isnan(math.atan2(NAN, 2.3))) self.assertTrue(math.isnan(math.atan2(NAN, INF))) self.assertTrue(math.isnan(math.atan2(NAN, NAN))) def testCeil(self): self.assertRaises(TypeError, math.ceil) self.assertEqual(int, type(math.ceil(0.5))) self.ftest('ceil(0.5)', math.ceil(0.5), 1) self.ftest('ceil(1.0)', math.ceil(1.0), 1) self.ftest('ceil(1.5)', math.ceil(1.5), 2) self.ftest('ceil(-0.5)', math.ceil(-0.5), 0) self.ftest('ceil(-1.0)', math.ceil(-1.0), -1) self.ftest('ceil(-1.5)', math.ceil(-1.5), -1) #self.assertEqual(math.ceil(INF), INF) #self.assertEqual(math.ceil(NINF), NINF) #self.assertTrue(math.isnan(math.ceil(NAN))) class TestCeil: def __ceil__(self): return 42 class TestNoCeil: pass self.ftest('ceil(TestCeil())', math.ceil(TestCeil()), 42) self.assertRaises(TypeError, math.ceil, TestNoCeil()) t = TestNoCeil() t.__ceil__ = lambda *args: args self.assertRaises(TypeError, math.ceil, t) self.assertRaises(TypeError, math.ceil, t, 0) @requires_IEEE_754 def testCopysign(self): self.assertEqual(math.copysign(1, 42), 1.0) self.assertEqual(math.copysign(0., 42), 0.0) self.assertEqual(math.copysign(1., -42), -1.0) self.assertEqual(math.copysign(3, 0.), 3.0) self.assertEqual(math.copysign(4., -0.), -4.0) self.assertRaises(TypeError, math.copysign) # copysign should let us distinguish signs of zeros self.assertEqual(math.copysign(1., 0.), 1.) self.assertEqual(math.copysign(1., -0.), -1.) self.assertEqual(math.copysign(INF, 0.), INF) self.assertEqual(math.copysign(INF, -0.), NINF) self.assertEqual(math.copysign(NINF, 0.), INF) self.assertEqual(math.copysign(NINF, -0.), NINF) # and of infinities self.assertEqual(math.copysign(1., INF), 1.) self.assertEqual(math.copysign(1., NINF), -1.) self.assertEqual(math.copysign(INF, INF), INF) self.assertEqual(math.copysign(INF, NINF), NINF) self.assertEqual(math.copysign(NINF, INF), INF) self.assertEqual(math.copysign(NINF, NINF), NINF) self.assertTrue(math.isnan(math.copysign(NAN, 1.))) self.assertTrue(math.isnan(math.copysign(NAN, INF))) self.assertTrue(math.isnan(math.copysign(NAN, NINF))) self.assertTrue(math.isnan(math.copysign(NAN, NAN))) # copysign(INF, NAN) may be INF or it may be NINF, since # we don't know whether the sign bit of NAN is set on any # given platform. self.assertTrue(math.isinf(math.copysign(INF, NAN))) # similarly, copysign(2., NAN) could be 2. or -2. self.assertEqual(abs(math.copysign(2., NAN)), 2.) def testCos(self): self.assertRaises(TypeError, math.cos) self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0, abs_tol=ulp(1)) self.ftest('cos(0)', math.cos(0), 1) self.ftest('cos(pi/2)', math.cos(math.pi/2), 0, abs_tol=ulp(1)) self.ftest('cos(pi)', math.cos(math.pi), -1) try: self.assertTrue(math.isnan(math.cos(INF))) self.assertTrue(math.isnan(math.cos(NINF))) except ValueError: self.assertRaises(ValueError, math.cos, INF) self.assertRaises(ValueError, math.cos, NINF) self.assertTrue(math.isnan(math.cos(NAN))) def testCosh(self): self.assertRaises(TypeError, math.cosh) self.ftest('cosh(0)', math.cosh(0), 1) self.ftest('cosh(2)-2*cosh(1)**2', math.cosh(2)-2*math.cosh(1)**2, -1) # Thanks to Lambert self.assertEqual(math.cosh(INF), INF) self.assertEqual(math.cosh(NINF), INF) self.assertTrue(math.isnan(math.cosh(NAN))) def testDegrees(self): self.assertRaises(TypeError, math.degrees) self.ftest('degrees(pi)', math.degrees(math.pi), 180.0) self.ftest('degrees(pi/2)', math.degrees(math.pi/2), 90.0) self.ftest('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0) self.ftest('degrees(0)', math.degrees(0), 0) def testExp(self): self.assertRaises(TypeError, math.exp) self.ftest('exp(-1)', math.exp(-1), 1/math.e) self.ftest('exp(0)', math.exp(0), 1) self.ftest('exp(1)', math.exp(1), math.e) self.assertEqual(math.exp(INF), INF) self.assertEqual(math.exp(NINF), 0.) self.assertTrue(math.isnan(math.exp(NAN))) self.assertRaises(OverflowError, math.exp, 1000000) def testFabs(self): self.assertRaises(TypeError, math.fabs) self.ftest('fabs(-1)', math.fabs(-1), 1) self.ftest('fabs(0)', math.fabs(0), 0) self.ftest('fabs(1)', math.fabs(1), 1) def testFactorial(self): self.assertEqual(math.factorial(0), 1) self.assertEqual(math.factorial(0.0), 1) total = 1 for i in range(1, 1000): total *= i self.assertEqual(math.factorial(i), total) self.assertEqual(math.factorial(float(i)), total) self.assertEqual(math.factorial(i), py_factorial(i)) self.assertRaises(ValueError, math.factorial, -1) self.assertRaises(ValueError, math.factorial, -1.0) self.assertRaises(ValueError, math.factorial, -10**100) self.assertRaises(ValueError, math.factorial, -1e100) self.assertRaises(ValueError, math.factorial, math.pi) # Other implementations may place different upper bounds. @support.cpython_only def testFactorialHugeInputs(self): # Currently raises ValueError for inputs that are too large # to fit into a C long. self.assertRaises(OverflowError, math.factorial, 10**100) self.assertRaises(OverflowError, math.factorial, 1e100) def testFloor(self): self.assertRaises(TypeError, math.floor) self.assertEqual(int, type(math.floor(0.5))) self.ftest('floor(0.5)', math.floor(0.5), 0) self.ftest('floor(1.0)', math.floor(1.0), 1) self.ftest('floor(1.5)', math.floor(1.5), 1) self.ftest('floor(-0.5)', math.floor(-0.5), -1) self.ftest('floor(-1.0)', math.floor(-1.0), -1) self.ftest('floor(-1.5)', math.floor(-1.5), -2) # pow() relies on floor() to check for integers # This fails on some platforms - so check it here self.ftest('floor(1.23e167)', math.floor(1.23e167), 1.23e167) self.ftest('floor(-1.23e167)', math.floor(-1.23e167), -1.23e167) #self.assertEqual(math.ceil(INF), INF) #self.assertEqual(math.ceil(NINF), NINF) #self.assertTrue(math.isnan(math.floor(NAN))) class TestFloor: def __floor__(self): return 42 class TestNoFloor: pass self.ftest('floor(TestFloor())', math.floor(TestFloor()), 42) self.assertRaises(TypeError, math.floor, TestNoFloor()) t = TestNoFloor() t.__floor__ = lambda *args: args self.assertRaises(TypeError, math.floor, t) self.assertRaises(TypeError, math.floor, t, 0) def testFmod(self): self.assertRaises(TypeError, math.fmod) self.ftest('fmod(10, 1)', math.fmod(10, 1), 0.0) self.ftest('fmod(10, 0.5)', math.fmod(10, 0.5), 0.0) self.ftest('fmod(10, 1.5)', math.fmod(10, 1.5), 1.0) self.ftest('fmod(-10, 1)', math.fmod(-10, 1), -0.0) self.ftest('fmod(-10, 0.5)', math.fmod(-10, 0.5), -0.0) self.ftest('fmod(-10, 1.5)', math.fmod(-10, 1.5), -1.0) self.assertTrue(math.isnan(math.fmod(NAN, 1.))) self.assertTrue(math.isnan(math.fmod(1., NAN))) self.assertTrue(math.isnan(math.fmod(NAN, NAN))) self.assertRaises(ValueError, math.fmod, 1., 0.) self.assertRaises(ValueError, math.fmod, INF, 1.) self.assertRaises(ValueError, math.fmod, NINF, 1.) self.assertRaises(ValueError, math.fmod, INF, 0.) self.assertEqual(math.fmod(3.0, INF), 3.0) self.assertEqual(math.fmod(-3.0, INF), -3.0) self.assertEqual(math.fmod(3.0, NINF), 3.0) self.assertEqual(math.fmod(-3.0, NINF), -3.0) self.assertEqual(math.fmod(0.0, 3.0), 0.0) self.assertEqual(math.fmod(0.0, NINF), 0.0) def testFrexp(self): self.assertRaises(TypeError, math.frexp) def testfrexp(name, result, expected): (mant, exp), (emant, eexp) = result, expected if abs(mant-emant) > eps or exp != eexp: self.fail('%s returned %r, expected %r'%\ (name, result, expected)) testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1)) testfrexp('frexp(0)', math.frexp(0), (0, 0)) testfrexp('frexp(1)', math.frexp(1), (0.5, 1)) testfrexp('frexp(2)', math.frexp(2), (0.5, 2)) self.assertEqual(math.frexp(INF)[0], INF) self.assertEqual(math.frexp(NINF)[0], NINF) self.assertTrue(math.isnan(math.frexp(NAN)[0])) @requires_IEEE_754 @unittest.skipIf(HAVE_DOUBLE_ROUNDING, "fsum is not exact on machines with double rounding") def testFsum(self): # math.fsum relies on exact rounding for correct operation. # There's a known problem with IA32 floating-point that causes # inexact rounding in some situations, and will cause the # math.fsum tests below to fail; see issue #2937. On non IEEE # 754 platforms, and on IEEE 754 platforms that exhibit the # problem described in issue #2937, we simply skip the whole # test. # Python version of math.fsum, for comparison. Uses a # different algorithm based on frexp, ldexp and integer # arithmetic. from sys import float_info mant_dig = float_info.mant_dig etiny = float_info.min_exp - mant_dig def msum(iterable): """Full precision summation. Compute sum(iterable) without any intermediate accumulation of error. Based on the 'lsum' function at http://code.activestate.com/recipes/393090/ """ tmant, texp = 0, 0 for x in iterable: mant, exp = math.frexp(x) mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig if texp > exp: tmant <<= texp-exp texp = exp else: mant <<= exp-texp tmant += mant # Round tmant * 2**texp to a float. The original recipe # used float(str(tmant)) * 2.0**texp for this, but that's # a little unsafe because str -> float conversion can't be # relied upon to do correct rounding on all platforms. tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp) if tail > 0: h = 1 << (tail-1) tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1) texp += tail return math.ldexp(tmant, texp) test_values = [ ([], 0.0), ([0.0], 0.0), ([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100), ([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0), ([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0), ([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0), ([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0), ([1./n for n in range(1, 1001)], float.fromhex('0x1.df11f45f4e61ap+2')), ([(-1.)**n/n for n in range(1, 1001)], float.fromhex('-0x1.62a2af1bd3624p-1')), ([1.7**(i+1)-1.7**i for i in range(1000)] + [-1.7**1000], -1.0), ([1e16, 1., 1e-16], 10000000000000002.0), ([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0), # exercise code for resizing partials array ([2.**n - 2.**(n+50) + 2.**(n+52) for n in range(-1074, 972, 2)] + [-2.**1022], float.fromhex('0x1.5555555555555p+970')), ] for i, (vals, expected) in enumerate(test_values): try: actual = math.fsum(vals) except OverflowError: self.fail("test %d failed: got OverflowError, expected %r " "for math.fsum(%.100r)" % (i, expected, vals)) except ValueError: self.fail("test %d failed: got ValueError, expected %r " "for math.fsum(%.100r)" % (i, expected, vals)) self.assertEqual(actual, expected) from random import random, gauss, shuffle for j in range(1000): vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10 s = 0 for i in range(200): v = gauss(0, random()) ** 7 - s s += v vals.append(v) shuffle(vals) s = msum(vals) self.assertEqual(msum(vals), math.fsum(vals)) def testGcd(self): gcd = math.gcd self.assertEqual(gcd(0, 0), 0) self.assertEqual(gcd(1, 0), 1) self.assertEqual(gcd(-1, 0), 1) self.assertEqual(gcd(0, 1), 1) self.assertEqual(gcd(0, -1), 1) self.assertEqual(gcd(7, 1), 1) self.assertEqual(gcd(7, -1), 1) self.assertEqual(gcd(-23, 15), 1) self.assertEqual(gcd(120, 84), 12) self.assertEqual(gcd(84, -120), 12) self.assertEqual(gcd(1216342683557601535506311712, 436522681849110124616458784), 32) c = 652560 x = 434610456570399902378880679233098819019853229470286994367836600566 y = 1064502245825115327754847244914921553977 a = x * c b = y * c self.assertEqual(gcd(a, b), c) self.assertEqual(gcd(b, a), c) self.assertEqual(gcd(-a, b), c) self.assertEqual(gcd(b, -a), c) self.assertEqual(gcd(a, -b), c) self.assertEqual(gcd(-b, a), c) self.assertEqual(gcd(-a, -b), c) self.assertEqual(gcd(-b, -a), c) c = 576559230871654959816130551884856912003141446781646602790216406874 a = x * c b = y * c self.assertEqual(gcd(a, b), c) self.assertEqual(gcd(b, a), c) self.assertEqual(gcd(-a, b), c) self.assertEqual(gcd(b, -a), c) self.assertEqual(gcd(a, -b), c) self.assertEqual(gcd(-b, a), c) self.assertEqual(gcd(-a, -b), c) self.assertEqual(gcd(-b, -a), c) self.assertRaises(TypeError, gcd, 120.0, 84) self.assertRaises(TypeError, gcd, 120, 84.0) self.assertEqual(gcd(MyIndexable(120), MyIndexable(84)), 12) def testHypot(self): self.assertRaises(TypeError, math.hypot) self.ftest('hypot(0,0)', math.hypot(0,0), 0) self.ftest('hypot(3,4)', math.hypot(3,4), 5) self.assertEqual(math.hypot(NAN, INF), INF) self.assertEqual(math.hypot(INF, NAN), INF) self.assertEqual(math.hypot(NAN, NINF), INF) self.assertEqual(math.hypot(NINF, NAN), INF) self.assertRaises(OverflowError, math.hypot, FLOAT_MAX, FLOAT_MAX) self.assertTrue(math.isnan(math.hypot(1.0, NAN))) self.assertTrue(math.isnan(math.hypot(NAN, -2.0))) def testLdexp(self): self.assertRaises(TypeError, math.ldexp) self.ftest('ldexp(0,1)', math.ldexp(0,1), 0) self.ftest('ldexp(1,1)', math.ldexp(1,1), 2) self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5) self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2) self.assertRaises(OverflowError, math.ldexp, 1., 1000000) self.assertRaises(OverflowError, math.ldexp, -1., 1000000) self.assertEqual(math.ldexp(1., -1000000), 0.) self.assertEqual(math.ldexp(-1., -1000000), -0.) self.assertEqual(math.ldexp(INF, 30), INF) self.assertEqual(math.ldexp(NINF, -213), NINF) self.assertTrue(math.isnan(math.ldexp(NAN, 0))) # large second argument for n in [10**5, 10**10, 10**20, 10**40]: self.assertEqual(math.ldexp(INF, -n), INF) self.assertEqual(math.ldexp(NINF, -n), NINF) self.assertEqual(math.ldexp(1., -n), 0.) self.assertEqual(math.ldexp(-1., -n), -0.) self.assertEqual(math.ldexp(0., -n), 0.) self.assertEqual(math.ldexp(-0., -n), -0.) self.assertTrue(math.isnan(math.ldexp(NAN, -n))) self.assertRaises(OverflowError, math.ldexp, 1., n) self.assertRaises(OverflowError, math.ldexp, -1., n) self.assertEqual(math.ldexp(0., n), 0.) self.assertEqual(math.ldexp(-0., n), -0.) self.assertEqual(math.ldexp(INF, n), INF) self.assertEqual(math.ldexp(NINF, n), NINF) self.assertTrue(math.isnan(math.ldexp(NAN, n))) def testLog(self): self.assertRaises(TypeError, math.log) self.ftest('log(1/e)', math.log(1/math.e), -1) self.ftest('log(1)', math.log(1), 0) self.ftest('log(e)', math.log(math.e), 1) self.ftest('log(32,2)', math.log(32,2), 5) self.ftest('log(10**40, 10)', math.log(10**40, 10), 40) self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2) self.ftest('log(10**1000)', math.log(10**1000), 2302.5850929940457) self.assertRaises(ValueError, math.log, -1.5) self.assertRaises(ValueError, math.log, -10**1000) self.assertRaises(ValueError, math.log, NINF) self.assertEqual(math.log(INF), INF) self.assertTrue(math.isnan(math.log(NAN))) def testLog1p(self): self.assertRaises(TypeError, math.log1p) for n in [2, 2**90, 2**300]: self.assertAlmostEqual(math.log1p(n), math.log1p(float(n))) self.assertRaises(ValueError, math.log1p, -1) self.assertEqual(math.log1p(INF), INF) @requires_IEEE_754 def testLog2(self): self.assertRaises(TypeError, math.log2) # Check some integer values self.assertEqual(math.log2(1), 0.0) self.assertEqual(math.log2(2), 1.0) self.assertEqual(math.log2(4), 2.0) # Large integer values self.assertEqual(math.log2(2**1023), 1023.0) self.assertEqual(math.log2(2**1024), 1024.0) self.assertEqual(math.log2(2**2000), 2000.0) self.assertRaises(ValueError, math.log2, -1.5) self.assertRaises(ValueError, math.log2, NINF) self.assertTrue(math.isnan(math.log2(NAN))) @requires_IEEE_754 # log2() is not accurate enough on Mac OS X Tiger (10.4) @support.requires_mac_ver(10, 5) def testLog2Exact(self): # Check that we get exact equality for log2 of powers of 2. actual = [math.log2(math.ldexp(1.0, n)) for n in range(-1074, 1024)] expected = [float(n) for n in range(-1074, 1024)] self.assertEqual(actual, expected) def testLog10(self): self.assertRaises(TypeError, math.log10) self.ftest('log10(0.1)', math.log10(0.1), -1) self.ftest('log10(1)', math.log10(1), 0) self.ftest('log10(10)', math.log10(10), 1) self.ftest('log10(10**1000)', math.log10(10**1000), 1000.0) self.assertRaises(ValueError, math.log10, -1.5) self.assertRaises(ValueError, math.log10, -10**1000) self.assertRaises(ValueError, math.log10, NINF) self.assertEqual(math.log(INF), INF) self.assertTrue(math.isnan(math.log10(NAN))) def testModf(self): self.assertRaises(TypeError, math.modf) def testmodf(name, result, expected): (v1, v2), (e1, e2) = result, expected if abs(v1-e1) > eps or abs(v2-e2): self.fail('%s returned %r, expected %r'%\ (name, result, expected)) testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0)) testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0)) self.assertEqual(math.modf(INF), (0.0, INF)) self.assertEqual(math.modf(NINF), (-0.0, NINF)) modf_nan = math.modf(NAN) self.assertTrue(math.isnan(modf_nan[0])) self.assertTrue(math.isnan(modf_nan[1])) def testPow(self): self.assertRaises(TypeError, math.pow) self.ftest('pow(0,1)', math.pow(0,1), 0) self.ftest('pow(1,0)', math.pow(1,0), 1) self.ftest('pow(2,1)', math.pow(2,1), 2) self.ftest('pow(2,-1)', math.pow(2,-1), 0.5) self.assertEqual(math.pow(INF, 1), INF) self.assertEqual(math.pow(NINF, 1), NINF) self.assertEqual((math.pow(1, INF)), 1.) self.assertEqual((math.pow(1, NINF)), 1.) self.assertTrue(math.isnan(math.pow(NAN, 1))) self.assertTrue(math.isnan(math.pow(2, NAN))) self.assertTrue(math.isnan(math.pow(0, NAN))) self.assertEqual(math.pow(1, NAN), 1) # pow(0., x) self.assertEqual(math.pow(0., INF), 0.) self.assertEqual(math.pow(0., 3.), 0.) self.assertEqual(math.pow(0., 2.3), 0.) self.assertEqual(math.pow(0., 2.), 0.) self.assertEqual(math.pow(0., 0.), 1.) self.assertEqual(math.pow(0., -0.), 1.) self.assertRaises(ValueError, math.pow, 0., -2.) self.assertRaises(ValueError, math.pow, 0., -2.3) self.assertRaises(ValueError, math.pow, 0., -3.) self.assertRaises(ValueError, math.pow, 0., NINF) self.assertTrue(math.isnan(math.pow(0., NAN))) # pow(INF, x) self.assertEqual(math.pow(INF, INF), INF) self.assertEqual(math.pow(INF, 3.), INF) self.assertEqual(math.pow(INF, 2.3), INF) self.assertEqual(math.pow(INF, 2.), INF) self.assertEqual(math.pow(INF, 0.), 1.) self.assertEqual(math.pow(INF, -0.), 1.) self.assertEqual(math.pow(INF, -2.), 0.) self.assertEqual(math.pow(INF, -2.3), 0.) self.assertEqual(math.pow(INF, -3.), 0.) self.assertEqual(math.pow(INF, NINF), 0.) self.assertTrue(math.isnan(math.pow(INF, NAN))) # pow(-0., x) self.assertEqual(math.pow(-0., INF), 0.) self.assertEqual(math.pow(-0., 3.), -0.) self.assertEqual(math.pow(-0., 2.3), 0.) self.assertEqual(math.pow(-0., 2.), 0.) self.assertEqual(math.pow(-0., 0.), 1.) self.assertEqual(math.pow(-0., -0.), 1.) self.assertRaises(ValueError, math.pow, -0., -2.) self.assertRaises(ValueError, math.pow, -0., -2.3) self.assertRaises(ValueError, math.pow, -0., -3.) self.assertRaises(ValueError, math.pow, -0., NINF) self.assertTrue(math.isnan(math.pow(-0., NAN))) # pow(NINF, x) self.assertEqual(math.pow(NINF, INF), INF) self.assertEqual(math.pow(NINF, 3.), NINF) self.assertEqual(math.pow(NINF, 2.3), INF) self.assertEqual(math.pow(NINF, 2.), INF) self.assertEqual(math.pow(NINF, 0.), 1.) self.assertEqual(math.pow(NINF, -0.), 1.) self.assertEqual(math.pow(NINF, -2.), 0.) self.assertEqual(math.pow(NINF, -2.3), 0.) self.assertEqual(math.pow(NINF, -3.), -0.) self.assertEqual(math.pow(NINF, NINF), 0.) self.assertTrue(math.isnan(math.pow(NINF, NAN))) # pow(-1, x) self.assertEqual(math.pow(-1., INF), 1.) self.assertEqual(math.pow(-1., 3.), -1.) self.assertRaises(ValueError, math.pow, -1., 2.3) self.assertEqual(math.pow(-1., 2.), 1.) self.assertEqual(math.pow(-1., 0.), 1.) self.assertEqual(math.pow(-1., -0.), 1.) self.assertEqual(math.pow(-1., -2.), 1.) self.assertRaises(ValueError, math.pow, -1., -2.3) self.assertEqual(math.pow(-1., -3.), -1.) self.assertEqual(math.pow(-1., NINF), 1.) self.assertTrue(math.isnan(math.pow(-1., NAN))) # pow(1, x) self.assertEqual(math.pow(1., INF), 1.) self.assertEqual(math.pow(1., 3.), 1.) self.assertEqual(math.pow(1., 2.3), 1.) self.assertEqual(math.pow(1., 2.), 1.) self.assertEqual(math.pow(1., 0.), 1.) self.assertEqual(math.pow(1., -0.), 1.) self.assertEqual(math.pow(1., -2.), 1.) self.assertEqual(math.pow(1., -2.3), 1.) self.assertEqual(math.pow(1., -3.), 1.) self.assertEqual(math.pow(1., NINF), 1.) self.assertEqual(math.pow(1., NAN), 1.) # pow(x, 0) should be 1 for any x self.assertEqual(math.pow(2.3, 0.), 1.) self.assertEqual(math.pow(-2.3, 0.), 1.) self.assertEqual(math.pow(NAN, 0.), 1.) self.assertEqual(math.pow(2.3, -0.), 1.) self.assertEqual(math.pow(-2.3, -0.), 1.) self.assertEqual(math.pow(NAN, -0.), 1.) # pow(x, y) is invalid if x is negative and y is not integral self.assertRaises(ValueError, math.pow, -1., 2.3) self.assertRaises(ValueError, math.pow, -15., -3.1) # pow(x, NINF) self.assertEqual(math.pow(1.9, NINF), 0.) self.assertEqual(math.pow(1.1, NINF), 0.) self.assertEqual(math.pow(0.9, NINF), INF) self.assertEqual(math.pow(0.1, NINF), INF) self.assertEqual(math.pow(-0.1, NINF), INF) self.assertEqual(math.pow(-0.9, NINF), INF) self.assertEqual(math.pow(-1.1, NINF), 0.) self.assertEqual(math.pow(-1.9, NINF), 0.) # pow(x, INF) self.assertEqual(math.pow(1.9, INF), INF) self.assertEqual(math.pow(1.1, INF), INF) self.assertEqual(math.pow(0.9, INF), 0.) self.assertEqual(math.pow(0.1, INF), 0.) self.assertEqual(math.pow(-0.1, INF), 0.) self.assertEqual(math.pow(-0.9, INF), 0.) self.assertEqual(math.pow(-1.1, INF), INF) self.assertEqual(math.pow(-1.9, INF), INF) # pow(x, y) should work for x negative, y an integer self.ftest('(-2.)**3.', math.pow(-2.0, 3.0), -8.0) self.ftest('(-2.)**2.', math.pow(-2.0, 2.0), 4.0) self.ftest('(-2.)**1.', math.pow(-2.0, 1.0), -2.0) self.ftest('(-2.)**0.', math.pow(-2.0, 0.0), 1.0) self.ftest('(-2.)**-0.', math.pow(-2.0, -0.0), 1.0) self.ftest('(-2.)**-1.', math.pow(-2.0, -1.0), -0.5) self.ftest('(-2.)**-2.', math.pow(-2.0, -2.0), 0.25) self.ftest('(-2.)**-3.', math.pow(-2.0, -3.0), -0.125) self.assertRaises(ValueError, math.pow, -2.0, -0.5) self.assertRaises(ValueError, math.pow, -2.0, 0.5) # the following tests have been commented out since they don't # really belong here: the implementation of ** for floats is # independent of the implementation of math.pow #self.assertEqual(1**NAN, 1) #self.assertEqual(1**INF, 1) #self.assertEqual(1**NINF, 1) #self.assertEqual(1**0, 1) #self.assertEqual(1.**NAN, 1) #self.assertEqual(1.**INF, 1) #self.assertEqual(1.**NINF, 1) #self.assertEqual(1.**0, 1) def testRadians(self): self.assertRaises(TypeError, math.radians) self.ftest('radians(180)', math.radians(180), math.pi) self.ftest('radians(90)', math.radians(90), math.pi/2) self.ftest('radians(-45)', math.radians(-45), -math.pi/4) self.ftest('radians(0)', math.radians(0), 0) @requires_IEEE_754 def testRemainder(self): from fractions import Fraction def validate_spec(x, y, r): """ Check that r matches remainder(x, y) according to the IEEE 754 specification. Assumes that x, y and r are finite and y is nonzero. """ fx, fy, fr = Fraction(x), Fraction(y), Fraction(r) # r should not exceed y/2 in absolute value self.assertLessEqual(abs(fr), abs(fy/2)) # x - r should be an exact integer multiple of y n = (fx - fr) / fy self.assertEqual(n, int(n)) if abs(fr) == abs(fy/2): # If |r| == |y/2|, n should be even. self.assertEqual(n/2, int(n/2)) # triples (x, y, remainder(x, y)) in hexadecimal form. testcases = [ # Remainders modulo 1, showing the ties-to-even behaviour. '-4.0 1 -0.0', '-3.8 1 0.8', '-3.0 1 -0.0', '-2.8 1 -0.8', '-2.0 1 -0.0', '-1.8 1 0.8', '-1.0 1 -0.0', '-0.8 1 -0.8', '-0.0 1 -0.0', ' 0.0 1 0.0', ' 0.8 1 0.8', ' 1.0 1 0.0', ' 1.8 1 -0.8', ' 2.0 1 0.0', ' 2.8 1 0.8', ' 3.0 1 0.0', ' 3.8 1 -0.8', ' 4.0 1 0.0', # Reductions modulo 2*pi '0x0.0p+0 0x1.921fb54442d18p+2 0x0.0p+0', '0x1.921fb54442d18p+0 0x1.921fb54442d18p+2 0x1.921fb54442d18p+0', '0x1.921fb54442d17p+1 0x1.921fb54442d18p+2 0x1.921fb54442d17p+1', '0x1.921fb54442d18p+1 0x1.921fb54442d18p+2 0x1.921fb54442d18p+1', '0x1.921fb54442d19p+1 0x1.921fb54442d18p+2 -0x1.921fb54442d17p+1', '0x1.921fb54442d17p+2 0x1.921fb54442d18p+2 -0x0.0000000000001p+2', '0x1.921fb54442d18p+2 0x1.921fb54442d18p+2 0x0p0', '0x1.921fb54442d19p+2 0x1.921fb54442d18p+2 0x0.0000000000001p+2', '0x1.2d97c7f3321d1p+3 0x1.921fb54442d18p+2 0x1.921fb54442d14p+1', '0x1.2d97c7f3321d2p+3 0x1.921fb54442d18p+2 -0x1.921fb54442d18p+1', '0x1.2d97c7f3321d3p+3 0x1.921fb54442d18p+2 -0x1.921fb54442d14p+1', '0x1.921fb54442d17p+3 0x1.921fb54442d18p+2 -0x0.0000000000001p+3', '0x1.921fb54442d18p+3 0x1.921fb54442d18p+2 0x0p0', '0x1.921fb54442d19p+3 0x1.921fb54442d18p+2 0x0.0000000000001p+3', '0x1.f6a7a2955385dp+3 0x1.921fb54442d18p+2 0x1.921fb54442d14p+1', '0x1.f6a7a2955385ep+3 0x1.921fb54442d18p+2 0x1.921fb54442d18p+1', '0x1.f6a7a2955385fp+3 0x1.921fb54442d18p+2 -0x1.921fb54442d14p+1', '0x1.1475cc9eedf00p+5 0x1.921fb54442d18p+2 0x1.921fb54442d10p+1', '0x1.1475cc9eedf01p+5 0x1.921fb54442d18p+2 -0x1.921fb54442d10p+1', # Symmetry with respect to signs. ' 1 0.c 0.4', '-1 0.c -0.4', ' 1 -0.c 0.4', '-1 -0.c -0.4', ' 1.4 0.c -0.4', '-1.4 0.c 0.4', ' 1.4 -0.c -0.4', '-1.4 -0.c 0.4', # Huge modulus, to check that the underlying algorithm doesn't # rely on 2.0 * modulus being representable. '0x1.dp+1023 0x1.4p+1023 0x0.9p+1023', '0x1.ep+1023 0x1.4p+1023 -0x0.ap+1023', '0x1.fp+1023 0x1.4p+1023 -0x0.9p+1023', ] for case in testcases: with self.subTest(case=case): x_hex, y_hex, expected_hex = case.split() x = float.fromhex(x_hex) y = float.fromhex(y_hex) expected = float.fromhex(expected_hex) validate_spec(x, y, expected) actual = math.remainder(x, y) # Cheap way of checking that the floats are # as identical as we need them to be. self.assertEqual(actual.hex(), expected.hex()) # Test tiny subnormal modulus: there's potential for # getting the implementation wrong here (for example, # by assuming that modulus/2 is exactly representable). tiny = float.fromhex('1p-1074') # min +ve subnormal for n in range(-25, 25): if n == 0: continue y = n * tiny for m in range(100): x = m * tiny actual = math.remainder(x, y) validate_spec(x, y, actual) actual = math.remainder(-x, y) validate_spec(-x, y, actual) # Special values. # NaNs should propagate as usual. for value in [NAN, 0.0, -0.0, 2.0, -2.3, NINF, INF]: self.assertIsNaN(math.remainder(NAN, value)) self.assertIsNaN(math.remainder(value, NAN)) # remainder(x, inf) is x, for non-nan non-infinite x. for value in [-2.3, -0.0, 0.0, 2.3]: self.assertEqual(math.remainder(value, INF), value) self.assertEqual(math.remainder(value, NINF), value) # remainder(x, 0) and remainder(infinity, x) for non-NaN x are invalid # operations according to IEEE 754-2008 7.2(f), and should raise. for value in [NINF, -2.3, -0.0, 0.0, 2.3, INF]: with self.assertRaises(ValueError): math.remainder(INF, value) with self.assertRaises(ValueError): math.remainder(NINF, value) with self.assertRaises(ValueError): math.remainder(value, 0.0) with self.assertRaises(ValueError): math.remainder(value, -0.0) def testSin(self): self.assertRaises(TypeError, math.sin) self.ftest('sin(0)', math.sin(0), 0) self.ftest('sin(pi/2)', math.sin(math.pi/2), 1) self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1) try: self.assertTrue(math.isnan(math.sin(INF))) self.assertTrue(math.isnan(math.sin(NINF))) except ValueError: self.assertRaises(ValueError, math.sin, INF) self.assertRaises(ValueError, math.sin, NINF) self.assertTrue(math.isnan(math.sin(NAN))) def testSinh(self): self.assertRaises(TypeError, math.sinh) self.ftest('sinh(0)', math.sinh(0), 0) self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1) self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0) self.assertEqual(math.sinh(INF), INF) self.assertEqual(math.sinh(NINF), NINF) self.assertTrue(math.isnan(math.sinh(NAN))) def testSqrt(self): self.assertRaises(TypeError, math.sqrt) self.ftest('sqrt(0)', math.sqrt(0), 0) self.ftest('sqrt(1)', math.sqrt(1), 1) self.ftest('sqrt(4)', math.sqrt(4), 2) self.assertEqual(math.sqrt(INF), INF) self.assertRaises(ValueError, math.sqrt, -1) self.assertRaises(ValueError, math.sqrt, NINF) self.assertTrue(math.isnan(math.sqrt(NAN))) def testTan(self): self.assertRaises(TypeError, math.tan) self.ftest('tan(0)', math.tan(0), 0) self.ftest('tan(pi/4)', math.tan(math.pi/4), 1) self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1) try: self.assertTrue(math.isnan(math.tan(INF))) self.assertTrue(math.isnan(math.tan(NINF))) except: self.assertRaises(ValueError, math.tan, INF) self.assertRaises(ValueError, math.tan, NINF) self.assertTrue(math.isnan(math.tan(NAN))) def testTanh(self): self.assertRaises(TypeError, math.tanh) self.ftest('tanh(0)', math.tanh(0), 0) self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0, abs_tol=ulp(1)) self.ftest('tanh(inf)', math.tanh(INF), 1) self.ftest('tanh(-inf)', math.tanh(NINF), -1) self.assertTrue(math.isnan(math.tanh(NAN))) @requires_IEEE_754 @unittest.skipIf(sysconfig.get_config_var('TANH_PRESERVES_ZERO_SIGN') == 0, "system tanh() function doesn't copy the sign") def testTanhSign(self): # check that tanh(-0.) == -0. on IEEE 754 systems self.assertEqual(math.tanh(-0.), -0.) self.assertEqual(math.copysign(1., math.tanh(-0.)), math.copysign(1., -0.)) def test_trunc(self): self.assertEqual(math.trunc(1), 1) self.assertEqual(math.trunc(-1), -1) self.assertEqual(type(math.trunc(1)), int) self.assertEqual(type(math.trunc(1.5)), int) self.assertEqual(math.trunc(1.5), 1) self.assertEqual(math.trunc(-1.5), -1) self.assertEqual(math.trunc(1.999999), 1) self.assertEqual(math.trunc(-1.999999), -1) self.assertEqual(math.trunc(-0.999999), -0) self.assertEqual(math.trunc(-100.999), -100) class TestTrunc(object): def __trunc__(self): return 23 class TestNoTrunc(object): pass self.assertEqual(math.trunc(TestTrunc()), 23) self.assertRaises(TypeError, math.trunc) self.assertRaises(TypeError, math.trunc, 1, 2) self.assertRaises(TypeError, math.trunc, TestNoTrunc()) def testIsfinite(self): self.assertTrue(math.isfinite(0.0)) self.assertTrue(math.isfinite(-0.0)) self.assertTrue(math.isfinite(1.0)) self.assertTrue(math.isfinite(-1.0)) self.assertFalse(math.isfinite(float("nan"))) self.assertFalse(math.isfinite(float("inf"))) self.assertFalse(math.isfinite(float("-inf"))) def testIsnan(self): self.assertTrue(math.isnan(float("nan"))) self.assertTrue(math.isnan(float("-nan"))) self.assertTrue(math.isnan(float("inf") * 0.)) self.assertFalse(math.isnan(float("inf"))) self.assertFalse(math.isnan(0.)) self.assertFalse(math.isnan(1.)) def testIsinf(self): self.assertTrue(math.isinf(float("inf"))) self.assertTrue(math.isinf(float("-inf"))) self.assertTrue(math.isinf(1E400)) self.assertTrue(math.isinf(-1E400)) self.assertFalse(math.isinf(float("nan"))) self.assertFalse(math.isinf(0.)) self.assertFalse(math.isinf(1.)) @requires_IEEE_754 def test_nan_constant(self): self.assertTrue(math.isnan(math.nan)) @requires_IEEE_754 def test_inf_constant(self): self.assertTrue(math.isinf(math.inf)) self.assertGreater(math.inf, 0.0) self.assertEqual(math.inf, float("inf")) self.assertEqual(-math.inf, float("-inf")) # RED_FLAG 16-Oct-2000 Tim # While 2.0 is more consistent about exceptions than previous releases, it # still fails this part of the test on some platforms. For now, we only # *run* test_exceptions() in verbose mode, so that this isn't normally # tested. @unittest.skipUnless(verbose, 'requires verbose mode') def test_exceptions(self): try: x = math.exp(-1000000000) except: # mathmodule.c is failing to weed out underflows from libm, or # we've got an fp format with huge dynamic range self.fail("underflowing exp() should not have raised " "an exception") if x != 0: self.fail("underflowing exp() should have returned 0") # If this fails, probably using a strict IEEE-754 conforming libm, and x # is +Inf afterwards. But Python wants overflows detected by default. try: x = math.exp(1000000000) except OverflowError: pass else: self.fail("overflowing exp() didn't trigger OverflowError") # If this fails, it could be a puzzle. One odd possibility is that # mathmodule.c's macros are getting confused while comparing # Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE # as a result (and so raising OverflowError instead). try: x = math.sqrt(-1.0) except ValueError: pass else: self.fail("sqrt(-1) didn't raise ValueError") @requires_IEEE_754 def test_testfile(self): # Some tests need to be skipped on ancient OS X versions. # See issue #27953. SKIP_ON_TIGER = {'tan0064'} osx_version = None if sys.platform == 'darwin': version_txt = platform.mac_ver()[0] try: osx_version = tuple(map(int, version_txt.split('.'))) except ValueError: pass fail_fmt = "{}: {}({!r}): {}" failures = [] for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file): # Skip if either the input or result is complex if ai != 0.0 or ei != 0.0: continue if fn in ['rect', 'polar']: # no real versions of rect, polar continue # Skip certain tests on OS X 10.4. if osx_version is not None and osx_version < (10, 5): if id in SKIP_ON_TIGER: continue func = getattr(math, fn) if 'invalid' in flags or 'divide-by-zero' in flags: er = 'ValueError' elif 'overflow' in flags: er = 'OverflowError' try: result = func(ar) except ValueError: result = 'ValueError' except OverflowError: result = 'OverflowError' # Default tolerances ulp_tol, abs_tol = 5, 0.0 failure = result_check(er, result, ulp_tol, abs_tol) if failure is None: continue msg = fail_fmt.format(id, fn, ar, failure) failures.append(msg) if failures: self.fail('Failures in test_testfile:\n ' + '\n '.join(failures)) @requires_IEEE_754 def test_mtestfile(self): fail_fmt = "{}: {}({!r}): {}" failures = [] for id, fn, arg, expected, flags in parse_mtestfile(math_testcases): func = getattr(math, fn) if 'invalid' in flags or 'divide-by-zero' in flags: expected = 'ValueError' elif 'overflow' in flags: expected = 'OverflowError' try: got = func(arg) except ValueError: got = 'ValueError' except OverflowError: got = 'OverflowError' # Default tolerances ulp_tol, abs_tol = 5, 0.0 # Exceptions to the defaults if fn == 'gamma': # Experimental results on one platform gave # an accuracy of <= 10 ulps across the entire float # domain. We weaken that to require 20 ulp accuracy. ulp_tol = 20 elif fn == 'lgamma': # we use a weaker accuracy test for lgamma; # lgamma only achieves an absolute error of # a few multiples of the machine accuracy, in # general. abs_tol = 1e-15 elif fn == 'erfc' and arg >= 0.0: # erfc has less-than-ideal accuracy for large # arguments (x ~ 25 or so), mainly due to the # error involved in computing exp(-x*x). # # Observed between CPython and mpmath at 25 dp: # x < 0 : err <= 2 ulp # 0 <= x < 1 : err <= 10 ulp # 1 <= x < 10 : err <= 100 ulp # 10 <= x < 20 : err <= 300 ulp # 20 <= x : < 600 ulp # if arg < 1.0: ulp_tol = 10 elif arg < 10.0: ulp_tol = 100 else: ulp_tol = 1000 failure = result_check(expected, got, ulp_tol, abs_tol) if failure is None: continue msg = fail_fmt.format(id, fn, arg, failure) failures.append(msg) if failures: self.fail('Failures in test_mtestfile:\n ' + '\n '.join(failures)) # Custom assertions. def assertIsNaN(self, value): if not math.isnan(value): self.fail("Expected a NaN, got {!r}.".format(value)) class IsCloseTests(unittest.TestCase): isclose = math.isclose # subclasses should override this def assertIsClose(self, a, b, *args, **kwargs): self.assertTrue(self.isclose(a, b, *args, **kwargs), msg="%s and %s should be close!" % (a, b)) def assertIsNotClose(self, a, b, *args, **kwargs): self.assertFalse(self.isclose(a, b, *args, **kwargs), msg="%s and %s should not be close!" % (a, b)) def assertAllClose(self, examples, *args, **kwargs): for a, b in examples: self.assertIsClose(a, b, *args, **kwargs) def assertAllNotClose(self, examples, *args, **kwargs): for a, b in examples: self.assertIsNotClose(a, b, *args, **kwargs) def test_negative_tolerances(self): # ValueError should be raised if either tolerance is less than zero with self.assertRaises(ValueError): self.assertIsClose(1, 1, rel_tol=-1e-100) with self.assertRaises(ValueError): self.assertIsClose(1, 1, rel_tol=1e-100, abs_tol=-1e10) def test_identical(self): # identical values must test as close identical_examples = [(2.0, 2.0), (0.1e200, 0.1e200), (1.123e-300, 1.123e-300), (12345, 12345.0), (0.0, -0.0), (345678, 345678)] self.assertAllClose(identical_examples, rel_tol=0.0, abs_tol=0.0) def test_eight_decimal_places(self): # examples that are close to 1e-8, but not 1e-9 eight_decimal_places_examples = [(1e8, 1e8 + 1), (-1e-8, -1.000000009e-8), (1.12345678, 1.12345679)] self.assertAllClose(eight_decimal_places_examples, rel_tol=1e-8) self.assertAllNotClose(eight_decimal_places_examples, rel_tol=1e-9) def test_near_zero(self): # values close to zero near_zero_examples = [(1e-9, 0.0), (-1e-9, 0.0), (-1e-150, 0.0)] # these should not be close to any rel_tol self.assertAllNotClose(near_zero_examples, rel_tol=0.9) # these should be close to abs_tol=1e-8 self.assertAllClose(near_zero_examples, abs_tol=1e-8) def test_identical_infinite(self): # these are close regardless of tolerance -- i.e. they are equal self.assertIsClose(INF, INF) self.assertIsClose(INF, INF, abs_tol=0.0) self.assertIsClose(NINF, NINF) self.assertIsClose(NINF, NINF, abs_tol=0.0) def test_inf_ninf_nan(self): # these should never be close (following IEEE 754 rules for equality) not_close_examples = [(NAN, NAN), (NAN, 1e-100), (1e-100, NAN), (INF, NAN), (NAN, INF), (INF, NINF), (INF, 1.0), (1.0, INF), (INF, 1e308), (1e308, INF)] # use largest reasonable tolerance self.assertAllNotClose(not_close_examples, abs_tol=0.999999999999999) def test_zero_tolerance(self): # test with zero tolerance zero_tolerance_close_examples = [(1.0, 1.0), (-3.4, -3.4), (-1e-300, -1e-300)] self.assertAllClose(zero_tolerance_close_examples, rel_tol=0.0) zero_tolerance_not_close_examples = [(1.0, 1.000000000000001), (0.99999999999999, 1.0), (1.0e200, .999999999999999e200)] self.assertAllNotClose(zero_tolerance_not_close_examples, rel_tol=0.0) def test_asymmetry(self): # test the asymmetry example from PEP 485 self.assertAllClose([(9, 10), (10, 9)], rel_tol=0.1) def test_integers(self): # test with integer values integer_examples = [(100000001, 100000000), (123456789, 123456788)] self.assertAllClose(integer_examples, rel_tol=1e-8) self.assertAllNotClose(integer_examples, rel_tol=1e-9) def test_decimals(self): # test with Decimal values from decimal import Decimal decimal_examples = [(Decimal('1.00000001'), Decimal('1.0')), (Decimal('1.00000001e-20'), Decimal('1.0e-20')), (Decimal('1.00000001e-100'), Decimal('1.0e-100')), (Decimal('1.00000001e20'), Decimal('1.0e20'))] self.assertAllClose(decimal_examples, rel_tol=1e-8) self.assertAllNotClose(decimal_examples, rel_tol=1e-9) def test_fractions(self): # test with Fraction values from fractions import Fraction fraction_examples = [ (Fraction(1, 100000000) + 1, Fraction(1)), (Fraction(100000001), Fraction(100000000)), (Fraction(10**8 + 1, 10**28), Fraction(1, 10**20))] self.assertAllClose(fraction_examples, rel_tol=1e-8) self.assertAllNotClose(fraction_examples, rel_tol=1e-9) def test_main(): from doctest import DocFileSuite suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(MathTests)) suite.addTest(unittest.makeSuite(IsCloseTests)) suite.addTest(DocFileSuite("ieee754.txt")) run_unittest(suite) if __name__ == '__main__': test_main()