1# check cases converting float to int, requiring double 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# This case occurs with time.time() values 34if ll_type != 0: 35 print(int(1418774543.0)) 36 print("%d" % 1418774543.0) 37 if ll_type == 3: 38 print(int(2.0 ** 100)) 39 print("%d" % 2.0 ** 100) 40else: 41 print(int(1073741823.0)) 42 print("%d" % 1073741823.0) 43 44testpass = True 45p2_rng = ((30, 63, 1024), (62, 63, 1024))[is_64bit][ll_type] 46for i in range(0, p2_rng): 47 bitcnt = len(bin(int(2.0 ** i))) - 3 48 if i != bitcnt: 49 print("fail: 2**%u was %u bits long" % (i, bitcnt)) 50 testpass = False 51print("power of 2 test: %s" % (testpass and "passed" or "failed")) 52 53testpass = True 54p10_rng = ((9, 18, 23), (18, 18, 23))[is_64bit][ll_type] 55for i in range(0, p10_rng): 56 digcnt = len(str(int(10.0 ** i))) - 1 57 if i != digcnt: 58 print("fail: 10**%u was %u digits long" % (i, digcnt)) 59 testpass = False 60print("power of 10 test: %s" % (testpass and "passed" or "failed")) 61 62 63def fp2int_test(num, name, should_fail): 64 try: 65 x = int(num) 66 passed = ~should_fail 67 except: 68 passed = should_fail 69 print("%s: %s" % (name, passed and "passed" or "failed")) 70 71 72if ll_type != 2: 73 if ll_type == 0: 74 if is_64bit: 75 neg_bad_fp = -1.00000005 * 2.0 ** 62.0 76 pos_bad_fp = 2.0 ** 62.0 77 neg_good_fp = -(2.0 ** 62.0) 78 pos_good_fp = 0.99999993 * 2.0 ** 62.0 79 else: 80 neg_bad_fp = -1.00000005 * 2.0 ** 30.0 81 pos_bad_fp = 2.0 ** 30.0 82 neg_good_fp = -(2.0 ** 30.0) 83 pos_good_fp = 0.9999999499 * 2.0 ** 30.0 84 else: 85 neg_bad_fp = -0.51 * 2.0 ** 64.0 86 pos_bad_fp = 2.0 ** 63.0 87 neg_good_fp = -(2.0 ** 63.0) 88 pos_good_fp = 1.9999998 * 2.0 ** 62.0 89 90 fp2int_test(neg_bad_fp, "neg bad", True) 91 fp2int_test(pos_bad_fp, "pos bad", True) 92 fp2int_test(neg_good_fp, "neg good", False) 93 fp2int_test(pos_good_fp, "pos good", False) 94else: 95 fp2int_test(-1.9999999999999981 * 2.0 ** 1023.0, "large neg", False) 96 fp2int_test(1.9999999999999981 * 2.0 ** 1023.0, "large pos", False) 97 98fp2int_test(float("inf"), "inf test", True) 99fp2int_test(float("-inf"), "inf test", True) 100fp2int_test(float("nan"), "NaN test", True) 101 102# test numbers < 1 (this used to fail; see issue #1044) 103fp2int_test(0.0001, "small num", False) 104struct.pack("I", int(1 / 2)) 105