Search code examples
pythonfloating-pointbinaryfloating

Binary representation of small float values in Python


How can I convert small float values such as 1.942890293094024e-15 or 2.8665157186802404e-07 to binary values in Python?

I tried GeeksforGeek's solution, however, it does not work for values this small (I get this error: ValueError: invalid literal for int() with base 10: '1.942890293094024e-15').

The code looks like this so far:

def float_bin(number, places = 3): 

    # split() seperates whole number and decimal  
    # part and stores it in two seperate variables 
    whole, dec = str(number).split(".") 

    # Convert both whole number and decimal   
    # part from string type to integer type 
    whole = int(whole) 
    dec = int (dec) 

    # Convert the whole number part to it's 
    # respective binary form and remove the 
    # "0b" from it. 
    res = bin(whole).lstrip("0b") + "."

    # Iterate the number of times, we want 
    # the number of decimal places to be 
    for x in range(places): 

        # Multiply the decimal value by 2  
        # and seperate the whole number part 
        # and decimal part 
        whole, dec = str((decimal_converter(dec)) * 2).split(".") 

        # Convert the decimal part 
        # to integer again 
        dec = int(dec) 

        # Keep adding the integer parts  
        # receive to the result variable 
        res += whole 

    return res 


# Function converts the value passed as 
# parameter to it's decimal representation 
def decimal_converter(num):  
  while num > 1: 
      num /= 10
  return num 

Solution

  • After some consultation, I found a good piece of code that solves my problem. I just had to apply some little tweaks on it (making it a function, removing automatic input requests etc.).

    Huge thanks to @kartoon!