【问题标题】:Binary representation of small float values in PythonPython中小浮点值的二进制表示
【发布时间】:2020-08-07 07:26:11
【问题描述】:

如何在 Python 中将 1.942890293094024e-152.8665157186802404e-07 等小浮点值转换为二进制值?

我试过GeeksforGeek's solution,但是,它不适用于这么小的值(我收到此错误:ValueError: invalid literal for int() with base 10: '1.942890293094024e-15' )。

目前的代码如下所示:

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 

【问题讨论】:

  • 什么不起作用?您可以复制粘贴代码(最小工作示例)和错误消息吗?
  • 我收到此错误:ValueError: invalid literal for int() with base 10: '1.942890293094024e-15'。我把代码放到这个问题上。
  • 看看这个trinket。您可能需要进行一些调整。
  • 我调整了您发送的代码,它可以工作!非常感谢! @kartoon
  • 干得好!如果您发布自己问题的答案以帮助其他需要帮助的人,那将是非常棒的。

标签: python floating-point binary floating


【解决方案1】:

我看到的一个问题是str(number).split(".")。在此之前我添加了一个简单的技巧:number = "{:30f}".format(number),因此数量上没有e。不过,我不确定结果是否正确。

【讨论】:

  • 当我这样做时,我看到 1.942890293094024e-15(数字)为 0.000000 :(
  • 对我来说似乎很合理。 2e-15 非常接近于 0。
  • 但是,我无法进行近似。我需要一个二进制表达式而不是 0。此外,当将此 sn-p 添加到代码中时,我收到此错误:ValueError: not enough values to unpack (expected 2, got 1)
  • 很可能 decimal_converter() 返回 int 而不是 float。请更好地描述您当前的问题。
【解决方案2】:

经过一番咨询,我找到了一个很好的piece of code,可以解决我的问题。我只需要对其进行一些小调整(使其成为一项功能,删除自动输入请求等)。

非常感谢@kartoon!

【讨论】:

    猜你喜欢
    • 2016-05-01
    • 2018-04-10
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 2013-05-02
    相关资源
    最近更新 更多