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 34# basic conversion 35# fmt: off 36print(int(14187745.)) 37print("%d" % 14187745.) 38# fmt: on 39if ll_type == 2: 40 print(int(2.0 ** 100)) 41 print("%d" % 2.0 ** 100) 42 43testpass = True 44p2_rng = ((30, 63, 127), (62, 63, 127))[is_64bit][ll_type] 45for i in range(0, p2_rng): 46 bitcnt = len(bin(int(2.0 ** i))) - 3 47 if i != bitcnt: 48 print("fail: 2.**%u was %u bits long" % (i, bitcnt)) 49 testpass = False 50print("power of 2 test: %s" % (testpass and "passed" or "failed")) 51 52# TODO why does 10**12 fail this test for single precision float? 53testpass = True 54p10_rng = 9 if (ll_type == 0 and ~is_64bit) else 11 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.999999879 * 2.0 ** 127.0, "large neg", False) 96 fp2int_test(1.999999879 * 2.0 ** 127.0, "large pos", False) 97 98fp2int_test(float("inf"), "inf test", True) 99fp2int_test(float("nan"), "NaN test", True) 100 101# test numbers < 1 (this used to fail; see issue #1044) 102fp2int_test(0.0001, "small num", False) 103struct.pack("I", int(1 / 2)) 104