Python float精度问题

我在编写一段二进制转换程序时,输出二进制数字位数在17位及以上就会有错误发生,不是系统报错,就是数字不再是“1010”之类的,会变成十进制其他数字。十六位及以下的数都没问题,所以我猜测是float或强转int出现精度问题,但我不知道怎么改。

import math
import decimal

testNum = input("Enter a positive decimal integer:")
binaryNum = 0
if testNum.isdigit():  # Test if input string is number or not.
    decimalNum = float(testNum)
    digitRecord = decimalNum
    digit = 0
    binaryNum = 0
    if decimalNum != 0 and decimalNum - (decimalNum // 1) == 0:
        while digitRecord >= 1:  # Calculate the binary digit
            digitRecord /= 2
            digit += 1
        while digit != 0:  # Minus the calculated part of decimal number. Add number into the binary number.
            decimalNum -= math.pow(2, digit - 1)
            binaryNum += math.pow(10, digit - 1)
            digitRecord = decimalNum
            digit = 0
            while digitRecord >= 1:  # Recalculate the binary digit
                digitRecord /= 2
                digit += 1
        print("Binary number is ", int(decimal.Decimal(binaryNum)))
    elif decimalNum - (decimalNum // 1) != 0:
        print("Please enter a positive decimal integer.")
    elif decimalNum == 0:
        print("Binary number is 0")
    else:
        print("Please enter a positive decimal integer.")
else:
    print("Please enter a positive decimal integer.")

有解决办法吗

建议你使用高精度计算来解决这个问题