1 | n/a | # |
---|
2 | n/a | # Copyright (c) 2008-2012 Stefan Krah. All rights reserved. |
---|
3 | n/a | # |
---|
4 | n/a | # Redistribution and use in source and binary forms, with or without |
---|
5 | n/a | # modification, are permitted provided that the following conditions |
---|
6 | n/a | # are met: |
---|
7 | n/a | # |
---|
8 | n/a | # 1. Redistributions of source code must retain the above copyright |
---|
9 | n/a | # notice, this list of conditions and the following disclaimer. |
---|
10 | n/a | # |
---|
11 | n/a | # 2. Redistributions in binary form must reproduce the above copyright |
---|
12 | n/a | # notice, this list of conditions and the following disclaimer in the |
---|
13 | n/a | # documentation and/or other materials provided with the distribution. |
---|
14 | n/a | # |
---|
15 | n/a | # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND |
---|
16 | n/a | # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
---|
17 | n/a | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
---|
18 | n/a | # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE |
---|
19 | n/a | # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
---|
20 | n/a | # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS |
---|
21 | n/a | # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) |
---|
22 | n/a | # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
---|
23 | n/a | # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
---|
24 | n/a | # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF |
---|
25 | n/a | # SUCH DAMAGE. |
---|
26 | n/a | # |
---|
27 | n/a | |
---|
28 | n/a | # |
---|
29 | n/a | # Usage: python deccheck.py [--short|--medium|--long|--all] |
---|
30 | n/a | # |
---|
31 | n/a | |
---|
32 | n/a | import sys, random |
---|
33 | n/a | from copy import copy |
---|
34 | n/a | from collections import defaultdict |
---|
35 | n/a | from test.support import import_fresh_module |
---|
36 | n/a | from randdec import randfloat, all_unary, all_binary, all_ternary |
---|
37 | n/a | from randdec import unary_optarg, binary_optarg, ternary_optarg |
---|
38 | n/a | from formathelper import rand_format, rand_locale |
---|
39 | n/a | from _pydecimal import _dec_from_triple |
---|
40 | n/a | |
---|
41 | n/a | C = import_fresh_module('decimal', fresh=['_decimal']) |
---|
42 | n/a | P = import_fresh_module('decimal', blocked=['_decimal']) |
---|
43 | n/a | EXIT_STATUS = 0 |
---|
44 | n/a | |
---|
45 | n/a | |
---|
46 | n/a | # Contains all categories of Decimal methods. |
---|
47 | n/a | Functions = { |
---|
48 | n/a | # Plain unary: |
---|
49 | n/a | 'unary': ( |
---|
50 | n/a | '__abs__', '__bool__', '__ceil__', '__complex__', '__copy__', |
---|
51 | n/a | '__floor__', '__float__', '__hash__', '__int__', '__neg__', |
---|
52 | n/a | '__pos__', '__reduce__', '__repr__', '__str__', '__trunc__', |
---|
53 | n/a | 'adjusted', 'as_integer_ratio', 'as_tuple', 'canonical', 'conjugate', |
---|
54 | n/a | 'copy_abs', 'copy_negate', 'is_canonical', 'is_finite', 'is_infinite', |
---|
55 | n/a | 'is_nan', 'is_qnan', 'is_signed', 'is_snan', 'is_zero', 'radix' |
---|
56 | n/a | ), |
---|
57 | n/a | # Unary with optional context: |
---|
58 | n/a | 'unary_ctx': ( |
---|
59 | n/a | 'exp', 'is_normal', 'is_subnormal', 'ln', 'log10', 'logb', |
---|
60 | n/a | 'logical_invert', 'next_minus', 'next_plus', 'normalize', |
---|
61 | n/a | 'number_class', 'sqrt', 'to_eng_string' |
---|
62 | n/a | ), |
---|
63 | n/a | # Unary with optional rounding mode and context: |
---|
64 | n/a | 'unary_rnd_ctx': ('to_integral', 'to_integral_exact', 'to_integral_value'), |
---|
65 | n/a | # Plain binary: |
---|
66 | n/a | 'binary': ( |
---|
67 | n/a | '__add__', '__divmod__', '__eq__', '__floordiv__', '__ge__', '__gt__', |
---|
68 | n/a | '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__pow__', |
---|
69 | n/a | '__radd__', '__rdivmod__', '__rfloordiv__', '__rmod__', '__rmul__', |
---|
70 | n/a | '__rpow__', '__rsub__', '__rtruediv__', '__sub__', '__truediv__', |
---|
71 | n/a | 'compare_total', 'compare_total_mag', 'copy_sign', 'quantize', |
---|
72 | n/a | 'same_quantum' |
---|
73 | n/a | ), |
---|
74 | n/a | # Binary with optional context: |
---|
75 | n/a | 'binary_ctx': ( |
---|
76 | n/a | 'compare', 'compare_signal', 'logical_and', 'logical_or', 'logical_xor', |
---|
77 | n/a | 'max', 'max_mag', 'min', 'min_mag', 'next_toward', 'remainder_near', |
---|
78 | n/a | 'rotate', 'scaleb', 'shift' |
---|
79 | n/a | ), |
---|
80 | n/a | # Plain ternary: |
---|
81 | n/a | 'ternary': ('__pow__',), |
---|
82 | n/a | # Ternary with optional context: |
---|
83 | n/a | 'ternary_ctx': ('fma',), |
---|
84 | n/a | # Special: |
---|
85 | n/a | 'special': ('__format__', '__reduce_ex__', '__round__', 'from_float', |
---|
86 | n/a | 'quantize'), |
---|
87 | n/a | # Properties: |
---|
88 | n/a | 'property': ('real', 'imag') |
---|
89 | n/a | } |
---|
90 | n/a | |
---|
91 | n/a | # Contains all categories of Context methods. The n-ary classification |
---|
92 | n/a | # applies to the number of Decimal arguments. |
---|
93 | n/a | ContextFunctions = { |
---|
94 | n/a | # Plain nullary: |
---|
95 | n/a | 'nullary': ('context.__hash__', 'context.__reduce__', 'context.radix'), |
---|
96 | n/a | # Plain unary: |
---|
97 | n/a | 'unary': ('context.abs', 'context.canonical', 'context.copy_abs', |
---|
98 | n/a | 'context.copy_decimal', 'context.copy_negate', |
---|
99 | n/a | 'context.create_decimal', 'context.exp', 'context.is_canonical', |
---|
100 | n/a | 'context.is_finite', 'context.is_infinite', 'context.is_nan', |
---|
101 | n/a | 'context.is_normal', 'context.is_qnan', 'context.is_signed', |
---|
102 | n/a | 'context.is_snan', 'context.is_subnormal', 'context.is_zero', |
---|
103 | n/a | 'context.ln', 'context.log10', 'context.logb', |
---|
104 | n/a | 'context.logical_invert', 'context.minus', 'context.next_minus', |
---|
105 | n/a | 'context.next_plus', 'context.normalize', 'context.number_class', |
---|
106 | n/a | 'context.plus', 'context.sqrt', 'context.to_eng_string', |
---|
107 | n/a | 'context.to_integral', 'context.to_integral_exact', |
---|
108 | n/a | 'context.to_integral_value', 'context.to_sci_string' |
---|
109 | n/a | ), |
---|
110 | n/a | # Plain binary: |
---|
111 | n/a | 'binary': ('context.add', 'context.compare', 'context.compare_signal', |
---|
112 | n/a | 'context.compare_total', 'context.compare_total_mag', |
---|
113 | n/a | 'context.copy_sign', 'context.divide', 'context.divide_int', |
---|
114 | n/a | 'context.divmod', 'context.logical_and', 'context.logical_or', |
---|
115 | n/a | 'context.logical_xor', 'context.max', 'context.max_mag', |
---|
116 | n/a | 'context.min', 'context.min_mag', 'context.multiply', |
---|
117 | n/a | 'context.next_toward', 'context.power', 'context.quantize', |
---|
118 | n/a | 'context.remainder', 'context.remainder_near', 'context.rotate', |
---|
119 | n/a | 'context.same_quantum', 'context.scaleb', 'context.shift', |
---|
120 | n/a | 'context.subtract' |
---|
121 | n/a | ), |
---|
122 | n/a | # Plain ternary: |
---|
123 | n/a | 'ternary': ('context.fma', 'context.power'), |
---|
124 | n/a | # Special: |
---|
125 | n/a | 'special': ('context.__reduce_ex__', 'context.create_decimal_from_float') |
---|
126 | n/a | } |
---|
127 | n/a | |
---|
128 | n/a | # Functions that require a restricted exponent range for reasonable runtimes. |
---|
129 | n/a | UnaryRestricted = [ |
---|
130 | n/a | '__ceil__', '__floor__', '__int__', '__trunc__', |
---|
131 | n/a | 'as_integer_ratio', 'to_integral', 'to_integral_value' |
---|
132 | n/a | ] |
---|
133 | n/a | |
---|
134 | n/a | BinaryRestricted = ['__round__'] |
---|
135 | n/a | |
---|
136 | n/a | TernaryRestricted = ['__pow__', 'context.power'] |
---|
137 | n/a | |
---|
138 | n/a | |
---|
139 | n/a | # ====================================================================== |
---|
140 | n/a | # Unified Context |
---|
141 | n/a | # ====================================================================== |
---|
142 | n/a | |
---|
143 | n/a | # Translate symbols. |
---|
144 | n/a | CondMap = { |
---|
145 | n/a | C.Clamped: P.Clamped, |
---|
146 | n/a | C.ConversionSyntax: P.ConversionSyntax, |
---|
147 | n/a | C.DivisionByZero: P.DivisionByZero, |
---|
148 | n/a | C.DivisionImpossible: P.InvalidOperation, |
---|
149 | n/a | C.DivisionUndefined: P.DivisionUndefined, |
---|
150 | n/a | C.Inexact: P.Inexact, |
---|
151 | n/a | C.InvalidContext: P.InvalidContext, |
---|
152 | n/a | C.InvalidOperation: P.InvalidOperation, |
---|
153 | n/a | C.Overflow: P.Overflow, |
---|
154 | n/a | C.Rounded: P.Rounded, |
---|
155 | n/a | C.Subnormal: P.Subnormal, |
---|
156 | n/a | C.Underflow: P.Underflow, |
---|
157 | n/a | C.FloatOperation: P.FloatOperation, |
---|
158 | n/a | } |
---|
159 | n/a | |
---|
160 | n/a | RoundModes = [C.ROUND_UP, C.ROUND_DOWN, C.ROUND_CEILING, C.ROUND_FLOOR, |
---|
161 | n/a | C.ROUND_HALF_UP, C.ROUND_HALF_DOWN, C.ROUND_HALF_EVEN, |
---|
162 | n/a | C.ROUND_05UP] |
---|
163 | n/a | |
---|
164 | n/a | |
---|
165 | n/a | class Context(object): |
---|
166 | n/a | """Provides a convenient way of syncing the C and P contexts""" |
---|
167 | n/a | |
---|
168 | n/a | __slots__ = ['c', 'p'] |
---|
169 | n/a | |
---|
170 | n/a | def __init__(self, c_ctx=None, p_ctx=None): |
---|
171 | n/a | """Initialization is from the C context""" |
---|
172 | n/a | self.c = C.getcontext() if c_ctx is None else c_ctx |
---|
173 | n/a | self.p = P.getcontext() if p_ctx is None else p_ctx |
---|
174 | n/a | self.p.prec = self.c.prec |
---|
175 | n/a | self.p.Emin = self.c.Emin |
---|
176 | n/a | self.p.Emax = self.c.Emax |
---|
177 | n/a | self.p.rounding = self.c.rounding |
---|
178 | n/a | self.p.capitals = self.c.capitals |
---|
179 | n/a | self.settraps([sig for sig in self.c.traps if self.c.traps[sig]]) |
---|
180 | n/a | self.setstatus([sig for sig in self.c.flags if self.c.flags[sig]]) |
---|
181 | n/a | self.p.clamp = self.c.clamp |
---|
182 | n/a | |
---|
183 | n/a | def __str__(self): |
---|
184 | n/a | return str(self.c) + '\n' + str(self.p) |
---|
185 | n/a | |
---|
186 | n/a | def getprec(self): |
---|
187 | n/a | assert(self.c.prec == self.p.prec) |
---|
188 | n/a | return self.c.prec |
---|
189 | n/a | |
---|
190 | n/a | def setprec(self, val): |
---|
191 | n/a | self.c.prec = val |
---|
192 | n/a | self.p.prec = val |
---|
193 | n/a | |
---|
194 | n/a | def getemin(self): |
---|
195 | n/a | assert(self.c.Emin == self.p.Emin) |
---|
196 | n/a | return self.c.Emin |
---|
197 | n/a | |
---|
198 | n/a | def setemin(self, val): |
---|
199 | n/a | self.c.Emin = val |
---|
200 | n/a | self.p.Emin = val |
---|
201 | n/a | |
---|
202 | n/a | def getemax(self): |
---|
203 | n/a | assert(self.c.Emax == self.p.Emax) |
---|
204 | n/a | return self.c.Emax |
---|
205 | n/a | |
---|
206 | n/a | def setemax(self, val): |
---|
207 | n/a | self.c.Emax = val |
---|
208 | n/a | self.p.Emax = val |
---|
209 | n/a | |
---|
210 | n/a | def getround(self): |
---|
211 | n/a | assert(self.c.rounding == self.p.rounding) |
---|
212 | n/a | return self.c.rounding |
---|
213 | n/a | |
---|
214 | n/a | def setround(self, val): |
---|
215 | n/a | self.c.rounding = val |
---|
216 | n/a | self.p.rounding = val |
---|
217 | n/a | |
---|
218 | n/a | def getcapitals(self): |
---|
219 | n/a | assert(self.c.capitals == self.p.capitals) |
---|
220 | n/a | return self.c.capitals |
---|
221 | n/a | |
---|
222 | n/a | def setcapitals(self, val): |
---|
223 | n/a | self.c.capitals = val |
---|
224 | n/a | self.p.capitals = val |
---|
225 | n/a | |
---|
226 | n/a | def getclamp(self): |
---|
227 | n/a | assert(self.c.clamp == self.p.clamp) |
---|
228 | n/a | return self.c.clamp |
---|
229 | n/a | |
---|
230 | n/a | def setclamp(self, val): |
---|
231 | n/a | self.c.clamp = val |
---|
232 | n/a | self.p.clamp = val |
---|
233 | n/a | |
---|
234 | n/a | prec = property(getprec, setprec) |
---|
235 | n/a | Emin = property(getemin, setemin) |
---|
236 | n/a | Emax = property(getemax, setemax) |
---|
237 | n/a | rounding = property(getround, setround) |
---|
238 | n/a | clamp = property(getclamp, setclamp) |
---|
239 | n/a | capitals = property(getcapitals, setcapitals) |
---|
240 | n/a | |
---|
241 | n/a | def clear_traps(self): |
---|
242 | n/a | self.c.clear_traps() |
---|
243 | n/a | for trap in self.p.traps: |
---|
244 | n/a | self.p.traps[trap] = False |
---|
245 | n/a | |
---|
246 | n/a | def clear_status(self): |
---|
247 | n/a | self.c.clear_flags() |
---|
248 | n/a | self.p.clear_flags() |
---|
249 | n/a | |
---|
250 | n/a | def settraps(self, lst): |
---|
251 | n/a | """lst: C signal list""" |
---|
252 | n/a | self.clear_traps() |
---|
253 | n/a | for signal in lst: |
---|
254 | n/a | self.c.traps[signal] = True |
---|
255 | n/a | self.p.traps[CondMap[signal]] = True |
---|
256 | n/a | |
---|
257 | n/a | def setstatus(self, lst): |
---|
258 | n/a | """lst: C signal list""" |
---|
259 | n/a | self.clear_status() |
---|
260 | n/a | for signal in lst: |
---|
261 | n/a | self.c.flags[signal] = True |
---|
262 | n/a | self.p.flags[CondMap[signal]] = True |
---|
263 | n/a | |
---|
264 | n/a | def assert_eq_status(self): |
---|
265 | n/a | """assert equality of C and P status""" |
---|
266 | n/a | for signal in self.c.flags: |
---|
267 | n/a | if self.c.flags[signal] == (not self.p.flags[CondMap[signal]]): |
---|
268 | n/a | return False |
---|
269 | n/a | return True |
---|
270 | n/a | |
---|
271 | n/a | |
---|
272 | n/a | # We don't want exceptions so that we can compare the status flags. |
---|
273 | n/a | context = Context() |
---|
274 | n/a | context.Emin = C.MIN_EMIN |
---|
275 | n/a | context.Emax = C.MAX_EMAX |
---|
276 | n/a | context.clear_traps() |
---|
277 | n/a | |
---|
278 | n/a | # When creating decimals, _decimal is ultimately limited by the maximum |
---|
279 | n/a | # context values. We emulate this restriction for decimal.py. |
---|
280 | n/a | maxcontext = P.Context( |
---|
281 | n/a | prec=C.MAX_PREC, |
---|
282 | n/a | Emin=C.MIN_EMIN, |
---|
283 | n/a | Emax=C.MAX_EMAX, |
---|
284 | n/a | rounding=P.ROUND_HALF_UP, |
---|
285 | n/a | capitals=1 |
---|
286 | n/a | ) |
---|
287 | n/a | maxcontext.clamp = 0 |
---|
288 | n/a | |
---|
289 | n/a | def RestrictedDecimal(value): |
---|
290 | n/a | maxcontext.traps = copy(context.p.traps) |
---|
291 | n/a | maxcontext.clear_flags() |
---|
292 | n/a | if isinstance(value, str): |
---|
293 | n/a | value = value.strip() |
---|
294 | n/a | dec = maxcontext.create_decimal(value) |
---|
295 | n/a | if maxcontext.flags[P.Inexact] or \ |
---|
296 | n/a | maxcontext.flags[P.Rounded] or \ |
---|
297 | n/a | maxcontext.flags[P.Clamped] or \ |
---|
298 | n/a | maxcontext.flags[P.InvalidOperation]: |
---|
299 | n/a | return context.p._raise_error(P.InvalidOperation) |
---|
300 | n/a | if maxcontext.flags[P.FloatOperation]: |
---|
301 | n/a | context.p.flags[P.FloatOperation] = True |
---|
302 | n/a | return dec |
---|
303 | n/a | |
---|
304 | n/a | |
---|
305 | n/a | # ====================================================================== |
---|
306 | n/a | # TestSet: Organize data and events during a single test case |
---|
307 | n/a | # ====================================================================== |
---|
308 | n/a | |
---|
309 | n/a | class RestrictedList(list): |
---|
310 | n/a | """List that can only be modified by appending items.""" |
---|
311 | n/a | def __getattribute__(self, name): |
---|
312 | n/a | if name != 'append': |
---|
313 | n/a | raise AttributeError("unsupported operation") |
---|
314 | n/a | return list.__getattribute__(self, name) |
---|
315 | n/a | def unsupported(self, *_): |
---|
316 | n/a | raise AttributeError("unsupported operation") |
---|
317 | n/a | __add__ = __delattr__ = __delitem__ = __iadd__ = __imul__ = unsupported |
---|
318 | n/a | __mul__ = __reversed__ = __rmul__ = __setattr__ = __setitem__ = unsupported |
---|
319 | n/a | |
---|
320 | n/a | class TestSet(object): |
---|
321 | n/a | """A TestSet contains the original input operands, converted operands, |
---|
322 | n/a | Python exceptions that occurred either during conversion or during |
---|
323 | n/a | execution of the actual function, and the final results. |
---|
324 | n/a | |
---|
325 | n/a | For safety, most attributes are lists that only support the append |
---|
326 | n/a | operation. |
---|
327 | n/a | |
---|
328 | n/a | If a function name is prefixed with 'context.', the corresponding |
---|
329 | n/a | context method is called. |
---|
330 | n/a | """ |
---|
331 | n/a | def __init__(self, funcname, operands): |
---|
332 | n/a | if funcname.startswith("context."): |
---|
333 | n/a | self.funcname = funcname.replace("context.", "") |
---|
334 | n/a | self.contextfunc = True |
---|
335 | n/a | else: |
---|
336 | n/a | self.funcname = funcname |
---|
337 | n/a | self.contextfunc = False |
---|
338 | n/a | self.op = operands # raw operand tuple |
---|
339 | n/a | self.context = context # context used for the operation |
---|
340 | n/a | self.cop = RestrictedList() # converted C.Decimal operands |
---|
341 | n/a | self.cex = RestrictedList() # Python exceptions for C.Decimal |
---|
342 | n/a | self.cresults = RestrictedList() # C.Decimal results |
---|
343 | n/a | self.pop = RestrictedList() # converted P.Decimal operands |
---|
344 | n/a | self.pex = RestrictedList() # Python exceptions for P.Decimal |
---|
345 | n/a | self.presults = RestrictedList() # P.Decimal results |
---|
346 | n/a | |
---|
347 | n/a | |
---|
348 | n/a | # ====================================================================== |
---|
349 | n/a | # SkipHandler: skip known discrepancies |
---|
350 | n/a | # ====================================================================== |
---|
351 | n/a | |
---|
352 | n/a | class SkipHandler: |
---|
353 | n/a | """Handle known discrepancies between decimal.py and _decimal.so. |
---|
354 | n/a | These are either ULP differences in the power function or |
---|
355 | n/a | extremely minor issues.""" |
---|
356 | n/a | |
---|
357 | n/a | def __init__(self): |
---|
358 | n/a | self.ulpdiff = 0 |
---|
359 | n/a | self.powmod_zeros = 0 |
---|
360 | n/a | self.maxctx = P.Context(Emax=10**18, Emin=-10**18) |
---|
361 | n/a | |
---|
362 | n/a | def default(self, t): |
---|
363 | n/a | return False |
---|
364 | n/a | __ge__ = __gt__ = __le__ = __lt__ = __ne__ = __eq__ = default |
---|
365 | n/a | __reduce__ = __format__ = __repr__ = __str__ = default |
---|
366 | n/a | |
---|
367 | n/a | def harrison_ulp(self, dec): |
---|
368 | n/a | """ftp://ftp.inria.fr/INRIA/publication/publi-pdf/RR/RR-5504.pdf""" |
---|
369 | n/a | a = dec.next_plus() |
---|
370 | n/a | b = dec.next_minus() |
---|
371 | n/a | return abs(a - b) |
---|
372 | n/a | |
---|
373 | n/a | def standard_ulp(self, dec, prec): |
---|
374 | n/a | return _dec_from_triple(0, '1', dec._exp+len(dec._int)-prec) |
---|
375 | n/a | |
---|
376 | n/a | def rounding_direction(self, x, mode): |
---|
377 | n/a | """Determine the effective direction of the rounding when |
---|
378 | n/a | the exact result x is rounded according to mode. |
---|
379 | n/a | Return -1 for downwards, 0 for undirected, 1 for upwards, |
---|
380 | n/a | 2 for ROUND_05UP.""" |
---|
381 | n/a | cmp = 1 if x.compare_total(P.Decimal("+0")) >= 0 else -1 |
---|
382 | n/a | |
---|
383 | n/a | if mode in (P.ROUND_HALF_EVEN, P.ROUND_HALF_UP, P.ROUND_HALF_DOWN): |
---|
384 | n/a | return 0 |
---|
385 | n/a | elif mode == P.ROUND_CEILING: |
---|
386 | n/a | return 1 |
---|
387 | n/a | elif mode == P.ROUND_FLOOR: |
---|
388 | n/a | return -1 |
---|
389 | n/a | elif mode == P.ROUND_UP: |
---|
390 | n/a | return cmp |
---|
391 | n/a | elif mode == P.ROUND_DOWN: |
---|
392 | n/a | return -cmp |
---|
393 | n/a | elif mode == P.ROUND_05UP: |
---|
394 | n/a | return 2 |
---|
395 | n/a | else: |
---|
396 | n/a | raise ValueError("Unexpected rounding mode: %s" % mode) |
---|
397 | n/a | |
---|
398 | n/a | def check_ulpdiff(self, exact, rounded): |
---|
399 | n/a | # current precision |
---|
400 | n/a | p = context.p.prec |
---|
401 | n/a | |
---|
402 | n/a | # Convert infinities to the largest representable number + 1. |
---|
403 | n/a | x = exact |
---|
404 | n/a | if exact.is_infinite(): |
---|
405 | n/a | x = _dec_from_triple(exact._sign, '10', context.p.Emax) |
---|
406 | n/a | y = rounded |
---|
407 | n/a | if rounded.is_infinite(): |
---|
408 | n/a | y = _dec_from_triple(rounded._sign, '10', context.p.Emax) |
---|
409 | n/a | |
---|
410 | n/a | # err = (rounded - exact) / ulp(rounded) |
---|
411 | n/a | self.maxctx.prec = p * 2 |
---|
412 | n/a | t = self.maxctx.subtract(y, x) |
---|
413 | n/a | if context.c.flags[C.Clamped] or \ |
---|
414 | n/a | context.c.flags[C.Underflow]: |
---|
415 | n/a | # The standard ulp does not work in Underflow territory. |
---|
416 | n/a | ulp = self.harrison_ulp(y) |
---|
417 | n/a | else: |
---|
418 | n/a | ulp = self.standard_ulp(y, p) |
---|
419 | n/a | # Error in ulps. |
---|
420 | n/a | err = self.maxctx.divide(t, ulp) |
---|
421 | n/a | |
---|
422 | n/a | dir = self.rounding_direction(x, context.p.rounding) |
---|
423 | n/a | if dir == 0: |
---|
424 | n/a | if P.Decimal("-0.6") < err < P.Decimal("0.6"): |
---|
425 | n/a | return True |
---|
426 | n/a | elif dir == 1: # directed, upwards |
---|
427 | n/a | if P.Decimal("-0.1") < err < P.Decimal("1.1"): |
---|
428 | n/a | return True |
---|
429 | n/a | elif dir == -1: # directed, downwards |
---|
430 | n/a | if P.Decimal("-1.1") < err < P.Decimal("0.1"): |
---|
431 | n/a | return True |
---|
432 | n/a | else: # ROUND_05UP |
---|
433 | n/a | if P.Decimal("-1.1") < err < P.Decimal("1.1"): |
---|
434 | n/a | return True |
---|
435 | n/a | |
---|
436 | n/a | print("ulp: %s error: %s exact: %s c_rounded: %s" |
---|
437 | n/a | % (ulp, err, exact, rounded)) |
---|
438 | n/a | return False |
---|
439 | n/a | |
---|
440 | n/a | def bin_resolve_ulp(self, t): |
---|
441 | n/a | """Check if results of _decimal's power function are within the |
---|
442 | n/a | allowed ulp ranges.""" |
---|
443 | n/a | # NaNs are beyond repair. |
---|
444 | n/a | if t.rc.is_nan() or t.rp.is_nan(): |
---|
445 | n/a | return False |
---|
446 | n/a | |
---|
447 | n/a | # "exact" result, double precision, half_even |
---|
448 | n/a | self.maxctx.prec = context.p.prec * 2 |
---|
449 | n/a | |
---|
450 | n/a | op1, op2 = t.pop[0], t.pop[1] |
---|
451 | n/a | if t.contextfunc: |
---|
452 | n/a | exact = getattr(self.maxctx, t.funcname)(op1, op2) |
---|
453 | n/a | else: |
---|
454 | n/a | exact = getattr(op1, t.funcname)(op2, context=self.maxctx) |
---|
455 | n/a | |
---|
456 | n/a | # _decimal's rounded result |
---|
457 | n/a | rounded = P.Decimal(t.cresults[0]) |
---|
458 | n/a | |
---|
459 | n/a | self.ulpdiff += 1 |
---|
460 | n/a | return self.check_ulpdiff(exact, rounded) |
---|
461 | n/a | |
---|
462 | n/a | ############################ Correct rounding ############################# |
---|
463 | n/a | def resolve_underflow(self, t): |
---|
464 | n/a | """In extremely rare cases where the infinite precision result is just |
---|
465 | n/a | below etiny, cdecimal does not set Subnormal/Underflow. Example: |
---|
466 | n/a | |
---|
467 | n/a | setcontext(Context(prec=21, rounding=ROUND_UP, Emin=-55, Emax=85)) |
---|
468 | n/a | Decimal("1.00000000000000000000000000000000000000000000000" |
---|
469 | n/a | "0000000100000000000000000000000000000000000000000" |
---|
470 | n/a | "0000000000000025").ln() |
---|
471 | n/a | """ |
---|
472 | n/a | if t.cresults != t.presults: |
---|
473 | n/a | return False # Results must be identical. |
---|
474 | n/a | if context.c.flags[C.Rounded] and \ |
---|
475 | n/a | context.c.flags[C.Inexact] and \ |
---|
476 | n/a | context.p.flags[P.Rounded] and \ |
---|
477 | n/a | context.p.flags[P.Inexact]: |
---|
478 | n/a | return True # Subnormal/Underflow may be missing. |
---|
479 | n/a | return False |
---|
480 | n/a | |
---|
481 | n/a | def exp(self, t): |
---|
482 | n/a | """Resolve Underflow or ULP difference.""" |
---|
483 | n/a | return self.resolve_underflow(t) |
---|
484 | n/a | |
---|
485 | n/a | def log10(self, t): |
---|
486 | n/a | """Resolve Underflow or ULP difference.""" |
---|
487 | n/a | return self.resolve_underflow(t) |
---|
488 | n/a | |
---|
489 | n/a | def ln(self, t): |
---|
490 | n/a | """Resolve Underflow or ULP difference.""" |
---|
491 | n/a | return self.resolve_underflow(t) |
---|
492 | n/a | |
---|
493 | n/a | def __pow__(self, t): |
---|
494 | n/a | """Always calls the resolve function. C.Decimal does not have correct |
---|
495 | n/a | rounding for the power function.""" |
---|
496 | n/a | if context.c.flags[C.Rounded] and \ |
---|
497 | n/a | context.c.flags[C.Inexact] and \ |
---|
498 | n/a | context.p.flags[P.Rounded] and \ |
---|
499 | n/a | context.p.flags[P.Inexact]: |
---|
500 | n/a | return self.bin_resolve_ulp(t) |
---|
501 | n/a | else: |
---|
502 | n/a | return False |
---|
503 | n/a | power = __rpow__ = __pow__ |
---|
504 | n/a | |
---|
505 | n/a | ############################## Technicalities ############################# |
---|
506 | n/a | def __float__(self, t): |
---|
507 | n/a | """NaN comparison in the verify() function obviously gives an |
---|
508 | n/a | incorrect answer: nan == nan -> False""" |
---|
509 | n/a | if t.cop[0].is_nan() and t.pop[0].is_nan(): |
---|
510 | n/a | return True |
---|
511 | n/a | return False |
---|
512 | n/a | __complex__ = __float__ |
---|
513 | n/a | |
---|
514 | n/a | def __radd__(self, t): |
---|
515 | n/a | """decimal.py gives precedence to the first NaN; this is |
---|
516 | n/a | not important, as __radd__ will not be called for |
---|
517 | n/a | two decimal arguments.""" |
---|
518 | n/a | if t.rc.is_nan() and t.rp.is_nan(): |
---|
519 | n/a | return True |
---|
520 | n/a | return False |
---|
521 | n/a | __rmul__ = __radd__ |
---|
522 | n/a | |
---|
523 | n/a | ################################ Various ################################## |
---|
524 | n/a | def __round__(self, t): |
---|
525 | n/a | """Exception: Decimal('1').__round__(-100000000000000000000000000) |
---|
526 | n/a | Should it really be InvalidOperation?""" |
---|
527 | n/a | if t.rc is None and t.rp.is_nan(): |
---|
528 | n/a | return True |
---|
529 | n/a | return False |
---|
530 | n/a | |
---|
531 | n/a | shandler = SkipHandler() |
---|
532 | n/a | def skip_error(t): |
---|
533 | n/a | return getattr(shandler, t.funcname, shandler.default)(t) |
---|
534 | n/a | |
---|
535 | n/a | |
---|
536 | n/a | # ====================================================================== |
---|
537 | n/a | # Handling verification errors |
---|
538 | n/a | # ====================================================================== |
---|
539 | n/a | |
---|
540 | n/a | class VerifyError(Exception): |
---|
541 | n/a | """Verification failed.""" |
---|
542 | n/a | pass |
---|
543 | n/a | |
---|
544 | n/a | def function_as_string(t): |
---|
545 | n/a | if t.contextfunc: |
---|
546 | n/a | cargs = t.cop |
---|
547 | n/a | pargs = t.pop |
---|
548 | n/a | cfunc = "c_func: %s(" % t.funcname |
---|
549 | n/a | pfunc = "p_func: %s(" % t.funcname |
---|
550 | n/a | else: |
---|
551 | n/a | cself, cargs = t.cop[0], t.cop[1:] |
---|
552 | n/a | pself, pargs = t.pop[0], t.pop[1:] |
---|
553 | n/a | cfunc = "c_func: %s.%s(" % (repr(cself), t.funcname) |
---|
554 | n/a | pfunc = "p_func: %s.%s(" % (repr(pself), t.funcname) |
---|
555 | n/a | |
---|
556 | n/a | err = cfunc |
---|
557 | n/a | for arg in cargs: |
---|
558 | n/a | err += "%s, " % repr(arg) |
---|
559 | n/a | err = err.rstrip(", ") |
---|
560 | n/a | err += ")\n" |
---|
561 | n/a | |
---|
562 | n/a | err += pfunc |
---|
563 | n/a | for arg in pargs: |
---|
564 | n/a | err += "%s, " % repr(arg) |
---|
565 | n/a | err = err.rstrip(", ") |
---|
566 | n/a | err += ")" |
---|
567 | n/a | |
---|
568 | n/a | return err |
---|
569 | n/a | |
---|
570 | n/a | def raise_error(t): |
---|
571 | n/a | global EXIT_STATUS |
---|
572 | n/a | |
---|
573 | n/a | if skip_error(t): |
---|
574 | n/a | return |
---|
575 | n/a | EXIT_STATUS = 1 |
---|
576 | n/a | |
---|
577 | n/a | err = "Error in %s:\n\n" % t.funcname |
---|
578 | n/a | err += "input operands: %s\n\n" % (t.op,) |
---|
579 | n/a | err += function_as_string(t) |
---|
580 | n/a | err += "\n\nc_result: %s\np_result: %s\n\n" % (t.cresults, t.presults) |
---|
581 | n/a | err += "c_exceptions: %s\np_exceptions: %s\n\n" % (t.cex, t.pex) |
---|
582 | n/a | err += "%s\n\n" % str(t.context) |
---|
583 | n/a | |
---|
584 | n/a | raise VerifyError(err) |
---|
585 | n/a | |
---|
586 | n/a | |
---|
587 | n/a | # ====================================================================== |
---|
588 | n/a | # Main testing functions |
---|
589 | n/a | # |
---|
590 | n/a | # The procedure is always (t is the TestSet): |
---|
591 | n/a | # |
---|
592 | n/a | # convert(t) -> Initialize the TestSet as necessary. |
---|
593 | n/a | # |
---|
594 | n/a | # Return 0 for early abortion (e.g. if a TypeError |
---|
595 | n/a | # occurs during conversion, there is nothing to test). |
---|
596 | n/a | # |
---|
597 | n/a | # Return 1 for continuing with the test case. |
---|
598 | n/a | # |
---|
599 | n/a | # callfuncs(t) -> Call the relevant function for each implementation |
---|
600 | n/a | # and record the results in the TestSet. |
---|
601 | n/a | # |
---|
602 | n/a | # verify(t) -> Verify the results. If verification fails, details |
---|
603 | n/a | # are printed to stdout. |
---|
604 | n/a | # ====================================================================== |
---|
605 | n/a | |
---|
606 | n/a | def convert(t, convstr=True): |
---|
607 | n/a | """ t is the testset. At this stage the testset contains a tuple of |
---|
608 | n/a | operands t.op of various types. For decimal methods the first |
---|
609 | n/a | operand (self) is always converted to Decimal. If 'convstr' is |
---|
610 | n/a | true, string operands are converted as well. |
---|
611 | n/a | |
---|
612 | n/a | Context operands are of type deccheck.Context, rounding mode |
---|
613 | n/a | operands are given as a tuple (C.rounding, P.rounding). |
---|
614 | n/a | |
---|
615 | n/a | Other types (float, int, etc.) are left unchanged. |
---|
616 | n/a | """ |
---|
617 | n/a | for i, op in enumerate(t.op): |
---|
618 | n/a | |
---|
619 | n/a | context.clear_status() |
---|
620 | n/a | |
---|
621 | n/a | if op in RoundModes: |
---|
622 | n/a | t.cop.append(op) |
---|
623 | n/a | t.pop.append(op) |
---|
624 | n/a | |
---|
625 | n/a | elif not t.contextfunc and i == 0 or \ |
---|
626 | n/a | convstr and isinstance(op, str): |
---|
627 | n/a | try: |
---|
628 | n/a | c = C.Decimal(op) |
---|
629 | n/a | cex = None |
---|
630 | n/a | except (TypeError, ValueError, OverflowError) as e: |
---|
631 | n/a | c = None |
---|
632 | n/a | cex = e.__class__ |
---|
633 | n/a | |
---|
634 | n/a | try: |
---|
635 | n/a | p = RestrictedDecimal(op) |
---|
636 | n/a | pex = None |
---|
637 | n/a | except (TypeError, ValueError, OverflowError) as e: |
---|
638 | n/a | p = None |
---|
639 | n/a | pex = e.__class__ |
---|
640 | n/a | |
---|
641 | n/a | t.cop.append(c) |
---|
642 | n/a | t.cex.append(cex) |
---|
643 | n/a | t.pop.append(p) |
---|
644 | n/a | t.pex.append(pex) |
---|
645 | n/a | |
---|
646 | n/a | if cex is pex: |
---|
647 | n/a | if str(c) != str(p) or not context.assert_eq_status(): |
---|
648 | n/a | raise_error(t) |
---|
649 | n/a | if cex and pex: |
---|
650 | n/a | # nothing to test |
---|
651 | n/a | return 0 |
---|
652 | n/a | else: |
---|
653 | n/a | raise_error(t) |
---|
654 | n/a | |
---|
655 | n/a | elif isinstance(op, Context): |
---|
656 | n/a | t.context = op |
---|
657 | n/a | t.cop.append(op.c) |
---|
658 | n/a | t.pop.append(op.p) |
---|
659 | n/a | |
---|
660 | n/a | else: |
---|
661 | n/a | t.cop.append(op) |
---|
662 | n/a | t.pop.append(op) |
---|
663 | n/a | |
---|
664 | n/a | return 1 |
---|
665 | n/a | |
---|
666 | n/a | def callfuncs(t): |
---|
667 | n/a | """ t is the testset. At this stage the testset contains operand lists |
---|
668 | n/a | t.cop and t.pop for the C and Python versions of decimal. |
---|
669 | n/a | For Decimal methods, the first operands are of type C.Decimal and |
---|
670 | n/a | P.Decimal respectively. The remaining operands can have various types. |
---|
671 | n/a | For Context methods, all operands can have any type. |
---|
672 | n/a | |
---|
673 | n/a | t.rc and t.rp are the results of the operation. |
---|
674 | n/a | """ |
---|
675 | n/a | context.clear_status() |
---|
676 | n/a | |
---|
677 | n/a | try: |
---|
678 | n/a | if t.contextfunc: |
---|
679 | n/a | cargs = t.cop |
---|
680 | n/a | t.rc = getattr(context.c, t.funcname)(*cargs) |
---|
681 | n/a | else: |
---|
682 | n/a | cself = t.cop[0] |
---|
683 | n/a | cargs = t.cop[1:] |
---|
684 | n/a | t.rc = getattr(cself, t.funcname)(*cargs) |
---|
685 | n/a | t.cex.append(None) |
---|
686 | n/a | except (TypeError, ValueError, OverflowError, MemoryError) as e: |
---|
687 | n/a | t.rc = None |
---|
688 | n/a | t.cex.append(e.__class__) |
---|
689 | n/a | |
---|
690 | n/a | try: |
---|
691 | n/a | if t.contextfunc: |
---|
692 | n/a | pargs = t.pop |
---|
693 | n/a | t.rp = getattr(context.p, t.funcname)(*pargs) |
---|
694 | n/a | else: |
---|
695 | n/a | pself = t.pop[0] |
---|
696 | n/a | pargs = t.pop[1:] |
---|
697 | n/a | t.rp = getattr(pself, t.funcname)(*pargs) |
---|
698 | n/a | t.pex.append(None) |
---|
699 | n/a | except (TypeError, ValueError, OverflowError, MemoryError) as e: |
---|
700 | n/a | t.rp = None |
---|
701 | n/a | t.pex.append(e.__class__) |
---|
702 | n/a | |
---|
703 | n/a | def verify(t, stat): |
---|
704 | n/a | """ t is the testset. At this stage the testset contains the following |
---|
705 | n/a | tuples: |
---|
706 | n/a | |
---|
707 | n/a | t.op: original operands |
---|
708 | n/a | t.cop: C.Decimal operands (see convert for details) |
---|
709 | n/a | t.pop: P.Decimal operands (see convert for details) |
---|
710 | n/a | t.rc: C result |
---|
711 | n/a | t.rp: Python result |
---|
712 | n/a | |
---|
713 | n/a | t.rc and t.rp can have various types. |
---|
714 | n/a | """ |
---|
715 | n/a | t.cresults.append(str(t.rc)) |
---|
716 | n/a | t.presults.append(str(t.rp)) |
---|
717 | n/a | if isinstance(t.rc, C.Decimal) and isinstance(t.rp, P.Decimal): |
---|
718 | n/a | # General case: both results are Decimals. |
---|
719 | n/a | t.cresults.append(t.rc.to_eng_string()) |
---|
720 | n/a | t.cresults.append(t.rc.as_tuple()) |
---|
721 | n/a | t.cresults.append(str(t.rc.imag)) |
---|
722 | n/a | t.cresults.append(str(t.rc.real)) |
---|
723 | n/a | t.presults.append(t.rp.to_eng_string()) |
---|
724 | n/a | t.presults.append(t.rp.as_tuple()) |
---|
725 | n/a | t.presults.append(str(t.rp.imag)) |
---|
726 | n/a | t.presults.append(str(t.rp.real)) |
---|
727 | n/a | |
---|
728 | n/a | nc = t.rc.number_class().lstrip('+-s') |
---|
729 | n/a | stat[nc] += 1 |
---|
730 | n/a | else: |
---|
731 | n/a | # Results from e.g. __divmod__ can only be compared as strings. |
---|
732 | n/a | if not isinstance(t.rc, tuple) and not isinstance(t.rp, tuple): |
---|
733 | n/a | if t.rc != t.rp: |
---|
734 | n/a | raise_error(t) |
---|
735 | n/a | stat[type(t.rc).__name__] += 1 |
---|
736 | n/a | |
---|
737 | n/a | # The return value lists must be equal. |
---|
738 | n/a | if t.cresults != t.presults: |
---|
739 | n/a | raise_error(t) |
---|
740 | n/a | # The Python exception lists (TypeError, etc.) must be equal. |
---|
741 | n/a | if t.cex != t.pex: |
---|
742 | n/a | raise_error(t) |
---|
743 | n/a | # The context flags must be equal. |
---|
744 | n/a | if not t.context.assert_eq_status(): |
---|
745 | n/a | raise_error(t) |
---|
746 | n/a | |
---|
747 | n/a | |
---|
748 | n/a | # ====================================================================== |
---|
749 | n/a | # Main test loops |
---|
750 | n/a | # |
---|
751 | n/a | # test_method(method, testspecs, testfunc) -> |
---|
752 | n/a | # |
---|
753 | n/a | # Loop through various context settings. The degree of |
---|
754 | n/a | # thoroughness is determined by 'testspec'. For each |
---|
755 | n/a | # setting, call 'testfunc'. Generally, 'testfunc' itself |
---|
756 | n/a | # a loop, iterating through many test cases generated |
---|
757 | n/a | # by the functions in randdec.py. |
---|
758 | n/a | # |
---|
759 | n/a | # test_n-ary(method, prec, exp_range, restricted_range, itr, stat) -> |
---|
760 | n/a | # |
---|
761 | n/a | # 'test_unary', 'test_binary' and 'test_ternary' are the |
---|
762 | n/a | # main test functions passed to 'test_method'. They deal |
---|
763 | n/a | # with the regular cases. The thoroughness of testing is |
---|
764 | n/a | # determined by 'itr'. |
---|
765 | n/a | # |
---|
766 | n/a | # 'prec', 'exp_range' and 'restricted_range' are passed |
---|
767 | n/a | # to the test-generating functions and limit the generated |
---|
768 | n/a | # values. In some cases, for reasonable run times a |
---|
769 | n/a | # maximum exponent of 9999 is required. |
---|
770 | n/a | # |
---|
771 | n/a | # The 'stat' parameter is passed down to the 'verify' |
---|
772 | n/a | # function, which records statistics for the result values. |
---|
773 | n/a | # ====================================================================== |
---|
774 | n/a | |
---|
775 | n/a | def log(fmt, args=None): |
---|
776 | n/a | if args: |
---|
777 | n/a | sys.stdout.write(''.join((fmt, '\n')) % args) |
---|
778 | n/a | else: |
---|
779 | n/a | sys.stdout.write(''.join((str(fmt), '\n'))) |
---|
780 | n/a | sys.stdout.flush() |
---|
781 | n/a | |
---|
782 | n/a | def test_method(method, testspecs, testfunc): |
---|
783 | n/a | """Iterate a test function through many context settings.""" |
---|
784 | n/a | log("testing %s ...", method) |
---|
785 | n/a | stat = defaultdict(int) |
---|
786 | n/a | for spec in testspecs: |
---|
787 | n/a | if 'samples' in spec: |
---|
788 | n/a | spec['prec'] = sorted(random.sample(range(1, 101), |
---|
789 | n/a | spec['samples'])) |
---|
790 | n/a | for prec in spec['prec']: |
---|
791 | n/a | context.prec = prec |
---|
792 | n/a | for expts in spec['expts']: |
---|
793 | n/a | emin, emax = expts |
---|
794 | n/a | if emin == 'rand': |
---|
795 | n/a | context.Emin = random.randrange(-1000, 0) |
---|
796 | n/a | context.Emax = random.randrange(prec, 1000) |
---|
797 | n/a | else: |
---|
798 | n/a | context.Emin, context.Emax = emin, emax |
---|
799 | n/a | if prec > context.Emax: continue |
---|
800 | n/a | log(" prec: %d emin: %d emax: %d", |
---|
801 | n/a | (context.prec, context.Emin, context.Emax)) |
---|
802 | n/a | restr_range = 9999 if context.Emax > 9999 else context.Emax+99 |
---|
803 | n/a | for rounding in RoundModes: |
---|
804 | n/a | context.rounding = rounding |
---|
805 | n/a | context.capitals = random.randrange(2) |
---|
806 | n/a | if spec['clamp'] == 'rand': |
---|
807 | n/a | context.clamp = random.randrange(2) |
---|
808 | n/a | else: |
---|
809 | n/a | context.clamp = spec['clamp'] |
---|
810 | n/a | exprange = context.c.Emax |
---|
811 | n/a | testfunc(method, prec, exprange, restr_range, |
---|
812 | n/a | spec['iter'], stat) |
---|
813 | n/a | log(" result types: %s" % sorted([t for t in stat.items()])) |
---|
814 | n/a | |
---|
815 | n/a | def test_unary(method, prec, exp_range, restricted_range, itr, stat): |
---|
816 | n/a | """Iterate a unary function through many test cases.""" |
---|
817 | n/a | if method in UnaryRestricted: |
---|
818 | n/a | exp_range = restricted_range |
---|
819 | n/a | for op in all_unary(prec, exp_range, itr): |
---|
820 | n/a | t = TestSet(method, op) |
---|
821 | n/a | try: |
---|
822 | n/a | if not convert(t): |
---|
823 | n/a | continue |
---|
824 | n/a | callfuncs(t) |
---|
825 | n/a | verify(t, stat) |
---|
826 | n/a | except VerifyError as err: |
---|
827 | n/a | log(err) |
---|
828 | n/a | |
---|
829 | n/a | if not method.startswith('__'): |
---|
830 | n/a | for op in unary_optarg(prec, exp_range, itr): |
---|
831 | n/a | t = TestSet(method, op) |
---|
832 | n/a | try: |
---|
833 | n/a | if not convert(t): |
---|
834 | n/a | continue |
---|
835 | n/a | callfuncs(t) |
---|
836 | n/a | verify(t, stat) |
---|
837 | n/a | except VerifyError as err: |
---|
838 | n/a | log(err) |
---|
839 | n/a | |
---|
840 | n/a | def test_binary(method, prec, exp_range, restricted_range, itr, stat): |
---|
841 | n/a | """Iterate a binary function through many test cases.""" |
---|
842 | n/a | if method in BinaryRestricted: |
---|
843 | n/a | exp_range = restricted_range |
---|
844 | n/a | for op in all_binary(prec, exp_range, itr): |
---|
845 | n/a | t = TestSet(method, op) |
---|
846 | n/a | try: |
---|
847 | n/a | if not convert(t): |
---|
848 | n/a | continue |
---|
849 | n/a | callfuncs(t) |
---|
850 | n/a | verify(t, stat) |
---|
851 | n/a | except VerifyError as err: |
---|
852 | n/a | log(err) |
---|
853 | n/a | |
---|
854 | n/a | if not method.startswith('__'): |
---|
855 | n/a | for op in binary_optarg(prec, exp_range, itr): |
---|
856 | n/a | t = TestSet(method, op) |
---|
857 | n/a | try: |
---|
858 | n/a | if not convert(t): |
---|
859 | n/a | continue |
---|
860 | n/a | callfuncs(t) |
---|
861 | n/a | verify(t, stat) |
---|
862 | n/a | except VerifyError as err: |
---|
863 | n/a | log(err) |
---|
864 | n/a | |
---|
865 | n/a | def test_ternary(method, prec, exp_range, restricted_range, itr, stat): |
---|
866 | n/a | """Iterate a ternary function through many test cases.""" |
---|
867 | n/a | if method in TernaryRestricted: |
---|
868 | n/a | exp_range = restricted_range |
---|
869 | n/a | for op in all_ternary(prec, exp_range, itr): |
---|
870 | n/a | t = TestSet(method, op) |
---|
871 | n/a | try: |
---|
872 | n/a | if not convert(t): |
---|
873 | n/a | continue |
---|
874 | n/a | callfuncs(t) |
---|
875 | n/a | verify(t, stat) |
---|
876 | n/a | except VerifyError as err: |
---|
877 | n/a | log(err) |
---|
878 | n/a | |
---|
879 | n/a | if not method.startswith('__'): |
---|
880 | n/a | for op in ternary_optarg(prec, exp_range, itr): |
---|
881 | n/a | t = TestSet(method, op) |
---|
882 | n/a | try: |
---|
883 | n/a | if not convert(t): |
---|
884 | n/a | continue |
---|
885 | n/a | callfuncs(t) |
---|
886 | n/a | verify(t, stat) |
---|
887 | n/a | except VerifyError as err: |
---|
888 | n/a | log(err) |
---|
889 | n/a | |
---|
890 | n/a | def test_format(method, prec, exp_range, restricted_range, itr, stat): |
---|
891 | n/a | """Iterate the __format__ method through many test cases.""" |
---|
892 | n/a | for op in all_unary(prec, exp_range, itr): |
---|
893 | n/a | fmt1 = rand_format(chr(random.randrange(0, 128)), 'EeGgn') |
---|
894 | n/a | fmt2 = rand_locale() |
---|
895 | n/a | for fmt in (fmt1, fmt2): |
---|
896 | n/a | fmtop = (op[0], fmt) |
---|
897 | n/a | t = TestSet(method, fmtop) |
---|
898 | n/a | try: |
---|
899 | n/a | if not convert(t, convstr=False): |
---|
900 | n/a | continue |
---|
901 | n/a | callfuncs(t) |
---|
902 | n/a | verify(t, stat) |
---|
903 | n/a | except VerifyError as err: |
---|
904 | n/a | log(err) |
---|
905 | n/a | for op in all_unary(prec, 9999, itr): |
---|
906 | n/a | fmt1 = rand_format(chr(random.randrange(0, 128)), 'Ff%') |
---|
907 | n/a | fmt2 = rand_locale() |
---|
908 | n/a | for fmt in (fmt1, fmt2): |
---|
909 | n/a | fmtop = (op[0], fmt) |
---|
910 | n/a | t = TestSet(method, fmtop) |
---|
911 | n/a | try: |
---|
912 | n/a | if not convert(t, convstr=False): |
---|
913 | n/a | continue |
---|
914 | n/a | callfuncs(t) |
---|
915 | n/a | verify(t, stat) |
---|
916 | n/a | except VerifyError as err: |
---|
917 | n/a | log(err) |
---|
918 | n/a | |
---|
919 | n/a | def test_round(method, prec, exprange, restricted_range, itr, stat): |
---|
920 | n/a | """Iterate the __round__ method through many test cases.""" |
---|
921 | n/a | for op in all_unary(prec, 9999, itr): |
---|
922 | n/a | n = random.randrange(10) |
---|
923 | n/a | roundop = (op[0], n) |
---|
924 | n/a | t = TestSet(method, roundop) |
---|
925 | n/a | try: |
---|
926 | n/a | if not convert(t): |
---|
927 | n/a | continue |
---|
928 | n/a | callfuncs(t) |
---|
929 | n/a | verify(t, stat) |
---|
930 | n/a | except VerifyError as err: |
---|
931 | n/a | log(err) |
---|
932 | n/a | |
---|
933 | n/a | def test_from_float(method, prec, exprange, restricted_range, itr, stat): |
---|
934 | n/a | """Iterate the __float__ method through many test cases.""" |
---|
935 | n/a | for rounding in RoundModes: |
---|
936 | n/a | context.rounding = rounding |
---|
937 | n/a | for i in range(1000): |
---|
938 | n/a | f = randfloat() |
---|
939 | n/a | op = (f,) if method.startswith("context.") else ("sNaN", f) |
---|
940 | n/a | t = TestSet(method, op) |
---|
941 | n/a | try: |
---|
942 | n/a | if not convert(t): |
---|
943 | n/a | continue |
---|
944 | n/a | callfuncs(t) |
---|
945 | n/a | verify(t, stat) |
---|
946 | n/a | except VerifyError as err: |
---|
947 | n/a | log(err) |
---|
948 | n/a | |
---|
949 | n/a | def randcontext(exprange): |
---|
950 | n/a | c = Context(C.Context(), P.Context()) |
---|
951 | n/a | c.Emax = random.randrange(1, exprange+1) |
---|
952 | n/a | c.Emin = random.randrange(-exprange, 0) |
---|
953 | n/a | maxprec = 100 if c.Emax >= 100 else c.Emax |
---|
954 | n/a | c.prec = random.randrange(1, maxprec+1) |
---|
955 | n/a | c.clamp = random.randrange(2) |
---|
956 | n/a | c.clear_traps() |
---|
957 | n/a | return c |
---|
958 | n/a | |
---|
959 | n/a | def test_quantize_api(method, prec, exprange, restricted_range, itr, stat): |
---|
960 | n/a | """Iterate the 'quantize' method through many test cases, using |
---|
961 | n/a | the optional arguments.""" |
---|
962 | n/a | for op in all_binary(prec, restricted_range, itr): |
---|
963 | n/a | for rounding in RoundModes: |
---|
964 | n/a | c = randcontext(exprange) |
---|
965 | n/a | quantizeop = (op[0], op[1], rounding, c) |
---|
966 | n/a | t = TestSet(method, quantizeop) |
---|
967 | n/a | try: |
---|
968 | n/a | if not convert(t): |
---|
969 | n/a | continue |
---|
970 | n/a | callfuncs(t) |
---|
971 | n/a | verify(t, stat) |
---|
972 | n/a | except VerifyError as err: |
---|
973 | n/a | log(err) |
---|
974 | n/a | |
---|
975 | n/a | |
---|
976 | n/a | def check_untested(funcdict, c_cls, p_cls): |
---|
977 | n/a | """Determine untested, C-only and Python-only attributes. |
---|
978 | n/a | Uncomment print lines for debugging.""" |
---|
979 | n/a | c_attr = set(dir(c_cls)) |
---|
980 | n/a | p_attr = set(dir(p_cls)) |
---|
981 | n/a | intersect = c_attr & p_attr |
---|
982 | n/a | |
---|
983 | n/a | funcdict['c_only'] = tuple(sorted(c_attr-intersect)) |
---|
984 | n/a | funcdict['p_only'] = tuple(sorted(p_attr-intersect)) |
---|
985 | n/a | |
---|
986 | n/a | tested = set() |
---|
987 | n/a | for lst in funcdict.values(): |
---|
988 | n/a | for v in lst: |
---|
989 | n/a | v = v.replace("context.", "") if c_cls == C.Context else v |
---|
990 | n/a | tested.add(v) |
---|
991 | n/a | |
---|
992 | n/a | funcdict['untested'] = tuple(sorted(intersect-tested)) |
---|
993 | n/a | |
---|
994 | n/a | #for key in ('untested', 'c_only', 'p_only'): |
---|
995 | n/a | # s = 'Context' if c_cls == C.Context else 'Decimal' |
---|
996 | n/a | # print("\n%s %s:\n%s" % (s, key, funcdict[key])) |
---|
997 | n/a | |
---|
998 | n/a | |
---|
999 | n/a | if __name__ == '__main__': |
---|
1000 | n/a | |
---|
1001 | n/a | import time |
---|
1002 | n/a | |
---|
1003 | n/a | randseed = int(time.time()) |
---|
1004 | n/a | random.seed(randseed) |
---|
1005 | n/a | |
---|
1006 | n/a | # Set up the testspecs list. A testspec is simply a dictionary |
---|
1007 | n/a | # that determines the amount of different contexts that 'test_method' |
---|
1008 | n/a | # will generate. |
---|
1009 | n/a | base_expts = [(C.MIN_EMIN, C.MAX_EMAX)] |
---|
1010 | n/a | if C.MAX_EMAX == 999999999999999999: |
---|
1011 | n/a | base_expts.append((-999999999, 999999999)) |
---|
1012 | n/a | |
---|
1013 | n/a | # Basic contexts. |
---|
1014 | n/a | base = { |
---|
1015 | n/a | 'expts': base_expts, |
---|
1016 | n/a | 'prec': [], |
---|
1017 | n/a | 'clamp': 'rand', |
---|
1018 | n/a | 'iter': None, |
---|
1019 | n/a | 'samples': None, |
---|
1020 | n/a | } |
---|
1021 | n/a | # Contexts with small values for prec, emin, emax. |
---|
1022 | n/a | small = { |
---|
1023 | n/a | 'prec': [1, 2, 3, 4, 5], |
---|
1024 | n/a | 'expts': [(-1, 1), (-2, 2), (-3, 3), (-4, 4), (-5, 5)], |
---|
1025 | n/a | 'clamp': 'rand', |
---|
1026 | n/a | 'iter': None |
---|
1027 | n/a | } |
---|
1028 | n/a | # IEEE interchange format. |
---|
1029 | n/a | ieee = [ |
---|
1030 | n/a | # DECIMAL32 |
---|
1031 | n/a | {'prec': [7], 'expts': [(-95, 96)], 'clamp': 1, 'iter': None}, |
---|
1032 | n/a | # DECIMAL64 |
---|
1033 | n/a | {'prec': [16], 'expts': [(-383, 384)], 'clamp': 1, 'iter': None}, |
---|
1034 | n/a | # DECIMAL128 |
---|
1035 | n/a | {'prec': [34], 'expts': [(-6143, 6144)], 'clamp': 1, 'iter': None} |
---|
1036 | n/a | ] |
---|
1037 | n/a | |
---|
1038 | n/a | if '--medium' in sys.argv: |
---|
1039 | n/a | base['expts'].append(('rand', 'rand')) |
---|
1040 | n/a | # 5 random precisions |
---|
1041 | n/a | base['samples'] = 5 |
---|
1042 | n/a | testspecs = [small] + ieee + [base] |
---|
1043 | n/a | if '--long' in sys.argv: |
---|
1044 | n/a | base['expts'].append(('rand', 'rand')) |
---|
1045 | n/a | # 10 random precisions |
---|
1046 | n/a | base['samples'] = 10 |
---|
1047 | n/a | testspecs = [small] + ieee + [base] |
---|
1048 | n/a | elif '--all' in sys.argv: |
---|
1049 | n/a | base['expts'].append(('rand', 'rand')) |
---|
1050 | n/a | # All precisions in [1, 100] |
---|
1051 | n/a | base['samples'] = 100 |
---|
1052 | n/a | testspecs = [small] + ieee + [base] |
---|
1053 | n/a | else: # --short |
---|
1054 | n/a | rand_ieee = random.choice(ieee) |
---|
1055 | n/a | base['iter'] = small['iter'] = rand_ieee['iter'] = 1 |
---|
1056 | n/a | # 1 random precision and exponent pair |
---|
1057 | n/a | base['samples'] = 1 |
---|
1058 | n/a | base['expts'] = [random.choice(base_expts)] |
---|
1059 | n/a | # 1 random precision and exponent pair |
---|
1060 | n/a | prec = random.randrange(1, 6) |
---|
1061 | n/a | small['prec'] = [prec] |
---|
1062 | n/a | small['expts'] = [(-prec, prec)] |
---|
1063 | n/a | testspecs = [small, rand_ieee, base] |
---|
1064 | n/a | |
---|
1065 | n/a | check_untested(Functions, C.Decimal, P.Decimal) |
---|
1066 | n/a | check_untested(ContextFunctions, C.Context, P.Context) |
---|
1067 | n/a | |
---|
1068 | n/a | |
---|
1069 | n/a | log("\n\nRandom seed: %d\n\n", randseed) |
---|
1070 | n/a | |
---|
1071 | n/a | # Decimal methods: |
---|
1072 | n/a | for method in Functions['unary'] + Functions['unary_ctx'] + \ |
---|
1073 | n/a | Functions['unary_rnd_ctx']: |
---|
1074 | n/a | test_method(method, testspecs, test_unary) |
---|
1075 | n/a | |
---|
1076 | n/a | for method in Functions['binary'] + Functions['binary_ctx']: |
---|
1077 | n/a | test_method(method, testspecs, test_binary) |
---|
1078 | n/a | |
---|
1079 | n/a | for method in Functions['ternary'] + Functions['ternary_ctx']: |
---|
1080 | n/a | test_method(method, testspecs, test_ternary) |
---|
1081 | n/a | |
---|
1082 | n/a | test_method('__format__', testspecs, test_format) |
---|
1083 | n/a | test_method('__round__', testspecs, test_round) |
---|
1084 | n/a | test_method('from_float', testspecs, test_from_float) |
---|
1085 | n/a | test_method('quantize', testspecs, test_quantize_api) |
---|
1086 | n/a | |
---|
1087 | n/a | # Context methods: |
---|
1088 | n/a | for method in ContextFunctions['unary']: |
---|
1089 | n/a | test_method(method, testspecs, test_unary) |
---|
1090 | n/a | |
---|
1091 | n/a | for method in ContextFunctions['binary']: |
---|
1092 | n/a | test_method(method, testspecs, test_binary) |
---|
1093 | n/a | |
---|
1094 | n/a | for method in ContextFunctions['ternary']: |
---|
1095 | n/a | test_method(method, testspecs, test_ternary) |
---|
1096 | n/a | |
---|
1097 | n/a | test_method('context.create_decimal_from_float', testspecs, test_from_float) |
---|
1098 | n/a | |
---|
1099 | n/a | |
---|
1100 | n/a | sys.exit(EXIT_STATUS) |
---|