blob: e99693c768d7aeb0776512e6e92b3f059ebe6ae9 [file] [log] [blame]
Mark Dickinson853c3bb2010-01-14 15:37:49 +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
9import test.support
10
Mark Dickinson7b26d7f2010-02-07 20:32:50 +000011if getattr(sys, 'float_repr_style', '') != 'short':
12 raise unittest.SkipTest('correctly-rounded string->float conversions '
13 'not available on this system')
14
Mark Dickinson853c3bb2010-01-14 15:37:49 +000015# Correctly rounded str -> float in pure Python, for comparison.
16
17strtod_parser = re.compile(r""" # A numeric string consists of:
18 (?P<sign>[-+])? # an optional sign, followed by
19 (?=\d|\.\d) # a number with at least one digit
20 (?P<int>\d*) # having a (possibly empty) integer part
21 (?:\.(?P<frac>\d*))? # followed by an optional fractional part
22 (?:E(?P<exp>[-+]?\d+))? # and an optional exponent
23 \Z
24""", re.VERBOSE | re.IGNORECASE).match
25
26def strtod(s, mant_dig=53, min_exp = -1021, max_exp = 1024):
27 """Convert a finite decimal string to a hex string representing an
28 IEEE 754 binary64 float. Return 'inf' or '-inf' on overflow.
29 This function makes no use of floating-point arithmetic at any
30 stage."""
31
32 # parse string into a pair of integers 'a' and 'b' such that
33 # abs(decimal value) = a/b, along with a boolean 'negative'.
34 m = strtod_parser(s)
35 if m is None:
36 raise ValueError('invalid numeric string')
37 fraction = m.group('frac') or ''
38 intpart = int(m.group('int') + fraction)
39 exp = int(m.group('exp') or '0') - len(fraction)
40 negative = m.group('sign') == '-'
41 a, b = intpart*10**max(exp, 0), 10**max(0, -exp)
42
43 # quick return for zeros
44 if not a:
45 return '-0x0.0p+0' if negative else '0x0.0p+0'
46
47 # compute exponent e for result; may be one too small in the case
48 # that the rounded value of a/b lies in a different binade from a/b
49 d = a.bit_length() - b.bit_length()
50 d += (a >> d if d >= 0 else a << -d) >= b
51 e = max(d, min_exp) - mant_dig
52
53 # approximate a/b by number of the form q * 2**e; adjust e if necessary
54 a, b = a << max(-e, 0), b << max(e, 0)
55 q, r = divmod(a, b)
56 if 2*r > b or 2*r == b and q & 1:
57 q += 1
58 if q.bit_length() == mant_dig+1:
59 q //= 2
60 e += 1
61
62 # double check that (q, e) has the right form
63 assert q.bit_length() <= mant_dig and e >= min_exp - mant_dig
64 assert q.bit_length() == mant_dig or e == min_exp - mant_dig
65
66 # check for overflow and underflow
67 if e + q.bit_length() > max_exp:
68 return '-inf' if negative else 'inf'
69 if not q:
70 return '-0x0.0p+0' if negative else '0x0.0p+0'
71
72 # for hex representation, shift so # bits after point is a multiple of 4
73 hexdigs = 1 + (mant_dig-2)//4
74 shift = 3 - (mant_dig-2)%4
75 q, e = q << shift, e - shift
76 return '{}0x{:x}.{:0{}x}p{:+d}'.format(
77 '-' if negative else '',
78 q // 16**hexdigs,
79 q % 16**hexdigs,
80 hexdigs,
81 e + 4*hexdigs)
82
Mark Dickinsond0ff7832010-02-21 14:49:52 +000083TEST_SIZE = 10
Mark Dickinson853c3bb2010-01-14 15:37:49 +000084
Mark Dickinson853c3bb2010-01-14 15:37:49 +000085class StrtodTests(unittest.TestCase):
86 def check_strtod(self, s):
87 """Compare the result of Python's builtin correctly rounded
88 string->float conversion (using float) to a pure Python
89 correctly rounded string->float implementation. Fail if the
90 two methods give different results."""
91
92 try:
93 fs = float(s)
94 except OverflowError:
95 got = '-inf' if s[0] == '-' else 'inf'
Mark Dickinson1c7d69b2010-01-16 20:34:30 +000096 except MemoryError:
97 got = 'memory error'
Mark Dickinson853c3bb2010-01-14 15:37:49 +000098 else:
99 got = fs.hex()
100 expected = strtod(s)
101 self.assertEqual(expected, got,
102 "Incorrectly rounded str->float conversion for {}: "
103 "expected {}, got {}".format(s, expected, got))
104
Mark Dickinsonadd28232010-01-21 19:51:08 +0000105 def test_short_halfway_cases(self):
106 # exact halfway cases with a small number of significant digits
107 for k in 0, 5, 10, 15, 20:
108 # upper = smallest integer >= 2**54/5**k
109 upper = -(-2**54//5**k)
110 # lower = smallest odd number >= 2**53/5**k
111 lower = -(-2**53//5**k)
112 if lower % 2 == 0:
113 lower += 1
Mark Dickinsond0ff7832010-02-21 14:49:52 +0000114 for i in range(TEST_SIZE):
Mark Dickinsonadd28232010-01-21 19:51:08 +0000115 # Select a random odd n in [2**53/5**k,
116 # 2**54/5**k). Then n * 10**k gives a halfway case
117 # with small number of significant digits.
118 n, e = random.randrange(lower, upper, 2), k
119
120 # Remove any additional powers of 5.
121 while n % 5 == 0:
122 n, e = n // 5, e + 1
123 assert n % 10 in (1, 3, 7, 9)
124
125 # Try numbers of the form n * 2**p2 * 10**e, p2 >= 0,
126 # until n * 2**p2 has more than 20 significant digits.
127 digits, exponent = n, e
128 while digits < 10**20:
129 s = '{}e{}'.format(digits, exponent)
130 self.check_strtod(s)
131 # Same again, but with extra trailing zeros.
132 s = '{}e{}'.format(digits * 10**40, exponent - 40)
133 self.check_strtod(s)
134 digits *= 2
135
136 # Try numbers of the form n * 5**p2 * 10**(e - p5), p5
137 # >= 0, with n * 5**p5 < 10**20.
138 digits, exponent = n, e
139 while digits < 10**20:
140 s = '{}e{}'.format(digits, exponent)
141 self.check_strtod(s)
142 # Same again, but with extra trailing zeros.
143 s = '{}e{}'.format(digits * 10**40, exponent - 40)
144 self.check_strtod(s)
145 digits *= 5
146 exponent -= 1
147
Mark Dickinson853c3bb2010-01-14 15:37:49 +0000148 def test_halfway_cases(self):
149 # test halfway cases for the round-half-to-even rule
Mark Dickinsond0ff7832010-02-21 14:49:52 +0000150 for i in range(100 * TEST_SIZE):
151 # bit pattern for a random finite positive (or +0.0) float
152 bits = random.randrange(2047*2**52)
Mark Dickinson853c3bb2010-01-14 15:37:49 +0000153
Mark Dickinsond0ff7832010-02-21 14:49:52 +0000154 # convert bit pattern to a number of the form m * 2**e
155 e, m = divmod(bits, 2**52)
156 if e:
157 m, e = m + 2**52, e - 1
158 e -= 1074
Mark Dickinson853c3bb2010-01-14 15:37:49 +0000159
Mark Dickinsond0ff7832010-02-21 14:49:52 +0000160 # add 0.5 ulps
161 m, e = 2*m + 1, e - 1
Mark Dickinson853c3bb2010-01-14 15:37:49 +0000162
Mark Dickinsond0ff7832010-02-21 14:49:52 +0000163 # convert to a decimal string
164 if e >= 0:
165 digits = m << e
166 exponent = 0
167 else:
168 # m * 2**e = (m * 5**-e) * 10**e
169 digits = m * 5**-e
170 exponent = e
171 s = '{}e{}'.format(digits, exponent)
172 self.check_strtod(s)
Mark Dickinson853c3bb2010-01-14 15:37:49 +0000173
174 def test_boundaries(self):
175 # boundaries expressed as triples (n, e, u), where
176 # n*10**e is an approximation to the boundary value and
177 # u*10**e is 1ulp
178 boundaries = [
179 (10000000000000000000, -19, 1110), # a power of 2 boundary (1.0)
180 (17976931348623159077, 289, 1995), # overflow boundary (2.**1024)
181 (22250738585072013831, -327, 4941), # normal/subnormal (2.**-1022)
182 (0, -327, 4941), # zero
183 ]
184 for n, e, u in boundaries:
185 for j in range(1000):
Mark Dickinsond0ff7832010-02-21 14:49:52 +0000186 digits = n + random.randrange(-3*u, 3*u)
187 exponent = e
188 s = '{}e{}'.format(digits, exponent)
189 self.check_strtod(s)
Mark Dickinson853c3bb2010-01-14 15:37:49 +0000190 n *= 10
191 u *= 10
192 e -= 1
193
194 def test_underflow_boundary(self):
195 # test values close to 2**-1075, the underflow boundary; similar
196 # to boundary_tests, except that the random error doesn't scale
197 # with n
198 for exponent in range(-400, -320):
199 base = 10**-exponent // 2**1075
200 for j in range(TEST_SIZE):
201 digits = base + random.randrange(-1000, 1000)
202 s = '{}e{}'.format(digits, exponent)
203 self.check_strtod(s)
204
205 def test_bigcomp(self):
Mark Dickinsonadd28232010-01-21 19:51:08 +0000206 for ndigs in 5, 10, 14, 15, 16, 17, 18, 19, 20, 40, 41, 50:
207 dig10 = 10**ndigs
Mark Dickinsond0ff7832010-02-21 14:49:52 +0000208 for i in range(10 * TEST_SIZE):
Mark Dickinsonadd28232010-01-21 19:51:08 +0000209 digits = random.randrange(dig10)
Mark Dickinson853c3bb2010-01-14 15:37:49 +0000210 exponent = random.randrange(-400, 400)
211 s = '{}e{}'.format(digits, exponent)
212 self.check_strtod(s)
213
214 def test_parsing(self):
Mark Dickinson45b63652010-01-16 18:10:25 +0000215 # make '0' more likely to be chosen than other digits
216 digits = '000000123456789'
Mark Dickinson853c3bb2010-01-14 15:37:49 +0000217 signs = ('+', '-', '')
218
219 # put together random short valid strings
220 # \d*[.\d*]?e
221 for i in range(1000):
222 for j in range(TEST_SIZE):
223 s = random.choice(signs)
224 intpart_len = random.randrange(5)
225 s += ''.join(random.choice(digits) for _ in range(intpart_len))
226 if random.choice([True, False]):
227 s += '.'
228 fracpart_len = random.randrange(5)
229 s += ''.join(random.choice(digits)
230 for _ in range(fracpart_len))
231 else:
232 fracpart_len = 0
233 if random.choice([True, False]):
234 s += random.choice(['e', 'E'])
235 s += random.choice(signs)
236 exponent_len = random.randrange(1, 4)
237 s += ''.join(random.choice(digits)
238 for _ in range(exponent_len))
239
240 if intpart_len + fracpart_len:
241 self.check_strtod(s)
242 else:
243 try:
244 float(s)
245 except ValueError:
246 pass
247 else:
248 assert False, "expected ValueError"
249
250 def test_particular(self):
251 # inputs that produced crashes or incorrectly rounded results with
252 # previous versions of dtoa.c, for various reasons
253 test_strings = [
254 # issue 7632 bug 1, originally reported failing case
255 '2183167012312112312312.23538020374420446192e-370',
256 # 5 instances of issue 7632 bug 2
257 '12579816049008305546974391768996369464963024663104e-357',
258 '17489628565202117263145367596028389348922981857013e-357',
259 '18487398785991994634182916638542680759613590482273e-357',
260 '32002864200581033134358724675198044527469366773928e-358',
261 '94393431193180696942841837085033647913224148539854e-358',
262 # failing case for bug introduced by METD in r77451 (attempted
263 # fix for issue 7632, bug 2), and fixed in r77482.
264 '28639097178261763178489759107321392745108491825303e-311',
265 # two numbers demonstrating a flaw in the bigcomp 'dig == 0'
266 # correction block (issue 7632, bug 3)
267 '1.00000000000000001e44',
268 '1.0000000000000000100000000000000000000001e44',
269 # dtoa.c bug for numbers just smaller than a power of 2 (issue
270 # 7632, bug 4)
271 '99999999999999994487665465554760717039532578546e-47',
272 # failing case for off-by-one error introduced by METD in
273 # r77483 (dtoa.c cleanup), fixed in r77490
274 '965437176333654931799035513671997118345570045914469' #...
275 '6213413350821416312194420007991306908470147322020121018368e0',
276 # incorrect lsb detection for round-half-to-even when
277 # bc->scale != 0 (issue 7632, bug 6).
278 '104308485241983990666713401708072175773165034278685' #...
279 '682646111762292409330928739751702404658197872319129' #...
280 '036519947435319418387839758990478549477777586673075' #...
281 '945844895981012024387992135617064532141489278815239' #...
282 '849108105951619997829153633535314849999674266169258' #...
283 '928940692239684771590065027025835804863585454872499' #...
284 '320500023126142553932654370362024104462255244034053' #...
285 '203998964360882487378334860197725139151265590832887' #...
286 '433736189468858614521708567646743455601905935595381' #...
287 '852723723645799866672558576993978025033590728687206' #...
288 '296379801363024094048327273913079612469982585674824' #...
289 '156000783167963081616214710691759864332339239688734' #...
290 '656548790656486646106983450809073750535624894296242' #...
291 '072010195710276073042036425579852459556183541199012' #...
292 '652571123898996574563824424330960027873516082763671875e-1075',
293 # demonstration that original fix for issue 7632 bug 1 was
294 # buggy; the exit condition was too strong
295 '247032822920623295e-341',
Mark Dickinsonadd28232010-01-21 19:51:08 +0000296 # demonstrate similar problem to issue 7632 bug1: crash
297 # with 'oversized quotient in quorem' message.
298 '99037485700245683102805043437346965248029601286431e-373',
299 '99617639833743863161109961162881027406769510558457e-373',
300 '98852915025769345295749278351563179840130565591462e-372',
301 '99059944827693569659153042769690930905148015876788e-373',
302 '98914979205069368270421829889078356254059760327101e-372',
Mark Dickinson853c3bb2010-01-14 15:37:49 +0000303 # issue 7632 bug 5: the following 2 strings convert differently
304 '1000000000000000000000000000000000000000e-16',
Mark Dickinson45b63652010-01-16 18:10:25 +0000305 '10000000000000000000000000000000000000000e-17',
Mark Dickinsonadd28232010-01-21 19:51:08 +0000306 # issue 7632 bug 7
307 '991633793189150720000000000000000000000000000000000000000e-33',
308 # And another, similar, failing halfway case
309 '4106250198039490000000000000000000000000000000000000000e-38',
Mark Dickinson45b63652010-01-16 18:10:25 +0000310 # issue 7632 bug 8: the following produced 10.0
311 '10.900000000000000012345678912345678912345',
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +0000312
313 # two humongous values from issue 7743
314 '116512874940594195638617907092569881519034793229385' #...
315 '228569165191541890846564669771714896916084883987920' #...
316 '473321268100296857636200926065340769682863349205363' #...
317 '349247637660671783209907949273683040397979984107806' #...
318 '461822693332712828397617946036239581632976585100633' #...
319 '520260770761060725403904123144384571612073732754774' #...
320 '588211944406465572591022081973828448927338602556287' #...
321 '851831745419397433012491884869454462440536895047499' #...
322 '436551974649731917170099387762871020403582994193439' #...
323 '761933412166821484015883631622539314203799034497982' #...
324 '130038741741727907429575673302461380386596501187482' #...
325 '006257527709842179336488381672818798450229339123527' #...
326 '858844448336815912020452294624916993546388956561522' #...
327 '161875352572590420823607478788399460162228308693742' #...
328 '05287663441403533948204085390898399055004119873046875e-1075',
329
330 '525440653352955266109661060358202819561258984964913' #...
331 '892256527849758956045218257059713765874251436193619' #...
332 '443248205998870001633865657517447355992225852945912' #...
333 '016668660000210283807209850662224417504752264995360' #...
334 '631512007753855801075373057632157738752800840302596' #...
335 '237050247910530538250008682272783660778181628040733' #...
336 '653121492436408812668023478001208529190359254322340' #...
337 '397575185248844788515410722958784640926528544043090' #...
338 '115352513640884988017342469275006999104519620946430' #...
339 '818767147966495485406577703972687838176778993472989' #...
340 '561959000047036638938396333146685137903018376496408' #...
341 '319705333868476925297317136513970189073693314710318' #...
342 '991252811050501448326875232850600451776091303043715' #...
343 '157191292827614046876950225714743118291034780466325' #...
344 '085141343734564915193426994587206432697337118211527' #...
345 '278968731294639353354774788602467795167875117481660' #...
346 '4738791256853675690543663283782215866825e-1180',
347
Mark Dickinsonadd28232010-01-21 19:51:08 +0000348 # exercise exit conditions in bigcomp comparison loop
349 '2602129298404963083833853479113577253105939995688e2',
350 '260212929840496308383385347911357725310593999568896e0',
351 '26021292984049630838338534791135772531059399956889601e-2',
352 '260212929840496308383385347911357725310593999568895e0',
353 '260212929840496308383385347911357725310593999568897e0',
354 '260212929840496308383385347911357725310593999568996e0',
355 '260212929840496308383385347911357725310593999568866e0',
356 # 2**53
357 '9007199254740992.00',
358 # 2**1024 - 2**970: exact overflow boundary. All values
359 # smaller than this should round to something finite; any value
360 # greater than or equal to this one overflows.
361 '179769313486231580793728971405303415079934132710037' #...
362 '826936173778980444968292764750946649017977587207096' #...
363 '330286416692887910946555547851940402630657488671505' #...
364 '820681908902000708383676273854845817711531764475730' #...
365 '270069855571366959622842914819860834936475292719074' #...
366 '168444365510704342711559699508093042880177904174497792',
367 # 2**1024 - 2**970 - tiny
368 '179769313486231580793728971405303415079934132710037' #...
369 '826936173778980444968292764750946649017977587207096' #...
370 '330286416692887910946555547851940402630657488671505' #...
371 '820681908902000708383676273854845817711531764475730' #...
372 '270069855571366959622842914819860834936475292719074' #...
373 '168444365510704342711559699508093042880177904174497791.999',
374 # 2**1024 - 2**970 + tiny
375 '179769313486231580793728971405303415079934132710037' #...
376 '826936173778980444968292764750946649017977587207096' #...
377 '330286416692887910946555547851940402630657488671505' #...
378 '820681908902000708383676273854845817711531764475730' #...
379 '270069855571366959622842914819860834936475292719074' #...
380 '168444365510704342711559699508093042880177904174497792.001',
381 # 1 - 2**-54, +-tiny
382 '999999999999999944488848768742172978818416595458984375e-54',
383 '9999999999999999444888487687421729788184165954589843749999999e-54',
384 '9999999999999999444888487687421729788184165954589843750000001e-54',
Mark Dickinson853c3bb2010-01-14 15:37:49 +0000385 ]
386 for s in test_strings:
387 self.check_strtod(s)
388
389def test_main():
390 test.support.run_unittest(StrtodTests)
391
392if __name__ == "__main__":
393 test_main()