blob: d738b7314d38528f0e3409f654d4bd582f71ed45 [file] [log] [blame]
Mark Dickinson647ed912010-01-14 15:22:33 +00001# Tests for the correctly-rounded string -> float conversions
2# introduced in Python 2.7 and 3.1.
3
4import random
5import struct
6import unittest
7import re
8import sys
9from test import test_support
10
11# Correctly rounded str -> float in pure Python, for comparison.
12
13strtod_parser = re.compile(r""" # A numeric string consists of:
14 (?P<sign>[-+])? # an optional sign, followed by
15 (?=\d|\.\d) # a number with at least one digit
16 (?P<int>\d*) # having a (possibly empty) integer part
17 (?:\.(?P<frac>\d*))? # followed by an optional fractional part
18 (?:E(?P<exp>[-+]?\d+))? # and an optional exponent
19 \Z
20""", re.VERBOSE | re.IGNORECASE).match
21
22def strtod(s, mant_dig=53, min_exp = -1021, max_exp = 1024):
23 """Convert a finite decimal string to a hex string representing an
24 IEEE 754 binary64 float. Return 'inf' or '-inf' on overflow.
25 This function makes no use of floating-point arithmetic at any
26 stage."""
27
28 # parse string into a pair of integers 'a' and 'b' such that
29 # abs(decimal value) = a/b, along with a boolean 'negative'.
30 m = strtod_parser(s)
31 if m is None:
32 raise ValueError('invalid numeric string')
33 fraction = m.group('frac') or ''
34 intpart = int(m.group('int') + fraction)
35 exp = int(m.group('exp') or '0') - len(fraction)
36 negative = m.group('sign') == '-'
37 a, b = intpart*10**max(exp, 0), 10**max(0, -exp)
38
39 # quick return for zeros
40 if not a:
41 return '-0x0.0p+0' if negative else '0x0.0p+0'
42
43 # compute exponent e for result; may be one too small in the case
44 # that the rounded value of a/b lies in a different binade from a/b
45 d = a.bit_length() - b.bit_length()
46 d += (a >> d if d >= 0 else a << -d) >= b
47 e = max(d, min_exp) - mant_dig
48
49 # approximate a/b by number of the form q * 2**e; adjust e if necessary
50 a, b = a << max(-e, 0), b << max(e, 0)
51 q, r = divmod(a, b)
52 if 2*r > b or 2*r == b and q & 1:
53 q += 1
54 if q.bit_length() == mant_dig+1:
55 q //= 2
56 e += 1
57
58 # double check that (q, e) has the right form
59 assert q.bit_length() <= mant_dig and e >= min_exp - mant_dig
60 assert q.bit_length() == mant_dig or e == min_exp - mant_dig
61
62 # check for overflow and underflow
63 if e + q.bit_length() > max_exp:
64 return '-inf' if negative else 'inf'
65 if not q:
66 return '-0x0.0p+0' if negative else '0x0.0p+0'
67
68 # for hex representation, shift so # bits after point is a multiple of 4
69 hexdigs = 1 + (mant_dig-2)//4
70 shift = 3 - (mant_dig-2)%4
71 q, e = q << shift, e - shift
72 return '{}0x{:x}.{:0{}x}p{:+d}'.format(
73 '-' if negative else '',
74 q // 16**hexdigs,
75 q % 16**hexdigs,
76 hexdigs,
77 e + 4*hexdigs)
78
Mark Dickinsonab6ee7a2010-01-17 11:10:03 +000079TEST_SIZE = 16
Mark Dickinson647ed912010-01-14 15:22:33 +000080
81@unittest.skipUnless(getattr(sys, 'float_repr_style', '') == 'short',
82 "applies only when using short float repr style")
83class StrtodTests(unittest.TestCase):
84 def check_strtod(self, s):
85 """Compare the result of Python's builtin correctly rounded
86 string->float conversion (using float) to a pure Python
87 correctly rounded string->float implementation. Fail if the
88 two methods give different results."""
89
90 try:
91 fs = float(s)
92 except OverflowError:
93 got = '-inf' if s[0] == '-' else 'inf'
Mark Dickinsond87f22c2010-01-16 20:33:02 +000094 except MemoryError:
95 got = 'memory error'
Mark Dickinson647ed912010-01-14 15:22:33 +000096 else:
97 got = fs.hex()
98 expected = strtod(s)
99 self.assertEqual(expected, got,
100 "Incorrectly rounded str->float conversion for {}: "
101 "expected {}, got {}".format(s, expected, got))
102
Mark Dickinson294d6ac2010-01-21 17:02:53 +0000103 def test_short_halfway_cases(self):
104 # exact halfway cases with a small number of significant digits
105 for k in 0, 5, 10, 15, 20:
106 # upper = smallest integer >= 2**54/5**k
107 upper = -(-2**54/5**k)
108 # lower = smallest odd number >= 2**53/5**k
109 lower = -(-2**53/5**k)
110 if lower % 2 == 0:
111 lower += 1
112 for i in xrange(10 * TEST_SIZE):
113 # Select a random odd n in [2**53/5**k,
114 # 2**54/5**k). Then n * 10**k gives a halfway case
115 # with small number of significant digits.
116 n, e = random.randrange(lower, upper, 2), k
117
118 # Remove any additional powers of 5.
119 while n % 5 == 0:
120 n, e = n // 5, e + 1
121 assert n % 10 in (1, 3, 7, 9)
122
123 # Try numbers of the form n * 2**p2 * 10**e, p2 >= 0,
124 # until n * 2**p2 has more than 20 significant digits.
125 digits, exponent = n, e
126 while digits < 10**20:
127 s = '{}e{}'.format(digits, exponent)
128 self.check_strtod(s)
129 # Same again, but with extra trailing zeros.
130 s = '{}e{}'.format(digits * 10**40, exponent - 40)
131 self.check_strtod(s)
132 digits *= 2
133
134 # Try numbers of the form n * 5**p2 * 10**(e - p5), p5
135 # >= 0, with n * 5**p5 < 10**20.
136 digits, exponent = n, e
137 while digits < 10**20:
138 s = '{}e{}'.format(digits, exponent)
139 self.check_strtod(s)
140 # Same again, but with extra trailing zeros.
141 s = '{}e{}'.format(digits * 10**40, exponent - 40)
142 self.check_strtod(s)
143 digits *= 5
144 exponent -= 1
145
Mark Dickinson647ed912010-01-14 15:22:33 +0000146 def test_halfway_cases(self):
147 # test halfway cases for the round-half-to-even rule
148 for i in xrange(1000):
149 for j in xrange(TEST_SIZE):
150 # bit pattern for a random finite positive (or +0.0) float
151 bits = random.randrange(2047*2**52)
152
153 # convert bit pattern to a number of the form m * 2**e
154 e, m = divmod(bits, 2**52)
155 if e:
156 m, e = m + 2**52, e - 1
157 e -= 1074
158
159 # add 0.5 ulps
160 m, e = 2*m + 1, e - 1
161
162 # convert to a decimal string
163 if e >= 0:
164 digits = m << e
165 exponent = 0
166 else:
167 # m * 2**e = (m * 5**-e) * 10**e
168 digits = m * 5**-e
169 exponent = e
170 s = '{}e{}'.format(digits, exponent)
Mark Dickinson647ed912010-01-14 15:22:33 +0000171 self.check_strtod(s)
172
173 # get expected answer via struct, to triple check
174 #fs = struct.unpack('<d', struct.pack('<Q', bits + (bits&1)))[0]
175 #self.assertEqual(fs, float(s))
176
177 def test_boundaries(self):
178 # boundaries expressed as triples (n, e, u), where
179 # n*10**e is an approximation to the boundary value and
180 # u*10**e is 1ulp
181 boundaries = [
182 (10000000000000000000, -19, 1110), # a power of 2 boundary (1.0)
183 (17976931348623159077, 289, 1995), # overflow boundary (2.**1024)
184 (22250738585072013831, -327, 4941), # normal/subnormal (2.**-1022)
185 (0, -327, 4941), # zero
186 ]
187 for n, e, u in boundaries:
188 for j in xrange(1000):
189 for i in xrange(TEST_SIZE):
190 digits = n + random.randrange(-3*u, 3*u)
191 exponent = e
192 s = '{}e{}'.format(digits, exponent)
193 self.check_strtod(s)
194 n *= 10
195 u *= 10
196 e -= 1
197
198 def test_underflow_boundary(self):
199 # test values close to 2**-1075, the underflow boundary; similar
200 # to boundary_tests, except that the random error doesn't scale
201 # with n
202 for exponent in xrange(-400, -320):
203 base = 10**-exponent // 2**1075
204 for j in xrange(TEST_SIZE):
205 digits = base + random.randrange(-1000, 1000)
206 s = '{}e{}'.format(digits, exponent)
207 self.check_strtod(s)
208
209 def test_bigcomp(self):
Mark Dickinson4141d652010-01-20 17:36:31 +0000210 for ndigs in 5, 10, 14, 15, 16, 17, 18, 19, 20, 40, 41, 50:
211 dig10 = 10**ndigs
212 for i in xrange(100 * TEST_SIZE):
213 digits = random.randrange(dig10)
Mark Dickinson647ed912010-01-14 15:22:33 +0000214 exponent = random.randrange(-400, 400)
215 s = '{}e{}'.format(digits, exponent)
216 self.check_strtod(s)
217
218 def test_parsing(self):
Mark Dickinson811ff822010-01-16 17:57:49 +0000219 # make '0' more likely to be chosen than other digits
220 digits = '000000123456789'
Mark Dickinson647ed912010-01-14 15:22:33 +0000221 signs = ('+', '-', '')
222
223 # put together random short valid strings
224 # \d*[.\d*]?e
225 for i in xrange(1000):
226 for j in xrange(TEST_SIZE):
227 s = random.choice(signs)
228 intpart_len = random.randrange(5)
229 s += ''.join(random.choice(digits) for _ in xrange(intpart_len))
230 if random.choice([True, False]):
231 s += '.'
232 fracpart_len = random.randrange(5)
233 s += ''.join(random.choice(digits)
234 for _ in xrange(fracpart_len))
235 else:
236 fracpart_len = 0
237 if random.choice([True, False]):
238 s += random.choice(['e', 'E'])
239 s += random.choice(signs)
240 exponent_len = random.randrange(1, 4)
241 s += ''.join(random.choice(digits)
242 for _ in xrange(exponent_len))
243
244 if intpart_len + fracpart_len:
245 self.check_strtod(s)
246 else:
247 try:
248 float(s)
249 except ValueError:
250 pass
251 else:
252 assert False, "expected ValueError"
253
254 def test_particular(self):
255 # inputs that produced crashes or incorrectly rounded results with
256 # previous versions of dtoa.c, for various reasons
257 test_strings = [
258 # issue 7632 bug 1, originally reported failing case
259 '2183167012312112312312.23538020374420446192e-370',
260 # 5 instances of issue 7632 bug 2
261 '12579816049008305546974391768996369464963024663104e-357',
262 '17489628565202117263145367596028389348922981857013e-357',
263 '18487398785991994634182916638542680759613590482273e-357',
264 '32002864200581033134358724675198044527469366773928e-358',
265 '94393431193180696942841837085033647913224148539854e-358',
266 # failing case for bug introduced by METD in r77451 (attempted
267 # fix for issue 7632, bug 2), and fixed in r77482.
268 '28639097178261763178489759107321392745108491825303e-311',
269 # two numbers demonstrating a flaw in the bigcomp 'dig == 0'
270 # correction block (issue 7632, bug 3)
271 '1.00000000000000001e44',
272 '1.0000000000000000100000000000000000000001e44',
273 # dtoa.c bug for numbers just smaller than a power of 2 (issue
274 # 7632, bug 4)
275 '99999999999999994487665465554760717039532578546e-47',
276 # failing case for off-by-one error introduced by METD in
277 # r77483 (dtoa.c cleanup), fixed in r77490
278 '965437176333654931799035513671997118345570045914469' #...
279 '6213413350821416312194420007991306908470147322020121018368e0',
280 # incorrect lsb detection for round-half-to-even when
281 # bc->scale != 0 (issue 7632, bug 6).
282 '104308485241983990666713401708072175773165034278685' #...
283 '682646111762292409330928739751702404658197872319129' #...
284 '036519947435319418387839758990478549477777586673075' #...
285 '945844895981012024387992135617064532141489278815239' #...
286 '849108105951619997829153633535314849999674266169258' #...
287 '928940692239684771590065027025835804863585454872499' #...
288 '320500023126142553932654370362024104462255244034053' #...
289 '203998964360882487378334860197725139151265590832887' #...
290 '433736189468858614521708567646743455601905935595381' #...
291 '852723723645799866672558576993978025033590728687206' #...
292 '296379801363024094048327273913079612469982585674824' #...
293 '156000783167963081616214710691759864332339239688734' #...
294 '656548790656486646106983450809073750535624894296242' #...
295 '072010195710276073042036425579852459556183541199012' #...
296 '652571123898996574563824424330960027873516082763671875e-1075',
297 # demonstration that original fix for issue 7632 bug 1 was
298 # buggy; the exit condition was too strong
299 '247032822920623295e-341',
Mark Dickinson294d6ac2010-01-21 17:02:53 +0000300 # demonstrate similar problem to issue 7632 bug1: crash
301 # with 'oversized quotient in quorem' message.
302 '99037485700245683102805043437346965248029601286431e-373',
303 '99617639833743863161109961162881027406769510558457e-373',
304 '98852915025769345295749278351563179840130565591462e-372',
305 '99059944827693569659153042769690930905148015876788e-373',
306 '98914979205069368270421829889078356254059760327101e-372',
Mark Dickinson647ed912010-01-14 15:22:33 +0000307 # issue 7632 bug 5: the following 2 strings convert differently
308 '1000000000000000000000000000000000000000e-16',
Mark Dickinson811ff822010-01-16 17:57:49 +0000309 '10000000000000000000000000000000000000000e-17',
Mark Dickinson294d6ac2010-01-21 17:02:53 +0000310 # issue 7632 bug 7
311 '991633793189150720000000000000000000000000000000000000000e-33',
312 # And another, similar, failing halfway case
313 '4106250198039490000000000000000000000000000000000000000e-38',
Mark Dickinson476279f2010-01-16 10:44:00 +0000314 # issue 7632 bug 8: the following produced 10.0
315 '10.900000000000000012345678912345678912345',
Mark Dickinson4141d652010-01-20 17:36:31 +0000316 # exercise exit conditions in bigcomp comparison loop
317 '2602129298404963083833853479113577253105939995688e2',
318 '260212929840496308383385347911357725310593999568896e0',
319 '26021292984049630838338534791135772531059399956889601e-2',
320 '260212929840496308383385347911357725310593999568895e0',
321 '260212929840496308383385347911357725310593999568897e0',
322 '260212929840496308383385347911357725310593999568996e0',
323 '260212929840496308383385347911357725310593999568866e0',
324 # 2**53
325 '9007199254740992.00',
326 # 2**1024 - 2**970: exact overflow boundary. All values
327 # smaller than this should round to something finite; any value
328 # greater than or equal to this one overflows.
329 '179769313486231580793728971405303415079934132710037' #...
330 '826936173778980444968292764750946649017977587207096' #...
331 '330286416692887910946555547851940402630657488671505' #...
332 '820681908902000708383676273854845817711531764475730' #...
333 '270069855571366959622842914819860834936475292719074' #...
334 '168444365510704342711559699508093042880177904174497792',
335 # 2**1024 - 2**970 - tiny
336 '179769313486231580793728971405303415079934132710037' #...
337 '826936173778980444968292764750946649017977587207096' #...
338 '330286416692887910946555547851940402630657488671505' #...
339 '820681908902000708383676273854845817711531764475730' #...
340 '270069855571366959622842914819860834936475292719074' #...
341 '168444365510704342711559699508093042880177904174497791.999',
342 # 2**1024 - 2**970 + tiny
343 '179769313486231580793728971405303415079934132710037' #...
344 '826936173778980444968292764750946649017977587207096' #...
345 '330286416692887910946555547851940402630657488671505' #...
346 '820681908902000708383676273854845817711531764475730' #...
347 '270069855571366959622842914819860834936475292719074' #...
348 '168444365510704342711559699508093042880177904174497792.001',
349 # 1 - 2**-54, +-tiny
350 '999999999999999944488848768742172978818416595458984375e-54',
351 '9999999999999999444888487687421729788184165954589843749999999e-54',
352 '9999999999999999444888487687421729788184165954589843750000001e-54',
Mark Dickinson647ed912010-01-14 15:22:33 +0000353 ]
354 for s in test_strings:
355 self.check_strtod(s)
356
357def test_main():
358 test_support.run_unittest(StrtodTests)
359
360if __name__ == "__main__":
361 test_main()