1# check cases converting float to int, relying only on single precision float
2
3try:
4    import ustruct as struct
5    import usys as sys
6except:
7    import struct
8    import sys
9
10maxsize_bits = 0
11maxsize = sys.maxsize
12while maxsize:
13    maxsize >>= 1
14    maxsize_bits += 1
15
16# work out configuration values
17is_64bit = maxsize_bits > 32
18# 0 = none, 1 = long long, 2 = mpz
19ll_type = None
20if is_64bit:
21    if maxsize_bits < 63:
22        ll_type = 0
23else:
24    if maxsize_bits < 31:
25        ll_type = 0
26if ll_type is None:
27    one = 1
28    if one << 65 < one << 62:
29        ll_type = 1
30    else:
31        ll_type = 2
32
33# basic conversion
34print(int(14187744.0))
35print("%d" % 14187744.0)
36if ll_type == 2:
37    print(int(2.0 ** 100))
38    print("%d" % 2.0 ** 100)
39
40testpass = True
41p2_rng = ((30, 63, 127), (62, 63, 127))[is_64bit][ll_type]
42for i in range(0, p2_rng):
43    bitcnt = len(bin(int(2.0 ** i))) - 3
44    if i != bitcnt:
45        print("fail: 2.**%u was %u bits long" % (i, bitcnt))
46        testpass = False
47print("power of  2 test: %s" % (testpass and "passed" or "failed"))
48
49# TODO why does 10**12 fail this test for single precision float?
50testpass = True
51p10_rng = 9
52for i in range(0, p10_rng):
53    digcnt = len(str(int(10.0 ** i))) - 1
54    if i != digcnt:
55        print("fail: 10.**%u was %u digits long" % (i, digcnt))
56        testpass = False
57print("power of 10 test: %s" % (testpass and "passed" or "failed"))
58
59
60def fp2int_test(num, name, should_fail):
61    try:
62        x = int(num)
63        passed = ~should_fail
64    except:
65        passed = should_fail
66    print("%s: %s" % (name, passed and "passed" or "failed"))
67
68
69if ll_type != 2:
70    if ll_type == 0:
71        if is_64bit:
72            neg_bad_fp = -1.00000005 * 2.0 ** 62.0
73            pos_bad_fp = 2.0 ** 62.0
74            neg_good_fp = -(2.0 ** 62.0)
75            pos_good_fp = 0.99999993 * 2.0 ** 62.0
76        else:
77            neg_bad_fp = -1.00000005 * 2.0 ** 30.0
78            pos_bad_fp = 2.0 ** 30.0
79            neg_good_fp = -(2.0 ** 30.0)
80            pos_good_fp = 0.9999999499 * 2.0 ** 30.0
81    else:
82        neg_bad_fp = -0.51 * 2.0 ** 64.0
83        pos_bad_fp = 2.0 ** 63.0
84        neg_good_fp = -(2.0 ** 63.0)
85        pos_good_fp = 1.9999998 * 2.0 ** 62.0
86
87    fp2int_test(neg_bad_fp, "neg bad", True)
88    fp2int_test(pos_bad_fp, "pos bad", True)
89    fp2int_test(neg_good_fp, "neg good", False)
90    fp2int_test(pos_good_fp, "pos good", False)
91else:
92    fp2int_test(-1.999999879 * 2.0 ** 126.0, "large neg", False)
93    fp2int_test(1.999999879 * 2.0 ** 126.0, "large pos", False)
94
95fp2int_test(float("inf"), "inf test", True)
96fp2int_test(float("-inf"), "inf test", True)
97fp2int_test(float("nan"), "NaN test", True)
98
99# test numbers < 1 (this used to fail; see issue #1044)
100fp2int_test(0.0001, "small num", False)
101struct.pack("I", int(1 / 2))
102